From 01ad0367e194a662e6839be1b97dfaa1c08aca9a Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:44:00 +0200 Subject: [PATCH 01/36] feat(antigravity): managed releases can be the agy CLI or the paired server Scient's installer and its setup actions now accept either kind of catalog release. The agy CLI counts as newer than every paired release, so a paired install is offered the CLI as its update, while an installed CLI is never offered a paired release, not even as a repair. The update says the user signs in to Google again: the CLI keeps its own sign-in. Running paired sessions keep their leased copy until they exit. Co-Authored-By: Claude Opus 5.5 --- .../provider/AntigravityInstallation.test.ts | 50 ++++++++ .../src/provider/AntigravityInstallation.ts | 38 +++--- .../AntigravityAcpLifecycleActions.test.ts | 98 ++++++++++++++++ .../AntigravityAcpLifecycleActions.ts | 108 ++++++++++++------ .../antigravityRuntimeRelease.ts | 74 ++++++++++++ 5 files changed, 320 insertions(+), 48 deletions(-) create mode 100644 apps/server/src/scient/providerLifecycle/antigravityRuntimeRelease.ts diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 2c4cc3cbd8..bf577ec889 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -353,6 +353,56 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst }), ); + // SCIENT-FORK: Scient's catalog moves a paired install to the agy CLI, never back. + it.effect( + "switches a paired install to the agy CLI while its running session keeps its copy", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const digest = yield* Digest.Digest; + const paired = { ...(yield* releaseAsset()), registryVersion: "1.5.2" }; + const first = yield* makeHarness({ asset: paired }); + yield* first.installation.startRelease(paired); + expect((yield* terminalState(first.installation)).phase).toBe("succeeded"); + yield* Deferred.await(first.stagingReleased); + + const second = yield* makeHarness({ + baseDir: first.baseDir, + asset: paired, + archive: nativeCliArchive, + }); + const scope = yield* Scope.make(); + const session = yield* second.installation.acquire().pipe(Scope.provide(scope)); + expect(session.harnessPath).not.toBeNull(); + const cli = { + version: "1.5.14", + url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.14-1/linux-x64/cli_linux_x64.tar.gz", + sha512: Hex.encode( + yield* digest.digest(Digest.sha512, nativeCliArchive).pipe(Effect.orDie), + ), + executable: { name: hostPlatform === "win32" ? "agy.exe" : "antigravity" }, + format: hostPlatform === "win32" ? ("executable" as const) : ("tar.gz" as const), + }; + yield* second.installation.startRelease(cli); + expect(yield* terminalState(second.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.14", + }); + yield* Deferred.await(second.stagingReleased); + expect(yield* second.installation.resolve()).toMatchObject({ + harnessPath: null, + version: "1.5.14", + source: "managed", + }); + expect(yield* fs.exists(session.executablePath)).toBe(true); + yield* Scope.close(scope, Exit.void); + + const refused = yield* second.installation.startRelease(paired).pipe(Effect.flip); + expect(refused.message).toContain("newer Antigravity runtime is already installed"); + expect((yield* second.installation.resolve()).harnessPath).toBeNull(); + }), + ); + it.effect("does not join a different immutable artifact with the same version label", () => Effect.gen(function* () { const entered = yield* Deferred.make(); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index 8fe57a5053..82b4a1ab08 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -16,7 +16,6 @@ import { type ServerProviderCompatibilityAdvisory, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { isManagedRuntimeUpdate } from "@scientfactory/provider-runtime"; import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime"; import { resolveCommandPath } from "@t3tools/shared/shell"; import * as Clock from "effect/Clock"; @@ -61,6 +60,14 @@ import { prepareAntigravityProfile, } from "./antigravityAuthSupport.ts"; import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; +// SCIENT-FORK:START — the catalog's release may be the paired server or the agy CLI. +import { + antigravityReleaseId, + antigravityReleaseIdentity, + supersedesAntigravityRelease, + type AntigravityManagedRelease, +} from "../scient/providerLifecycle/antigravityRuntimeRelease.ts"; +// SCIENT-FORK:END const DRIVER = ProviderDriverKind.make("antigravity"); const DOWNLOAD_TIMEOUT = "45 minutes"; @@ -130,9 +137,9 @@ export interface AntigravityExecutable { interface AntigravityInstallationService { readonly managedDirectory: string; - readonly latestRelease: Effect.Effect; + readonly latestRelease: Effect.Effect; /** Bounded catalog refresh for explicit install, update, or repair. */ - readonly refreshLatestRelease: Effect.Effect; + readonly refreshLatestRelease: Effect.Effect; readonly resolve: ( binaryPath?: string, environment?: NodeJS.ProcessEnv, @@ -148,7 +155,7 @@ interface AntigravityInstallationService { readonly start: Effect.Effect; /** Install the exact locally-qualified release the user reviewed. */ readonly startRelease: ( - asset: AntigravityReleaseAsset, + asset: AntigravityManagedRelease, ) => Effect.Effect; readonly cancel: ( operationId: string, @@ -185,8 +192,8 @@ export interface AntigravityInstallationOptions { readonly baseDir: string; readonly releaseAsset?: AntigravityReleaseAsset | AntigravityCliReleaseAsset | null; // SCIENT-FORK:START — Scient's qualified catalog supplies the release to install. - readonly latestRelease?: Effect.Effect; - readonly refreshLatestRelease?: Effect.Effect; + readonly latestRelease?: Effect.Effect; + readonly refreshLatestRelease?: Effect.Effect; // SCIENT-FORK:END readonly updateChecksEnabled?: Effect.Effect; readonly validate?: ( @@ -1650,13 +1657,14 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma }).pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation."))); // SCIENT-FORK:START — install the exact locally-qualified release the user reviewed. - const startRelease = (asset: AntigravityReleaseAsset) => + const startRelease = (asset: AntigravityManagedRelease) => gate .withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); + const releaseId = antigravityReleaseId(asset); if (isRunning(current)) { - if (current.version === asset.version && running?.releaseId === asset.sha256) + if (current.version === asset.version && running?.releaseId === releaseId) return current; return yield* installationError( "start", @@ -1674,12 +1682,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); if ( Option.isSome(activeRecord) && - asset.registryVersion && - activeRecord.value.registryVersion && - isManagedRuntimeUpdate({ - provider: "antigravityAcp", - current: asset.registryVersion, - candidate: activeRecord.value.registryVersion, + supersedesAntigravityRelease(antigravityReleaseIdentity(asset), { + cli: activeRecord.value.harness === null, + version: activeRecord.value.version, + registryVersion: activeRecord.value.registryVersion, }) ) { return yield* installationError( @@ -1693,7 +1699,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma operationId, phase: "downloading", downloadedBytes: 0, - totalBytes: asset.archiveBytes, + totalBytes: "sha256" in asset ? asset.archiveBytes : null, version: asset.version, installedVersion: current.installedVersion, canRemove: current.canRemove, @@ -1728,7 +1734,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ); const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope); - running = { operationId, releaseId: asset.sha256, fiber }; + running = { operationId, releaseId, fiber }; return next; }).pipe(Effect.uninterruptible), ) diff --git a/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.test.ts b/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.test.ts index 3f46e06782..85145773ee 100644 --- a/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.test.ts +++ b/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.test.ts @@ -21,6 +21,7 @@ import { bundledAntigravityAcpAsset, } from "./antigravityAcpCatalog.ts"; import { ANTIGRAVITY_SESSION_SETUP_FAILED_MESSAGE } from "./antigravityAuthDiagnostics.ts"; +import type { AntigravityManagedRelease } from "./antigravityRuntimeRelease.ts"; const instanceId = ProviderInstanceId.make("antigravity-lifecycle-test"); const driver = ProviderDriverKind.make("antigravity"); @@ -419,6 +420,103 @@ it.effect("never removes a managed runtime when its repair download or verificat }), ); +it.effect("offers the agy CLI as the update for a paired runtime and never back again", () => + Effect.gen(function* () { + const paired = bundledAntigravityAcpAsset("linux", "x64")!; + const cliRelease = (version: string) => ({ + version, + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-1/linux-x64/cli_linux_x64.tar.gz`, + sha512: version.replaceAll(".", "").padEnd(128, "a"), + archiveBytes: 56_000_000, + executable: { name: "antigravity" }, + format: "tar.gz" as const, + }); + const state = { + latest: cliRelease("1.5.14") as AntigravityManagedRelease, + installed: { + harnessPath: "/managed/localharness_external" as string | null, + version: "1.4.5", + }, + }; + const started: AntigravityManagedRelease[] = []; + const installation = AntigravityInstallation.of({ + managedDirectory: "/managed/antigravity", + compatibility: () => Effect.undefined, + latestRelease: Effect.sync(() => state.latest), + refreshLatestRelease: Effect.sync(() => state.latest), + resolve: () => + Effect.sync(() => ({ + executablePath: "/managed/runtime", + harnessPath: state.installed.harnessPath, + source: "managed" as const, + version: state.installed.version, + managedVersionDirectory: "/managed/antigravity/versions/current", + })), + acquire: () => Effect.die("not used"), + start: Effect.die("Use the exact reviewed release"), + startRelease: (asset) => + Effect.sync(() => { + started.push(asset); + return installState("downloading", { operationId: "switch", version: asset.version }); + }), + checkForUpdate: Effect.void, + cancel: () => Effect.die("not used"), + state: Effect.sync(() => installState("idle", { installedVersion: state.installed.version })), + changes: Stream.make(installState("succeeded", { operationId: "switch" })), + remove: () => Effect.die("not used"), + }); + const actions = makeAntigravityManagedRuntimeActions({ + installation, + settings: { + enabled: true, + authMethod: "oauth-personal", + apiKey: "", + gcpProject: "", + gcpLocation: "", + binaryPath: "", + customModels: [], + }, + environment: {}, + platform: "linux", + arch: "x64", + protectedBinaryPaths: Effect.succeed([]), + }); + + const fromPaired = yield* actions.getSummary; + expect(fromPaired).toMatchObject({ + actions: ["update", "repair", "remove"], + availableManagedVersion: "1.5.14", + }); + expect(fromPaired.message).toContain("sign in to Google again"); + const plan = yield* actions.plan("update"); + expect(plan).toMatchObject({ + version: "1.5.14", + downloadBytes: 56_000_000, + sourceLabel: "Official Google Antigravity CLI release", + catalogRevision: `antigravity-cli:1.5.14:${cliRelease("1.5.14").sha512}`, + }); + expect(plan.message).toContain("sign in to Google again"); + yield* actions.run("update", plan.catalogRevision, () => Effect.void, Effect.void); + expect(started).toEqual([cliRelease("1.5.14")]); + + // An installed CLI is never offered the paired release, not even as a repair. + state.installed = { harnessPath: null, version: "1.5.14" }; + state.latest = paired; + expect(yield* actions.getSummary).toMatchObject({ + actions: ["remove"], + availableManagedVersion: null, + }); + // A newer CLI is an ordinary update; the same one is a repair. + state.latest = cliRelease("1.5.20"); + expect((yield* actions.getSummary).actions).toEqual(["update", "repair", "remove"]); + state.latest = cliRelease("1.5.14"); + const current = yield* actions.getSummary; + expect(current.actions).toEqual(["repair", "remove"]); + expect(current.message).not.toContain("sign in"); + expect((yield* actions.plan("repair")).message).not.toContain("sign in"); + }), +); + it.effect("tells a session failure after Google accepted the sign-in from a failed sign-in", () => Effect.gen(function* () { const controllerWith = (states: ReadonlyArray): ProviderAuthController => ({ diff --git a/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.ts b/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.ts index 459356dd47..df15bd1fc3 100644 --- a/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.ts +++ b/apps/server/src/scient/providerLifecycle/AntigravityAcpLifecycleActions.ts @@ -12,7 +12,6 @@ import { import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; -import { isManagedRuntimeUpdate } from "@scientfactory/provider-runtime"; import { isProviderConnectionActionError, @@ -24,11 +23,18 @@ import type { ProviderManagedRuntimeProgress, } from "../../provider/ScientProviderInstanceSeams.ts"; import type { AntigravityInstallation } from "../../provider/AntigravityInstallation.ts"; -import type { AntigravityReleaseAsset } from "../../provider/antigravityRelease.ts"; import { ANTIGRAVITY_ACP_REGISTRY_VERSION, resolveAntigravityReleaseAsset, } from "./antigravityAcpCatalog.ts"; +import { + antigravityReleaseDownloadBytes, + antigravityReleaseIdentity, + antigravityReleaseRevision, + supersedesAntigravityRelease, + type AntigravityManagedRelease, + type AntigravityReleaseIdentity, +} from "./antigravityRuntimeRelease.ts"; import { ManagedRuntimeCatalog } from "./ManagedRuntimeCatalog.ts"; import { antigravityAuthUsesBrowser } from "../../provider/antigravityAuthSupport.ts"; import type { ProviderAuthController } from "../../provider/ProviderAuthService.ts"; @@ -55,6 +61,9 @@ const failure = (message: string, cause?: unknown, reason?: ProviderConnectionFa export const ANTIGRAVITY_STARTING_MESSAGE = "Antigravity can take up to a minute to start."; +const CLI_SWITCH_MESSAGE = + "An update moves Antigravity to Google's agy CLI, which runs your Antigravity plugins in Scient chats."; + export function antigravityConnectionMethod(method: AntigravityAuthMethod) { return antigravityAuthUsesBrowser(method) ? ("antigravity_google" as const) @@ -255,10 +264,6 @@ function installProgress(state: ProviderInstallState): ProviderManagedRuntimePro }; } -function runtimeRevision(version: string, sha256: string): string { - return `antigravity-acp:${version}:${sha256}`; -} - /** Expose T3's verified ACP installer through Scient's reviewed runtime actions. */ export function makeAntigravityManagedRuntimeActions(input: { readonly installation: AntigravityInstallation["Service"]; @@ -271,6 +276,10 @@ export function makeAntigravityManagedRuntimeActions(input: { const bundledAsset = resolveAntigravityReleaseAsset(input.platform, input.arch); const target = `${input.platform}-${input.arch}`; const configuredPath = input.settings.binaryPath.trim(); + // The CLI keeps its own sign-in; a paired runtime's Google sign-in does not carry over. + const signInAgain = antigravityAuthUsesBrowser(input.settings.authMethod) + ? " You'll sign in to Google again after it." + : ""; const readResolution = input.installation .resolve(configuredPath || undefined, input.environment) @@ -294,23 +303,33 @@ export function makeAntigravityManagedRuntimeActions(input: { ? "scient_managed" : "missing"; const fullyAssisted = asset !== null && !configuredPath; - const installedRegistryVersion = - executable?.registryVersion ?? - (executable?.version === bundledAsset?.version ? ANTIGRAVITY_ACP_REGISTRY_VERSION : null); + const installed: AntigravityReleaseIdentity | undefined = executable && { + cli: executable.harnessPath === null, + version: executable.version, + registryVersion: + executable.registryVersion ?? + (executable.harnessPath !== null && executable.version === bundledAsset?.version + ? ANTIGRAVITY_ACP_REGISTRY_VERSION + : undefined), + }; + const candidate = asset ? antigravityReleaseIdentity(asset) : undefined; const updateAvailable = source === "scient_managed" && + installed !== undefined && + candidate !== undefined && + supersedesAntigravityRelease(installed, candidate); + // Repair reinstalls the catalog's release, so it never replaces a newer install with an older one. + const repairAvailable = asset !== null && - asset.registryVersion !== undefined && - isManagedRuntimeUpdate({ - provider: "antigravityAcp", - current: installedRegistryVersion, - candidate: asset.registryVersion, - }); + (installed === undefined || + candidate === undefined || + !supersedesAntigravityRelease(candidate, installed)); + const switchesToCli = updateAvailable && candidate?.cli === true && installed?.cli === false; const actions: ReadonlyArray = source === "scient_managed" && !configuredPath ? [ ...(updateAvailable ? (["update"] as const) : []), - ...(asset ? (["repair"] as const) : []), + ...(repairAvailable ? (["repair"] as const) : []), "remove", ] : !fullyAssisted @@ -325,7 +344,9 @@ export function makeAntigravityManagedRuntimeActions(input: { ? "Scient is using the official Antigravity ACP runtime already installed on this computer." : source === "scient_managed" ? executable - ? "Scient is using an app-private, verified Antigravity ACP runtime." + ? switchesToCli + ? `${CLI_SWITCH_MESSAGE}${signInAgain}` + : "Scient is using an app-private, verified Antigravity ACP runtime." : "The private Antigravity ACP runtime needs repair." : configuredPath ? "Scient could not launch the custom Antigravity ACP runtime. Update or clear its path." @@ -342,7 +363,11 @@ export function makeAntigravityManagedRuntimeActions(input: { target, actions: [...actions], managedVersion: state.installedVersion, - availableManagedVersion: updateAvailable ? (asset?.registryVersion ?? null) : null, + availableManagedVersion: updateAvailable + ? candidate?.cli + ? (candidate.version ?? null) + : (candidate?.registryVersion ?? null) + : null, previousManagedVersion: null, // No `qualifiedVersion`: the installed executable and its registry // release are numbered differently, so "Up to date" is never claimed. @@ -372,28 +397,47 @@ export function makeAntigravityManagedRuntimeActions(input: { ? input.installation.latestRelease : input.installation.refreshLatestRelease; const summary = yield* getSummary; - if (!summary.actions.includes(action) || (action !== "remove" && !asset)) { + if (action === "remove") { + if (!summary.actions.includes(action)) { + return yield* failure( + `The ${action} action is not available for this Antigravity runtime.`, + ); + } + return { + action, + target, + version: null, + downloadBytes: null, + sourceLabel: "Official Google Antigravity ACP release", + catalogRevision: `antigravity-acp:remove:${summary.managedVersion ?? "none"}`, + message: + "Remove Scient's private Antigravity ACP runtime. System and custom installations are untouched.", + }; + } + if (!summary.actions.includes(action) || !asset) { return yield* failure(`The ${action} action is not available for this Antigravity runtime.`); } + const cli = antigravityReleaseIdentity(asset).cli; + const replacesPaired = + cli && Option.exists(yield* readResolution, (current) => current.harnessPath !== null); + const verb = action === "repair" ? "Repair" : action === "update" ? "Update" : "Install"; return { action, target, - version: action === "remove" ? null : (asset?.version ?? null), - downloadBytes: action === "remove" ? null : (asset?.archiveBytes ?? null), - sourceLabel: "Official Google Antigravity ACP release", - catalogRevision: - action === "remove" - ? `antigravity-acp:remove:${summary.managedVersion ?? "none"}` - : runtimeRevision(asset!.version, asset!.sha256), - message: - action === "remove" - ? "Remove Scient's private Antigravity ACP runtime. System and custom installations are untouched." - : `${action === "repair" ? "Repair" : action === "update" ? "Update" : "Install"} Google's verified Antigravity ACP runtime privately for Scient.`, + version: asset.version, + downloadBytes: antigravityReleaseDownloadBytes(asset), + sourceLabel: cli + ? "Official Google Antigravity CLI release" + : "Official Google Antigravity ACP release", + catalogRevision: antigravityReleaseRevision(asset), + message: cli + ? `${verb} Google's verified Antigravity CLI privately for Scient. It runs your Antigravity plugins in Scient chats.${replacesPaired ? signInAgain : ""}` + : `${verb} Google's verified Antigravity ACP runtime privately for Scient.`, }; }); const runInstall = Effect.fn("AntigravityLifecycleBridge.runInstall")(function* ( - asset: AntigravityReleaseAsset, + asset: AntigravityManagedRelease, report: (progress: ProviderManagedRuntimeProgress) => Effect.Effect, ) { const started = yield* input.installation.startRelease(asset); @@ -443,7 +487,7 @@ export function makeAntigravityManagedRuntimeActions(input: { return; } const asset = yield* input.installation.latestRelease; - if (!asset || revision !== runtimeRevision(asset.version, asset.sha256)) { + if (!asset || revision !== antigravityReleaseRevision(asset)) { return yield* failure("The Antigravity installation plan changed. Review it again."); } yield* awaitActivationWindow; diff --git a/apps/server/src/scient/providerLifecycle/antigravityRuntimeRelease.ts b/apps/server/src/scient/providerLifecycle/antigravityRuntimeRelease.ts new file mode 100644 index 0000000000..79ebabf3cc --- /dev/null +++ b/apps/server/src/scient/providerLifecycle/antigravityRuntimeRelease.ts @@ -0,0 +1,74 @@ +import { isManagedRuntimeUpdate } from "@scientfactory/provider-runtime"; + +import type { AntigravityCliReleaseAsset } from "../../provider/antigravityCliRelease.ts"; +import type { AntigravityReleaseAsset } from "../../provider/antigravityRelease.ts"; + +/** A managed Antigravity release: the paired ACP server, or the agy CLI that serves ACP itself. */ +export type AntigravityManagedRelease = AntigravityReleaseAsset | AntigravityCliReleaseAsset; + +export interface AntigravityReleaseIdentity { + readonly cli: boolean; + readonly version: string | null; + readonly registryVersion?: string | undefined; +} + +function isAntigravityCliRelease( + release: AntigravityManagedRelease, +): release is AntigravityCliReleaseAsset { + return "sha512" in release; +} + +export function antigravityReleaseIdentity( + release: AntigravityManagedRelease, +): AntigravityReleaseIdentity { + return isAntigravityCliRelease(release) + ? { cli: true, version: release.version } + : { cli: false, version: release.version, registryVersion: release.registryVersion }; +} + +/** The installer's release directory name: CLI releases use a SHA-512 prefix. */ +export function antigravityReleaseId(release: AntigravityManagedRelease): string { + return isAntigravityCliRelease(release) ? release.sha512.slice(0, 64) : release.sha256; +} + +/** Plan identity: a different archive under the same version label is a different plan. */ +export function antigravityReleaseRevision(release: AntigravityManagedRelease): string { + return isAntigravityCliRelease(release) + ? `antigravity-cli:${release.version}:${release.sha512}` + : `antigravity-acp:${release.version}:${release.sha256}`; +} + +export function antigravityReleaseDownloadBytes(release: AntigravityManagedRelease): number | null { + const bytes = "archiveBytes" in release ? release.archiveBytes : undefined; + return typeof bytes === "number" ? bytes : null; +} + +/** + * Whether `candidate` replaces `current` as the managed default. The agy CLI loads full + * Antigravity plugins, so it supersedes every paired release; within one family the newer + * release does. Unknown versions never count as newer. + */ +export function supersedesAntigravityRelease( + current: AntigravityReleaseIdentity, + candidate: AntigravityReleaseIdentity, +): boolean { + if (current.cli !== candidate.cli) return candidate.cli; + if (candidate.cli) { + return ( + candidate.version !== null && + isManagedRuntimeUpdate({ + provider: "antigravity", + current: current.version, + candidate: candidate.version, + }) + ); + } + return ( + candidate.registryVersion !== undefined && + isManagedRuntimeUpdate({ + provider: "antigravityAcp", + current: current.registryVersion ?? null, + candidate: candidate.registryVersion, + }) + ); +} From e299b2d713e98206c3dcb3c2074eb03dddec8cbe Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:44:25 +0200 Subject: [PATCH 02/36] feat(antigravity): install the catalog's agy CLI as the managed default On Scient's ACP targets the managed runtime is now the agy CLI that Scient's catalog lists under `antigravity`, which runs `agy acp` and loads the user's full Antigravity plugins. Only a CLI from 1.5.12 on qualifies; earlier ones, including the bundled 1.1.x floor, cannot serve ACP. Where no qualified CLI is listed (offline before the first catalog check, musl Linux) the paired release stays the floor. Intel Macs keep the legacy backend. Co-Authored-By: Claude Opus 5.5 --- .../ScientAntigravityInstallation.ts | 35 +++++++-- .../antigravityAcpCatalog.test.ts | 73 +++++++++++++++++++ .../antigravityAcpCatalog.ts | 63 ++++++++++++++++ 3 files changed, 166 insertions(+), 5 deletions(-) diff --git a/apps/server/src/scient/providerLifecycle/ScientAntigravityInstallation.ts b/apps/server/src/scient/providerLifecycle/ScientAntigravityInstallation.ts index 4ba2aa8002..c5e09165df 100644 --- a/apps/server/src/scient/providerLifecycle/ScientAntigravityInstallation.ts +++ b/apps/server/src/scient/providerLifecycle/ScientAntigravityInstallation.ts @@ -5,25 +5,50 @@ import { } from "../../provider/AntigravityInstallation.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import { ManagedRuntimeCatalog } from "./ManagedRuntimeCatalog.ts"; +import { ManagedRuntimeCatalog, type ManagedRuntimeCatalogData } from "./ManagedRuntimeCatalog.ts"; import { bundledAntigravityAcpAsset, resolveAntigravityAcpCatalogAsset, + resolveAntigravityCliCatalogAsset, } from "./antigravityAcpCatalog.ts"; -/** Compose Scient's qualified release source with T3's paired native installer. */ +/** + * The managed default is the catalog's agy CLI, which loads full Antigravity plugins; the + * paired release stays the floor where no qualified CLI is listed for this computer. + */ +export function selectAntigravityManagedRelease( + catalog: ManagedRuntimeCatalogData, + platform: NodeJS.Platform, + arch: string, + musl: boolean, +) { + return ( + resolveAntigravityCliCatalogAsset(catalog, platform, arch, musl) ?? + resolveAntigravityAcpCatalogAsset(catalog, platform, arch) ?? + bundledAntigravityAcpAsset(platform, arch) + ); +} + +/** Compose Scient's qualified release source with T3's native installer. */ export const scientAntigravityInstallationLayer = Layer.effect( AntigravityInstallation, Effect.gen(function* () { const config = yield* ServerConfig; const catalog = yield* ManagedRuntimeCatalog; + const fs = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const arch = yield* HostProcess.Architecture; - const resolve = (current: Parameters[0]) => - resolveAntigravityAcpCatalogAsset(current, platform, arch) ?? - bundledAntigravityAcpAsset(platform, arch); + // As T3's CLI channel does: Google publishes separate musl builds. + const musl = + platform === "linux" && + (yield* fs + .exists(arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1") + .pipe(Effect.orElseSucceed(() => false))); + const resolve = (current: ManagedRuntimeCatalogData) => + selectAntigravityManagedRelease(current, platform, arch, musl); return yield* makeAntigravityInstallation({ baseDir: config.baseDir, refreshLatestRelease: catalog.refresh.pipe(Effect.map(resolve)), diff --git a/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.test.ts b/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.test.ts index 1e95f8a736..42478d24a2 100644 --- a/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.test.ts +++ b/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.test.ts @@ -5,7 +5,13 @@ import { bundledAntigravityAcpAsset, ANTIGRAVITY_ACP_REGISTRY_VERSION, resolveAntigravityAcpCatalogAsset, + resolveAntigravityCliCatalogAsset, } from "./antigravityAcpCatalog.ts"; +import { + BUNDLED_MANAGED_RUNTIME_CATALOG, + type ManagedRuntimeCatalogData, +} from "./ManagedRuntimeCatalog.ts"; +import { selectAntigravityManagedRelease } from "./ScientAntigravityInstallation.ts"; const targets = [ ["darwin", "arm64"], @@ -139,3 +145,70 @@ it("rejects feed attempts to change the approved ACP host, member facts, or rele }), ).toBeUndefined(); }); + +const bundledCli = BUNDLED_MANAGED_RUNTIME_CATALOG.providers.antigravity!; +const withCli = ( + version: string, + url: (url: string) => string = (value) => + value.replace(/antigravity-cli\/[^/]+\//u, `antigravity-cli/${version}-5302690847260672/`), +): ManagedRuntimeCatalogData => ({ + ...BUNDLED_MANAGED_RUNTIME_CATALOG, + providers: { + ...BUNDLED_MANAGED_RUNTIME_CATALOG.providers, + antigravity: { + ...bundledCli, + version, + artifacts: Object.fromEntries( + Object.entries(bundledCli.artifacts).map(([key, artifact]) => [ + key, + { ...artifact, url: url(artifact.url) }, + ]), + ), + }, + }, +}); + +it("makes the catalog's ACP-capable agy CLI the managed default on every ACP target", () => { + const served = withCli("1.5.14"); + for (const [platform, arch] of targets) { + const key = platform === "linux" ? `${platform}-${arch}-glibc` : `${platform}-${arch}`; + const artifact = served.providers.antigravity!.artifacts[key]!; + const selected = selectAntigravityManagedRelease(served, platform, arch, false); + expect(selected).toEqual({ + version: "1.5.14", + url: artifact.url, + sha512: artifact.checksum.digest, + archiveBytes: artifact.size, + executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, + format: platform === "win32" ? "executable" : "tar.gz", + }); + } + // Intel Macs keep the legacy backend: the CLI is not offered to the ACP driver there. + expect(resolveAntigravityCliCatalogAsset(served, "darwin", "x64")).toBeUndefined(); +}); + +it("keeps the paired release as the floor where no qualified CLI is listed", () => { + const paired = (platform: NodeJS.Platform, arch: string) => + resolveAntigravityAcpCatalogAsset(BUNDLED_MANAGED_RUNTIME_CATALOG, platform, arch); + // The bundled catalog's 1.1.x CLI cannot serve ACP, so offline installs stay paired. + for (const [platform, arch] of targets) { + expect( + selectAntigravityManagedRelease(BUNDLED_MANAGED_RUNTIME_CATALOG, platform, arch, false), + ).toEqual(paired(platform, arch)); + } + expect(selectAntigravityManagedRelease(withCli("1.5.11"), "linux", "x64", false)).toEqual( + paired("linux", "x64"), + ); + // Google publishes no reviewed musl CLI. + expect(selectAntigravityManagedRelease(withCli("1.5.14"), "linux", "x64", true)).toEqual( + paired("linux", "x64"), + ); + expect( + selectAntigravityManagedRelease( + withCli("1.5.14", (url) => url.replace("storage.googleapis.com", "example.com")), + "linux", + "x64", + false, + ), + ).toEqual(paired("linux", "x64")); +}); diff --git a/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.ts b/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.ts index fca4bf98e1..e1cddaccb6 100644 --- a/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.ts +++ b/apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.ts @@ -1,8 +1,19 @@ import { ANTIGRAVITY_ACP_REGISTRY_VERSION, ANTIGRAVITY_ACP_TARGETS, + compareManagedRuntimeVersions, + MANAGED_RUNTIME_POLICY, + resolveReviewedAntigravityArtifact, } from "@scientfactory/provider-runtime"; +import { + parseAntigravityCliRelease, + type AntigravityCliReleaseAsset, +} from "../../provider/antigravityCliRelease.ts"; import { type AntigravityReleaseAsset } from "../../provider/antigravityRelease.ts"; +import { + resolveManagedRuntimeCatalogArtifact, + type ManagedRuntimeCatalogData, +} from "./ManagedRuntimeCatalog.ts"; export { ANTIGRAVITY_ACP_REGISTRY_VERSION, @@ -103,3 +114,55 @@ export function bundledAntigravityAcpAsset( const asset = resolveAntigravityReleaseAsset(platform, arch); return asset ? { ...asset, registryVersion: ANTIGRAVITY_ACP_REGISTRY_VERSION } : null; } + +// The first agy CLI qualified with Scient's ACP launch (profile flags, sign-in, plugins). +// Earlier catalog CLIs, including the bundled 1.1.x floor, cannot serve ACP. +const ANTIGRAVITY_CLI_ACP_MINIMUM_VERSION = "1.5.12"; + +export interface AntigravityCliCatalogAsset extends AntigravityCliReleaseAsset { + readonly archiveBytes: number; +} + +/** The catalog's agy CLI for an ACP target, when it is new enough to serve ACP. */ +export function resolveAntigravityCliCatalogAsset( + catalog: ManagedRuntimeCatalogData, + platform: NodeJS.Platform, + arch: string, + musl = false, +): AntigravityCliCatalogAsset | undefined { + const acpTarget = ANTIGRAVITY_ACP_TARGETS.find( + (target) => target.platform === platform && target.arch === arch, + ); + if (!acpTarget) return undefined; + const policy = resolveReviewedAntigravityArtifact({ + platform: acpTarget.platform, + arch: acpTarget.arch, + ...(acpTarget.platform === "linux" ? { libc: musl ? "musl" : "glibc" } : {}), + }); + const artifact = policy + ? resolveManagedRuntimeCatalogArtifact({ + catalog, + policy, + contractRevision: MANAGED_RUNTIME_POLICY.antigravity.revision, + }) + : undefined; + if ( + !artifact || + artifact.checksum.algorithm !== "sha512" || + !["equal", "newer"].includes( + compareManagedRuntimeVersions({ + provider: "antigravity", + current: ANTIGRAVITY_CLI_ACP_MINIMUM_VERSION, + candidate: artifact.version, + }), + ) + ) + return undefined; + const release = parseAntigravityCliRelease( + { version: artifact.version, url: artifact.url, sha512: artifact.checksum.digest }, + platform, + arch, + musl, + ); + return release ? { ...release, archiveBytes: artifact.size } : undefined; +} From a3cb0d56eb04682af46ab0c913426affb2e4d70b Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:44:49 +0200 Subject: [PATCH 03/36] feat(antigravity): project plugin skills only for the paired runtime The agy CLI loads plugins itself from the user's ~/.gemini, whatever GEMINI_HOME says, so a profile launched with it skips the skills-only projection and loses the `config/plugins` link only when Scient made that link to one of its generations. User folders and other links stay, and generations stay for paired sessions still running. The paired projection now also leaves out plugins `agy plugin disable` turned off in the user's config. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/Drivers/AntigravityDriver.ts | 1 + .../src/provider/antigravityAuthSupport.ts | 14 ++- .../antigravityPluginSkillProjection.test.ts | 109 ++++++++++++++++++ .../antigravityPluginSkillProjection.ts | 80 ++++++++++++- 4 files changed, 198 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 6edf2071ab..3209602eeb 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -284,6 +284,7 @@ export const AntigravityDriver: ScientProviderDriver< auth, userHome, tempDirectory: directories.runtimeTemp, + nativePlugins: executable.harnessPath === null, // SCIENT-FORK: the agy CLI loads plugins. }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index d069daf88b..b16234abf8 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -23,7 +23,10 @@ import * as AcpErrors from "effect-acp/errors"; import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; // SCIENT-FORK:START — plugin skills are projected without their other components. -import { projectAntigravityPluginSkills } from "../scient/skills/antigravityPluginSkillProjection.ts"; +import { + projectAntigravityPluginSkills, + removeAntigravityPluginSkillProjection, +} from "../scient/skills/antigravityPluginSkillProjection.ts"; // SCIENT-FORK:END // SCIENT-FORK:START — safe skill links and a once-per-helper browser preflight. import { @@ -525,6 +528,9 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( readonly auth?: AntigravityAuthConfig; readonly userHome?: string; readonly tempDirectory?: string; + // SCIENT-FORK:START — the agy CLI loads plugins itself; only a paired runtime needs projection. + readonly nativePlugins?: boolean; + // SCIENT-FORK:END }) { const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH; const fs = yield* FileSystem.FileSystem; @@ -673,7 +679,11 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( if (platform === "win32") { yield* copyAntigravityUserConfigFiles({ profileDirectory: geminiHome, userHome }); } - yield* projectAntigravityPluginSkills({ profileDirectory: geminiHome, userHome, platform }); + // SCIENT-FORK:START — see nativePlugins. + yield* input.nativePlugins + ? removeAntigravityPluginSkillProjection({ profileDirectory: geminiHome }) + : projectAntigravityPluginSkills({ profileDirectory: geminiHome, userHome, platform }); + // SCIENT-FORK:END return profile; }); diff --git a/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts b/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts new file mode 100644 index 0000000000..68af9a43f0 --- /dev/null +++ b/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts @@ -0,0 +1,109 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +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 { prepareAntigravityProfile } from "../../provider/antigravityAuthSupport.ts"; +import { + projectAntigravityPluginSkills, + removeAntigravityPluginSkillProjection, +} from "./antigravityPluginSkillProjection.ts"; + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +const makeHome = Effect.fn("test.makeAntigravityPluginHome")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "scient-agy-projection-" }); + const userHome = path.join(root, "home"); + const profileDirectory = path.join(root, "profile"); + const plugins = path.join(userHome, ".gemini", "config", "plugins"); + for (const name of ["science", "gmail"]) { + yield* fs.makeDirectory(path.join(plugins, name, "skills", `${name}-skill`), { + recursive: true, + }); + yield* fs.writeFileString(path.join(plugins, name, "plugin.json"), encodeJson({ name })); + } + return { root, userHome, profileDirectory, plugins }; +}); + +it.layer(NodeServices.layer)("Antigravity plugin skill projection", (it) => { + it.effect.skipIf(!symlinksSupported)( + "leaves out plugins `agy plugin disable` turned off, and all of them when its switches are unreadable", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* makeHome(); + const config = path.join(home.userHome, ".gemini", "config", "config.json"); + const projected = (name: string) => + fs.exists(path.join(home.profileDirectory, "config", "plugins", name, "skills")); + const project = projectAntigravityPluginSkills({ + profileDirectory: home.profileDirectory, + userHome: home.userHome, + platform: yield* HostProcess.Platform, + }); + + yield* fs.writeFileString(config, encodeJson({ plugins: { gmail: { enabled: false } } })); + yield* project; + expect(yield* projected("science")).toBe(true); + expect(yield* projected("gmail")).toBe(false); + + yield* fs.writeFileString(config, `{"pad":"${"x".repeat(1_000_000)}"}`); + yield* project; + expect(yield* projected("science")).toBe(false); + + yield* fs.remove(config); + yield* project; + expect(yield* projected("science")).toBe(true); + expect(yield* projected("gmail")).toBe(true); + }), + ); + + it.effect.skipIf(!symlinksSupported)( + "removes only the projection link Scient made when the agy CLI loads plugins", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* makeHome(); + const pluginsLink = path.join(home.profileDirectory, "config", "plugins"); + const isLink = fs.readLink(pluginsLink).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + + yield* prepareAntigravityProfile({ + profileDirectory: home.profileDirectory, + userHome: home.userHome, + }); + expect(yield* isLink).toBe(true); + const generation = yield* fs.readLink(pluginsLink); + + yield* prepareAntigravityProfile({ + profileDirectory: home.profileDirectory, + userHome: home.userHome, + nativePlugins: true, + }); + expect(yield* fs.exists(pluginsLink)).toBe(false); + // A paired session that is still running keeps reading its generation. + expect(yield* fs.exists(path.join(generation, "science", "skills"))).toBe(true); + + const remove = removeAntigravityPluginSkillProjection({ + profileDirectory: home.profileDirectory, + }); + yield* fs.symlink(home.plugins, pluginsLink); + yield* remove; + expect(yield* fs.readLink(pluginsLink)).toBe(home.plugins); + + yield* fs.remove(pluginsLink); + yield* fs.makeDirectory(path.join(pluginsLink, "own-plugin"), { recursive: true }); + yield* remove; + expect(yield* fs.exists(path.join(pluginsLink, "own-plugin"))).toBe(true); + }), + ); +}); diff --git a/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts b/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts index 3738f486ad..581ce4b539 100644 --- a/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts +++ b/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts @@ -10,6 +10,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; const maxPluginProjectionEntries = 10_000; @@ -17,6 +18,35 @@ const maxPluginManifestBytes = 1_000_000; const decodePluginProjectionManifest = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ name: Schema.String })), ); +const decodePluginSwitches = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + plugins: Schema.optional( + Schema.Record(Schema.String, Schema.Struct({ enabled: Schema.optional(Schema.Boolean) })), + ), + }), + ), +); +const projectionGeneration = /^[a-f0-9]{64}$/u; + +/** Plugins `agy plugin disable` turned off, read as the skill picker reads them; null when + * the user's config cannot be read. */ +async function readDisabledPlugins(userHome: string): Promise | null> { + const configPath = NodePath.join(userHome, ".gemini", "config", "config.json"); + const info = await NodeFSP.stat(configPath).catch((error: NodeJS.ErrnoException) => + error.code === "ENOENT" ? undefined : null, + ); + if (info === null || (info?.isFile() && info.size > maxPluginManifestBytes)) return null; + if (!info?.isFile()) return new Set(); + const contents = await NodeFSP.readFile(configPath, "utf8").catch(() => null); + if (contents === null) return null; + const switches = decodePluginSwitches(contents); + return new Set( + Object.entries(Option.isSome(switches) ? (switches.value.plugins ?? {}) : {}).flatMap( + ([name, plugin]) => (plugin.enabled === false ? [name] : []), + ), + ); +} /** * Give the managed ACP runtime the skill component of each Antigravity plugin @@ -39,15 +69,18 @@ export const projectAntigravityPluginSkills = Effect.fn("projectAntigravityPlugi if (sourceEntries.length > maxPluginProjectionEntries) { throw new Error("Antigravity plugin discovery exceeded its entry limit."); } + // Unknown switches project nothing, as the skill picker shows nothing for them. + const disabled = await readDisabledPlugins(input.userHome); const plugins: Array<{ readonly directoryName: string; readonly manifest: string; readonly skillsDirectory: string; }> = []; - for (const entry of sourceEntries.toSorted((left, right) => - left.name.localeCompare(right.name), - )) { + for (const entry of disabled === null + ? [] + : sourceEntries.toSorted((left, right) => left.name.localeCompare(right.name))) { if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; + if (disabled?.has(entry.name)) continue; const pluginDirectory = NodePath.join(sourceRoot, entry.name); const manifestPath = NodePath.join(pluginDirectory, "plugin.json"); const skillsDirectory = NodePath.join(pluginDirectory, "skills"); @@ -69,7 +102,7 @@ export const projectAntigravityPluginSkills = Effect.fn("projectAntigravityPlugi } catch { continue; } - if (!parsed.name.trim()) continue; + if (!parsed.name.trim() || disabled?.has(parsed.name.trim())) continue; plugins.push({ directoryName: entry.name, manifest, skillsDirectory }); } @@ -152,3 +185,42 @@ export const projectAntigravityPluginSkills = Effect.fn("projectAntigravityPlugi ); }, ); + +/** + * The agy CLI loads plugins itself from the user's ~/.gemini. Remove the profile's + * `config/plugins` link only when it is one Scient made to a projected generation; user + * directories and other links stay, and generations stay for any running paired session. + */ +export const removeAntigravityPluginSkillProjection = Effect.fn( + "removeAntigravityPluginSkillProjection", +)(function* (input: { readonly profileDirectory: string }) { + yield* Effect.tryPromise({ + try: async () => { + const pluginsLink = NodePath.join(input.profileDirectory, "config", "plugins"); + const existing = await NodeFSP.lstat(pluginsLink).catch((error: NodeJS.ErrnoException) => + error.code === "ENOENT" ? undefined : Promise.reject(error), + ); + if (!existing?.isSymbolicLink()) return; + // Windows may report a junction's target with the \\?\ long-path prefix. + const written = (await NodeFSP.readlink(pluginsLink)).replace(/^\\\\\?\\/u, ""); + const target = NodePath.resolve(NodePath.dirname(pluginsLink), written); + const projectionRoot = NodePath.resolve( + input.profileDirectory, + "antigravity-acp", + "skill-plugins", + ); + if ( + NodePath.dirname(target) !== projectionRoot || + !projectionGeneration.test(NodePath.basename(target)) + ) { + return; + } + await NodeFSP.rm(pluginsLink); + }, + catch: (cause) => (cause instanceof Error ? cause.message : String(cause)), + }).pipe( + Effect.catch((error) => + Effect.logWarning("Antigravity's projected plugin skills link was not removed.", { error }), + ), + ); +}); From a5e5fc68abe2b1db0d4a50dcf4c320c529420d98 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:45:15 +0200 Subject: [PATCH 04/36] fix(antigravity): skill picker hides plugins agy disabled `agy plugin disable` records the switch in the user's ~/.gemini/config/config.json, not the instance profile, so a disabled plugin's skills still surfaced through the picker's global scan. The scan now honors those switches, matched by folder or manifest name, and a stale paired projection cannot bring the plugin back. Co-Authored-By: Claude Opus 5.5 --- .../Drivers/AntigravitySkills.scient.test.ts | 57 +++++++++++++++++++ .../src/provider/Drivers/AntigravitySkills.ts | 52 +++++++++++------ 2 files changed, 92 insertions(+), 17 deletions(-) create mode 100644 apps/server/src/provider/Drivers/AntigravitySkills.scient.test.ts diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.scient.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.scient.test.ts new file mode 100644 index 0000000000..6b48bad47d --- /dev/null +++ b/apps/server/src/provider/Drivers/AntigravitySkills.scient.test.ts @@ -0,0 +1,57 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +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 { discoverAntigravitySkills } from "./AntigravitySkills.ts"; + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +it.layer(NodeServices.layer)("discoverAntigravitySkills (Scient)", (it) => { + it.effect("hides a global plugin's skills once `agy plugin disable` turns it off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "scient-agy-skills-" }); + const userHome = path.join(root, "home"); + const profileDirectory = path.join(root, "profile"); + const userConfig = path.join(userHome, ".gemini", "config"); + for (const name of ["science", "gmail"]) { + const plugin = path.join(userConfig, "plugins", name); + yield* fs.makeDirectory(path.join(plugin, "skills", "use"), { recursive: true }); + yield* fs.writeFileString(path.join(plugin, "plugin.json"), encodeJson({ name })); + yield* fs.writeFileString( + path.join(plugin, "skills", "use", "SKILL.md"), + `---\nname: use\ndescription: Use ${name}.\n---\n`, + ); + } + // A paired runtime's stale projection of the same plugin does not bring it back. + const projected = path.join(profileDirectory, "config", "plugins", "gmail"); + yield* fs.makeDirectory(path.join(projected, "skills", "use"), { recursive: true }); + yield* fs.writeFileString(path.join(projected, "plugin.json"), encodeJson({ name: "gmail" })); + yield* fs.writeFileString( + path.join(projected, "skills", "use", "SKILL.md"), + "---\nname: use\ndescription: Use gmail.\n---\n", + ); + const names = () => + discoverAntigravitySkills({ userHome, profileDirectory }).pipe( + Effect.map((skills) => skills.map((skill) => skill.name)), + ); + + expect(yield* names()).toEqual(["gmail:use", "science:use"]); + yield* fs.writeFileString( + path.join(userConfig, "config.json"), + encodeJson({ plugins: { gmail: { enabled: false }, science: { enabled: true } } }), + ); + expect(yield* names()).toEqual(["science:use"]); + // Switches that cannot be read leave plugins out rather than guessing they are on. + yield* fs.writeFileString( + path.join(userConfig, "config.json"), + `{"pad":"${"x".repeat(1_000_000)}"}`, + ); + expect(yield* names()).toEqual([]); + }), + ); +}); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 28af63d46d..dd7d824447 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -467,7 +467,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( const manifest = decodePluginManifest(manifestContents); if (Option.isNone(manifest)) continue; const pluginName = manifest.value.name.trim(); - if (!pluginName) continue; + if (!pluginName || disabled.has(pluginName)) continue; yield* scanDirectory(path.join(pluginDirectory, "skills"), "plugin", true, pluginName); } }); @@ -567,17 +567,14 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( ); } - // SCIENT-FORK:START — the instance profile is where agy loads plugins; Scient keeps each - // plugin's manifest namespace there too and skips plugins its config turns off. - const profilePlugins = path.join(input.profileDirectory, "config", "plugins"); - const profilePluginEntries = yield* readIfPresent( - fileSystem.readDirectory(profilePlugins), - profilePlugins, - ); - if (profilePluginEntries !== undefined && profilePluginEntries.length > 0) { - // A config that cannot be read leaves out only these plugins, whose switches it holds; the - // other skills still load. - const configPath = path.join(input.profileDirectory, "config", "config.json"); + // SCIENT-FORK:START — the instance profile is where a paired runtime loads plugins; Scient + // keeps each plugin's manifest namespace there too and skips plugins a config turns off. + // A config that cannot be read leaves out only the plugins whose switches it holds; the + // other skills still load. + const readDisabledPlugins = Effect.fn("readAntigravityDisabledPlugins")(function* ( + configDirectory: string, + ) { + const configPath = path.join(configDirectory, "config.json"); const configInfo = yield* readIfPresent(fileSystem.stat(configPath), configPath).pipe( Effect.orElseSucceed(() => null), ); @@ -590,17 +587,38 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( Effect.orElseSucceed(() => null), ) : undefined; - const preferences = - config === undefined || config === null ? undefined : decodePluginPreferences(config); - const disabledPlugins = new Set( + if (config === null) return null; + const preferences = config === undefined ? undefined : decodePluginPreferences(config); + return new Set( Object.entries( (preferences?._tag === "Some" ? preferences.value.plugins : undefined) ?? {}, ).flatMap(([name, plugin]) => (plugin.enabled === false ? [name] : [])), ); - if (config !== null) yield* scanPluginDirectory(profilePlugins, disabledPlugins); + }); + // `agy plugin disable` records its switch in the user's config, not the instance profile. + const userDisabledPlugins = yield* readDisabledPlugins(path.join(userGeminiHome, "config")); + const profilePlugins = path.join(input.profileDirectory, "config", "plugins"); + const profilePluginEntries = yield* readIfPresent( + fileSystem.readDirectory(profilePlugins), + profilePlugins, + ); + if ( + userDisabledPlugins !== null && + profilePluginEntries !== undefined && + profilePluginEntries.length > 0 + ) { + const profileDisabledPlugins = yield* readDisabledPlugins( + path.join(input.profileDirectory, "config"), + ); + if (profileDisabledPlugins !== null) { + yield* scanPluginDirectory( + profilePlugins, + new Set([...profileDisabledPlugins, ...userDisabledPlugins]), + ); + } } + if (userDisabledPlugins !== null) yield* scanPluginDirectory(globalPlugins, userDisabledPlugins); // SCIENT-FORK:END - yield* scanPluginDirectory(globalPlugins); if (input.cwd) { yield* scanPluginDirectory(path.resolve(input.cwd, ".agents", "plugins")); } From b57a2f23875666259eb43035560f5b9ccc838325 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:46:09 +0200 Subject: [PATCH 05/36] docs(antigravity): the managed runtime is the agy CLI Help says Scient installs Google's Antigravity CLI, which runs the user's Antigravity plugins, and that updating from the paired runtime asks for one more Google sign-in. Internals record the selection, why a paired sign-in is not converted (same OAuth client, narrower scopes), where the CLI keeps plugins and their switches, and the remaining projection. Co-Authored-By: Claude Opus 5.5 --- UPSTREAM.md | 10 ++++++---- docs/internals/providers.md | 28 +++++++++++++++++++++------- docs/internals/scient-skills.md | 8 +++++--- docs/user/providers-antigravity.md | 9 +++++++++ 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index ccbe698846..c5bb9586aa 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -1789,10 +1789,12 @@ generation runner. Retain these narrow mounts without forking the native engine. Legacy CLI owners are named explicitly and remain active for explicit `agy` paths and targets outside the qualified native set; removing a fallback requires native replacement qualification, not merely an available Google archive. T3 now installs Google's -native CLI and dropped its pinned ACP release; Scient keeps that 1.4.5 release as the offline -floor of its qualified catalog (`scient/providerLifecycle/antigravityAcpCatalog.ts`), and T3's -native install runs only where no catalog is supplied. Moving Scient to the native CLI needs that -qualification first. +native CLI and dropped its pinned ACP release. Scient installs the CLI too, but from its own +catalog's `antigravity` key (1.5.12 and later, through T3's CLI install path), and keeps the +paired release as the floor where no qualified CLI is listed +(`scient/providerLifecycle/antigravityAcpCatalog.ts`); T3's own CLI channel runs only where no +catalog is supplied. `startRelease` treats the CLI as newer than any paired release, and +`prepareAntigravityProfile` takes `nativePlugins` so a CLI launch skips Scient's projection. T3 also removed harness support and rates Antigravity below 1.5 broken; Scient's manifest keeps 1.4.5 supported, and the driver, prompt and permission seams keep the harness path (its own `yolo`/`auto_edit` modes, video linking, runtime-policy approvals when no native Auto is diff --git a/docs/internals/providers.md b/docs/internals/providers.md index 9d7262d70d..70a5b070cd 100644 --- a/docs/internals/providers.md +++ b/docs/internals/providers.md @@ -275,7 +275,17 @@ instances. The open driver and instance identifiers require no database migratio WebSocket and provider-instance scopes. Instances share an explicit download operation and the completed runtime. Client disconnects and instance rebuilds do not cancel installation. -The fixed [release table][antigravity-release] supplies the bundled floor. Scient's qualified +On Scient's ACP targets the managed default is the agy CLI that Scient's catalog lists under the +`antigravity` key, from 1.5.12 on: it serves ACP as `agy acp` and loads full plugins. The +catalog's URL policy and T3's CLI release parser both apply. The paired release below is the +floor where no qualified CLI is listed (no catalog check yet, musl Linux). The CLI supersedes +every paired release, so a paired install is offered it as an update and an installed CLI is +never offered a paired release. A paired Google sign-in is not converted: both runtimes use the +same Google OAuth client, but the paired grant lacks scopes the CLI requests (`openid`, +`userinfo.profile`, `cclog`, `experimentsandconfigs`), so the user signs in once after the +switch. + +The fixed [release table][antigravity-release] supplies the paired bundled floor. Scient's qualified catalog may advance immutable release facts under the separate `antigravityAcp` key; the app still owns the allowed targets, Google URL family, exact executable pair, and launch policy. The catalog's semver is distinct from the agent's native build version. When the bundled @@ -300,7 +310,8 @@ the same verified archive updates its receipt without replacing or downloading t Resolution order is explicit `binaryPath`, active managed release, then the instance's `PATH`. An invalid explicit path fails without fallback. Manual installations are never changed by the -installer. Every launch pins `ANTIGRAVITY_HARNESS_PATH` to the selected executable's sibling. +installer. Every paired launch pins `ANTIGRAVITY_HARNESS_PATH` to the selected executable's +sibling. ### Google profiles and sign-in @@ -312,11 +323,14 @@ the official macOS keychain entry being shared across instances. Profile directo `0700` on POSIX. This is file storage, not an encrypted keychain. Windows uses the host profile's filesystem permissions. -The private profile links the user's documented loose and provider-managed skill roots. Global -plugin skills receive a skill-only projection containing each plugin manifest and skill directory; -plugin MCP servers, hooks, rules, agents, and credentials remain outside the profile. This keeps -native skill loading available without expanding a provider session's authority as a side effect of -skill discovery. +The private profile links the user's documented loose and provider-managed skill roots. The agy +CLI loads plugins natively from the OS user's `~/.gemini/config/plugins` whatever `GEMINI_HOME` +says, and `agy plugin enable|disable` keeps their switches in `~/.gemini/config/config.json`; +installed plugins are therefore shared with the user's own Antigravity. For a paired runtime, +which loads no plugins of its own, global plugin skills receive a skill-only projection +containing each enabled plugin's manifest and skill directory; plugin MCP servers, hooks, rules, +agents, and credentials remain outside the profile. A CLI launch skips the projection and removes +only a `config/plugins` link that points at one of Scient's projected generations. The launch environment removes API-key and cloud-billing variables, disables inherited environment extension, sets `PYTHONUNBUFFERED=1`, and controls `BROWSER`. A tested Node or diff --git a/docs/internals/scient-skills.md b/docs/internals/scient-skills.md index a0cd023103..557669af6e 100644 --- a/docs/internals/scient-skills.md +++ b/docs/internals/scient-skills.md @@ -492,9 +492,11 @@ metadata; Droid uses its official SDK inventory; Grok uses `grok inspect --json`; Cursor reads its documented personal compatibility roots and provider-managed built-ins; managed Antigravity reads its loose and plugin skill roots; and legacy Antigravity asks `agy /skills` for the exact native -catalog, including provider built-ins. Managed Antigravity projects only plugin -manifests and skill directories into its isolated profile, leaving plugin MCP -servers, hooks, rules, agents, and credentials outside the runtime. +catalog, including provider built-ins. Plugins that `agy plugin disable` turned +off stay hidden. The managed agy CLI loads the user's plugins itself; a paired +ACP runtime gets only plugin manifests and skill directories projected into its +isolated profile, leaving plugin MCP servers, hooks, rules, agents, and +credentials outside the runtime. External inventory does not import provider skills into Scient's own catalog, rewrite their source, or execute them. Personal, provider-bundled, plugin, diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 6fb4a5c4cf..c4f9d9e7a9 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -97,6 +97,11 @@ On Windows, **Binary path** can also be a `.cmd` or `.bat` script that only sets variables and then runs `agy_acp_server.exe` by its full path or a `%~dp0`-relative path; keep `localharness_external.exe` beside that executable. +On those targets Scient installs Google's Antigravity CLI (`agy`), which serves +ACP itself and runs the plugins you added to Antigravity in your Scient chats. +If Scient cannot reach its release list before the first install, it installs +the older paired ACP runtime instead, which offers only your plugins' skills. + Scient's update catalog treats official ACP and legacy `agy` as separate release families. When a newer ACP release has passed download, archive, native-startup, activation, and removal qualification on its supported target, @@ -104,6 +109,10 @@ native-startup, activation, and removal qualification on its supported target, the previous generation available while active sessions finish. It never mutates a system or custom installation. +A managed installation of the paired runtime is offered the CLI as its update. +The CLI keeps its own sign-in, so with a Google account you sign in to Google +once more after updating. + **Repair Antigravity** stages and validates a complete replacement before it touches a damaged managed generation. A failed download or verification leaves the existing copy and active pointer unchanged. Scient refuses to replace or From ab81dc0c20fa8eb5b907c206c197276fed6af9e8 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:44:58 +0200 Subject: [PATCH 06/36] feat(antigravity): offer plugin sign-in from its tool challenge A plugin that needs a sign-in fails its tool call with a card and a loopback sign-in link. The Antigravity adapter now takes that challenge only from the tool's result, validates the page strictly, keeps it in an expiring registry tied to the live agent process, scrubs it from tool output and streamed text, and raises a system notice carrying pluginSignIn. scient.pluginSignIn.open returns the page to the thread that showed the notice, under the provider management grant. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.ts | 2 + .../src/observability/RpcInstrumentation.ts | 2 + .../AntigravityAdapterV2.scient.test.ts | 241 +++++++ .../Adapters/AntigravityAdapterV2.ts | 68 +- .../PluginSignInRpcHandlers.test.ts | 92 +++ .../antigravity/PluginSignInRpcHandlers.ts | 91 +++ .../scient/antigravity/pluginSignIn.test.ts | 327 ++++++++++ .../src/scient/antigravity/pluginSignIn.ts | 603 ++++++++++++++++++ apps/server/src/ws.ts | 10 + .../src/clientRpcPermissions.scient.test.ts | 25 + .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/index.ts | 3 + packages/contracts/src/orchestrationV2.ts | 9 + packages/contracts/src/rpc.ts | 9 + packages/contracts/src/scient/pluginSignIn.ts | 62 ++ packages/provider-acp/src/server/adapter.ts | 80 +++ .../src/server/ProviderAdapter.ts | 7 + .../src/server/scientPluginSignIn.ts | 26 + 18 files changed, 1657 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts create mode 100644 apps/server/src/scient/antigravity/PluginSignInRpcHandlers.test.ts create mode 100644 apps/server/src/scient/antigravity/PluginSignInRpcHandlers.ts create mode 100644 apps/server/src/scient/antigravity/pluginSignIn.test.ts create mode 100644 apps/server/src/scient/antigravity/pluginSignIn.ts create mode 100644 packages/contracts/src/scient/pluginSignIn.ts create mode 100644 packages/provider-core/src/server/scientPluginSignIn.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 205ccbcf2f..9b44663b2f 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -80,6 +80,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.providerAuthComplete]: AuthProvidersManageScope, [WS_METHODS.providerMcpSignInStart]: AuthProvidersManageScope, [WS_METHODS.providerMcpSignInComplete]: AuthProvidersManageScope, + // SCIENT-FORK: an Antigravity plugin sign-in takes the same grant as an MCP sign-in. + [WS_METHODS.pluginSignInOpen]: AuthProvidersManageScope, [WS_METHODS.chatGptReconnectProfile]: AuthProvidersManageScope, [WS_METHODS.chatGptImportProfile]: AuthProvidersManageScope, [WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 18f31132e7..7e585285a5 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -53,6 +53,8 @@ const RPC_AGGREGATES = { [WS_METHODS.providerAuthComplete]: "provider", [WS_METHODS.providerMcpSignInStart]: "provider", [WS_METHODS.providerMcpSignInComplete]: "provider", + // SCIENT-FORK: Antigravity plugin sign-in from its chat notice. + [WS_METHODS.pluginSignInOpen]: "provider", [WS_METHODS.chatGptReconnectProfile]: "provider", [WS_METHODS.chatGptImportProfile]: "provider", [WS_METHODS.chatGptHandoffSubscribe]: "provider", diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts new file mode 100644 index 0000000000..98381e1bac --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts @@ -0,0 +1,241 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + MessageId, + NodeId, + ProjectId, + ProviderInstanceId, + ProviderSessionId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import { ChildProcessSpawner } from "effect/process"; +import type * as EffectAcpSchema from "effect-acp/compat"; + +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; +import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; +import { makeAntigravityAdapterV2 } from "./AntigravityAdapterV2.ts"; + +const layerSession = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + IdAllocator.layer, + McpProviderSessions.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), +); + +const STATE = "synthetic-state-0123456789"; +const SIGN_IN_URL = `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({ + client_id: "synthetic-client.example", + code_challenge: "synthetic-challenge", + redirect_uri: "http://127.0.0.1:57512/callback", + response_type: "code", + state: STATE, +}).toString()}`; +const CARD = ``; +const CHALLENGE = [ + "Command exited with code 1.", + "gmail: gmail/google needs authentication (not signed in). Show the user this card on its own line:\r", + `${CARD}\r`, + `Only if the card can't be shown, give them this sign-in link instead: ${SIGN_IN_URL}\r`, +].join("\n"); + +describe("AntigravityAdapterV2 plugin sign-in", () => { + it.effect("offers a plugin sign-in and keeps its page off the transcript", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("antigravity-plugin-sign-in-test"); + const threadId = ThreadId.make("thread-antigravity-plugin-sign-in"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const rawInput = { CommandLine: "gmail readonly search --max 3" }; + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "call-gmail", + title: "gmail readonly search --max 3", + kind: "execute", + status: "in_progress", + rawInput, + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call-gmail", + kind: "execute", + status: "completed", + rawInput, + rawOutput: { output: CHALLENGE, exit_code: 1 }, + content: [{ type: "content", content: { type: "text", text: CHALLENGE } }], + }); + const reply = `Sign in with ${SIGN_IN_URL}\n\n${CARD}`; + for (const text of [reply.slice(0, 40), reply.slice(40, 120), reply.slice(120)]) { + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text }, + }); + } + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-plugin-sign-in"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-plugin-sign-in"), + title: "Antigravity plugin sign-in", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + 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, + }, + threadId, + runId: RunId.make("run-antigravity-plugin-sign-in"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-plugin-sign-in"), + rootNodeId: NodeId.make("node-antigravity-plugin-sign-in"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-plugin-sign-in"), + text: "list my three newest emails", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + + const serialized = JSON.stringify(events); + assert.notInclude(serialized, STATE); + assert.notInclude(serialized, "synthetic-challenge"); + const notices = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice" + ? [event.turnItem] + : [], + ); + assert.strictEqual(notices.length, 1); + const pluginSignIn = notices[0]?.pluginSignIn; + assert.deepInclude(pluginSignIn, { plugin: "gmail", displayName: "Gmail" }); + const reply = events.findLast( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message", + ); + assert.strictEqual( + reply?.type === "turn_item.updated" && reply.turnItem.type === "assistant_message" + ? reply.turnItem.text + : undefined, + "Sign in with [sign-in link removed]\n\n", + ); + + const open = session.scientPluginSignIn?.open; + assert.isDefined(open); + const opened = yield* open!({ + threadId, + providerThread, + attemptId: pluginSignIn!.attemptId, + }); + assert.strictEqual(opened.authorizationUrl, SIGN_IN_URL); + const otherThread = yield* open!({ + threadId: ThreadId.make("thread-other"), + providerThread, + attemptId: pluginSignIn!.attemptId, + }).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(otherThread)); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 899afbf3f9..1370747950 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -4,9 +4,12 @@ import { ProviderInstanceId, type OrchestrationV2ProviderCapabilities, type ProviderSetupError, + // SCIENT-FORK: plugin sign-in failures are safe to show. + PluginSignInError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import type { SelfInvocation } from "@t3tools/shared/nodeRuntime"; +import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -55,6 +58,9 @@ import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuth // SCIENT-FORK:START Scient ACP application bridge import { scientAntigravityBridge } from "./ScientAcpApplicationBridge.ts"; // SCIENT-FORK:END Scient ACP application bridge +// SCIENT-FORK:START — plugin sign-in challenges from tool results. +import { makeAntigravityPluginSignIns } from "../../scient/antigravity/pluginSignIn.ts"; +// SCIENT-FORK:END import { AcpProviderCapabilitiesV2, makeAcpAdapterV2, @@ -165,11 +171,21 @@ export function makeAntigravityAcpAdapterFlavor( // managed 1.4.5 harness offers none: it runs Auto as `default`, answered by Scient's policy. const nativeAutoSessionIds = new Set(); // SCIENT-FORK:END + // SCIENT-FORK:START — sign-in challenges a plugin's tool result printed, by agent process. + const pluginSignIns = makeAntigravityPluginSignIns(); + // SCIENT-FORK:END const antigravityClientFileRoots = (cwd: string | null) => cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { const scope = yield* Scope.fork(yield* Effect.scope); + // SCIENT-FORK:START — a challenge's loopback listener lives in this process. + const generation = pluginSignIns.openGeneration(); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => pluginSignIns.closeGeneration(generation)), + ); + // SCIENT-FORK:END const platform = yield* HostProcess.Platform; const runtime = yield* options .withProcess( @@ -203,6 +219,15 @@ export function makeAntigravityAcpAdapterFlavor( // Served reads are reported from the read handler, so they take turns with agent updates. const updates = yield* Semaphore.make(1); let projectUpdate: Parameters[0] | undefined; + // SCIENT-FORK:START — text held while it could begin a sign-in link goes out at prompt end. + const releaseHeldText = Effect.suspend(() => + projectUpdate === undefined + ? Effect.void + : updates.withPermit( + Effect.forEach(pluginSignIns.flush(generation), projectUpdate, { discard: true }), + ), + ).pipe(Effect.ignore); + // SCIENT-FORK:END return { ...runtime, handleReadTextFile: (handler) => @@ -227,11 +252,32 @@ export function makeAntigravityAcpAdapterFlavor( ), ), prompt: (payload, promptOptions) => - Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), + Effect.sync(reads.reset).pipe( + Effect.andThen(runtime.prompt(payload, promptOptions)), + // SCIENT-FORK: see releaseHeldText. + Effect.ensuring(releaseHeldText), + ), handleSessionUpdate: (handler) => { projectUpdate = handler; return runtime.handleSessionUpdate((notification) => - updates.withPermit(handler(reads.repair(notification))), + updates.withPermit( + // SCIENT-FORK:START — challenges are kept and scrubbed before anything projects them. + Effect.gen(function* () { + const repaired = reads.repair(notification); + const toolUpdate = + repaired.update.sessionUpdate === "tool_call" || + repaired.update.sessionUpdate === "tool_call_update"; + const attemptId = toolUpdate ? yield* options.random.uuidV4() : ""; + const projected = pluginSignIns.observe({ + generation, + notification: repaired, + now: yield* Clock.currentTimeMillis, + newId: () => attemptId, + }); + yield* Effect.forEach(projected, handler, { discard: true }); + }), + // SCIENT-FORK:END + ), ); }, start: () => @@ -367,6 +413,24 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, + // SCIENT-FORK:START — plugin sign-in notices and the pages they open. + scientToolNotice: (toolCallId, owner) => pluginSignIns.takeToolNotice(toolCallId, owner), + scientPluginSignIn: { + open: Effect.fn("AntigravityAdapterV2.pluginSignIn.open")(function* (input) { + const redeemed = pluginSignIns.redeem({ + attemptId: input.attemptId, + owner: input.owner, + nativeSessionId: input.nativeSessionId ?? undefined, + now: yield* Clock.currentTimeMillis, + }); + if ("url" in redeemed) return { authorizationUrl: redeemed.url }; + return yield* new PluginSignInError({ + reason: "expired", + detail: "This sign-in has ended. Ask the agent to try again.", + }); + }), + }, + // SCIENT-FORK:END extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, compactViaAdvertisedCommand: true, diff --git a/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.test.ts b/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.test.ts new file mode 100644 index 0000000000..6e49f79dde --- /dev/null +++ b/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.test.ts @@ -0,0 +1,92 @@ +import { expect, it } from "@effect/vitest"; +import { + AuthOrchestrationOperateScope, + AuthProvidersManageScope, + type OrchestrationV2ProviderThread, + ProviderSessionId, + ProviderThreadId, + RpcScopeAuthorization, + ThreadId, + WS_METHODS, + WsPluginSignInOpenRpc, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { RpcGroup, RpcTest } from "effect/rpc"; + +import type * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts"; +import type * as ThreadManagementService from "../../orchestration-v2/ThreadManagementService.ts"; +import * as RpcAuthorization from "../../auth/RpcAuthorization.ts"; +import { makePluginSignInRpcHandlers } from "./PluginSignInRpcHandlers.ts"; + +const threadId = ThreadId.make("thread-plugin-sign-in"); +const providerThreadId = ProviderThreadId.make("provider-thread-plugin-sign-in"); +const input = { threadId, providerThreadId, attemptId: "attempt-1" }; + +const harness = (options: { readonly live: boolean }) => { + const opened: Array = []; + const providerThread = { + id: providerThreadId, + providerSessionId: ProviderSessionId.make("provider-session-plugin-sign-in"), + } as OrchestrationV2ProviderThread; + const threadManagement = { + getThreadRecords: () => Effect.succeed({ providerThreads: [providerThread] }), + } as unknown as ThreadManagementService.ThreadManagementService["Service"]; + const providerSessions = { + get: () => + Effect.succeed( + options.live + ? Option.some({ + scientPluginSignIn: { + open: (request: unknown) => + Effect.sync(() => { + opened.push(request); + return { authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth" }; + }), + }, + }) + : Option.none(), + ), + } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]; + const group = RpcGroup.make(WsPluginSignInOpenRpc).middleware(RpcScopeAuthorization); + const layer = group.toLayer( + makePluginSignInRpcHandlers({ + observeRpcEffect: (_method, effect) => effect, + threadManagement, + providerSessions, + }), + ); + const client = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(layer, RpcAuthorization.layer(scopes))), + ); + return { client, opened, providerThread }; +}; + +it.effect("opens a plugin sign-in only with the provider management grant", () => + Effect.gen(function* () { + const { client, opened, providerThread } = harness({ live: true }); + const operator = yield* client([AuthOrchestrationOperateScope]); + expect(yield* operator[WS_METHODS.pluginSignInOpen](input).pipe(Effect.flip)).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredPermission: AuthProvidersManageScope, + }); + expect(opened).toEqual([]); + const manager = yield* client([AuthProvidersManageScope]); + expect(yield* manager[WS_METHODS.pluginSignInOpen](input)).toEqual({ + authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth", + }); + expect(opened).toEqual([{ threadId, providerThread, attemptId: "attempt-1" }]); + }).pipe(Effect.scoped), +); + +it.effect("reports an ended agent session as an expired sign-in", () => + Effect.gen(function* () { + const manager = yield* harness({ live: false }).client([AuthProvidersManageScope]); + expect(yield* manager[WS_METHODS.pluginSignInOpen](input).pipe(Effect.flip)).toMatchObject({ + _tag: "PluginSignInError", + reason: "expired", + }); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.ts b/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.ts new file mode 100644 index 0000000000..61ba2d422a --- /dev/null +++ b/apps/server/src/scient/antigravity/PluginSignInRpcHandlers.ts @@ -0,0 +1,91 @@ +/** + * Opens an Antigravity plugin sign-in from its chat notice. The page stays with the session that + * printed it; this resolves that live session for the thread and returns the page on a click. + */ +import { + type PluginSignInOpenInput, + PluginSignInError, + WS_METHODS, + type WsWorkspaceRpcGroup, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import * as Schema from "effect/Schema"; + +import type * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts"; +import type * as ThreadManagementService from "../../orchestration-v2/ThreadManagementService.ts"; +import type { ScientRpcHandlerSubset, ScientRpcObservers } from "../ScientRpcObservers.ts"; + +const isPluginSignInError = Schema.is(PluginSignInError); +const ended = new PluginSignInError({ + reason: "expired", + detail: "The agent session has ended. Ask the agent to try again.", +}); + +export const makePluginSignInRpcHandlers = ({ + observeRpcEffect, + threadManagement, + providerSessions, +}: Pick & { + readonly threadManagement: ThreadManagementService.ThreadManagementService["Service"]; + readonly providerSessions: ProviderSessionManager.ProviderSessionManagerV2["Service"]; +}) => { + const open = Effect.fn("PluginSignIn.open")( + function* (input: PluginSignInOpenInput) { + const { providerThreads } = yield* threadManagement.getThreadRecords(input.threadId, [ + "providerThreads", + ]); + const providerThread = providerThreads.find( + (candidate) => candidate.id === input.providerThreadId, + ); + if (providerThread?.providerSessionId == null) return yield* ended; + const runtime = Option.getOrUndefined( + yield* providerSessions.get(providerThread.providerSessionId), + ); + if (runtime === undefined) return yield* ended; + if (runtime.scientPluginSignIn === undefined) { + return yield* new PluginSignInError({ + reason: "unsupported", + detail: "This agent can't sign plugins in from Scient.", + }); + } + return yield* runtime.scientPluginSignIn.open({ + threadId: input.threadId, + providerThread, + attemptId: input.attemptId, + }); + }, + // Lookup failures can carry thread details; callers see one safe line. + (effect, input) => + effect.pipe( + Effect.catchIf( + (cause) => !isPluginSignInError(cause), + (cause) => + Effect.logWarning("plugin-sign-in.failed", { + threadId: input.threadId, + cause: Predicate.hasProperty(cause, "_tag") ? cause._tag : "unknown", + }).pipe( + Effect.andThen( + Effect.fail( + new PluginSignInError({ + reason: "failed", + detail: "Scient couldn't open this sign-in.", + }), + ), + ), + ), + ), + ), + ); + + return { + [WS_METHODS.pluginSignInOpen]: (input) => + observeRpcEffect(WS_METHODS.pluginSignInOpen, open(input), { + "rpc.aggregate": "provider", + }), + } satisfies ScientRpcHandlerSubset< + typeof WsWorkspaceRpcGroup, + typeof WS_METHODS.pluginSignInOpen + >; +}; diff --git a/apps/server/src/scient/antigravity/pluginSignIn.test.ts b/apps/server/src/scient/antigravity/pluginSignIn.test.ts new file mode 100644 index 0000000000..f373c3da38 --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginSignIn.test.ts @@ -0,0 +1,327 @@ +import { ProviderThreadId, ThreadId } from "@t3tools/contracts"; +import type * as EffectAcpSchema from "effect-acp/compat"; +import { describe, expect, it } from "vite-plus/test"; + +import { + extractPluginSignInChallenge, + extractToolCallChallenge, + LINK_REMOVED, + makeAntigravityPluginSignIns, + makeStreamRedactor, +} from "./pluginSignIn.ts"; + +const STATE = "synthetic-state-0123456789"; +const CHALLENGE_CODE = "synthetic-challenge-abcdef"; +const signInUrl = ( + overrides: Record = {}, + base = "https://accounts.google.com/o/oauth2/v2/auth", +) => { + const params = new URLSearchParams({ + access_type: "offline", + client_id: "synthetic-client.example", + code_challenge: CHALLENGE_CODE, + code_challenge_method: "S256", + prompt: "consent", + redirect_uri: "http://127.0.0.1:57512/callback", + response_type: "code", + scope: "https://www.googleapis.com/auth/gmail.readonly", + state: STATE, + ...overrides, + }); + return `${base}?${params.toString()}`; +}; +const URL_OK = signInUrl(); +const card = (slug = "gmail") => ``; +const challengeText = (url = URL_OK, cardText = card()) => + [ + "Command exited with code 1.", + "", + "Command output:", + "gmail: gmail/google needs authentication (not signed in). Show the user this card on its own line:\r", + `${cardText}\r`, + `Ask them to sign in to gmail, then try again. Only if the card can't be shown, give them this sign-in link instead: ${url}\r`, + ].join("\n"); + +describe("extractPluginSignInChallenge", () => { + it("reads the card and the loopback sign-in page", () => { + const challenge = extractPluginSignInChallenge(challengeText()); + expect(challenge?.plugin).toBe("gmail"); + expect(challenge?.authorizationUrl).toBe(URL_OK); + expect(challenge?.secrets).toEqual([URL_OK, STATE, CHALLENGE_CODE]); + }); + + it.each([ + ["no card", challengeText().replace(card(), "")], + ["two cards", challengeText(URL_OK, `${card()}${card("gdrive")}`)], + [ + "a nested card", + challengeText(URL_OK, `${card()}`), + ], + ["a malformed card", challengeText(URL_OK, ``)], + ["an oversized slug", challengeText(URL_OK, card("g".repeat(65)))], + ["two URLs", `${challengeText()} see https://example.com/help`], + ["a non-https page", challengeText(URL_OK.replace("https://", "http://"))], + ["an unknown endpoint", challengeText(signInUrl({}, "https://evil.example/o/oauth2/v2/auth"))], + [ + "a remote redirect", + challengeText(signInUrl({ redirect_uri: "http://10.0.0.5:57512/callback" })), + ], + [ + "an https redirect", + challengeText(signInUrl({ redirect_uri: "https://127.0.0.1:57512/callback" })), + ], + [ + "a redirect without a port", + challengeText(signInUrl({ redirect_uri: "http://localhost/callback" })), + ], + [ + "a privileged redirect port", + challengeText(signInUrl({ redirect_uri: "http://localhost:80/callback" })), + ], + [ + "another redirect path", + challengeText(signInUrl({ redirect_uri: "http://127.0.0.1:57512/other" })), + ], + ["no state", challengeText(URL_OK.replace(`&state=${STATE}`, ""))], + ["two states", challengeText(`${URL_OK}&state=second`)], + [ + "two redirects", + challengeText(`${URL_OK}&redirect_uri=http%3A%2F%2Flocalhost%3A9999%2Fcallback`), + ], + ["userinfo", challengeText(URL_OK.replace("https://", "https://user@"))], + ["a fragment", challengeText(`${URL_OK}#frag`)], + ["an oversized page", challengeText(signInUrl({ scope: "x".repeat(5_000) }))], + ])("refuses %s", (_label, text) => { + expect(extractPluginSignInChallenge(text)).toBeUndefined(); + }); + + it("accepts [::1] and localhost loopback redirects", () => { + for (const redirect_uri of ["http://[::1]:4000/callback", "http://localhost:4000/callback"]) { + expect( + extractPluginSignInChallenge(challengeText(signInUrl({ redirect_uri }))), + ).toBeDefined(); + } + }); +}); + +describe("extractToolCallChallenge", () => { + const output = challengeText(); + it("reads a tool result whose fields repeat the same text", () => { + expect( + extractToolCallChallenge({ + title: "gmail readonly search", + rawInput: { CommandLine: "gmail readonly search" }, + rawOutput: { output, exit_code: 1 }, + content: [{ type: "content", content: { type: "text", text: output } }], + })?.plugin, + ).toBe("gmail"); + }); + + it("refuses a challenge the call's own input wrote", () => { + expect( + extractToolCallChallenge({ + title: "echo", + rawInput: { CommandLine: `echo '${output}'` }, + rawOutput: { output }, + }), + ).toBeUndefined(); + }); + + it("refuses fields that disagree on the page", () => { + expect( + extractToolCallChallenge({ + rawOutput: { output }, + content: [ + { + type: "content", + content: { type: "text", text: challengeText(signInUrl({ state: "other-state" })) }, + }, + ], + }), + ).toBeUndefined(); + }); +}); + +describe("makeStreamRedactor", () => { + it("scrubs a pattern split across chunks and keeps the other text", () => { + const redactor = makeStreamRedactor(() => [{ text: URL_OK, replacement: LINK_REMOVED }]); + const text = `Open ${URL_OK} now.`; + const chunks = [text.slice(0, 9), text.slice(9, 60), text.slice(60, 200), text.slice(200)]; + const emitted = chunks.map((chunk) => redactor.push(chunk)).join("") + redactor.flush(); + expect(emitted).toBe(`Open ${LINK_REMOVED} now.`); + }); + + it("drops a standalone card and keeps an inline one", () => { + const patterns = () => [{ text: card(), replacement: "", standalone: true }]; + const standalone = makeStreamRedactor(patterns); + const out = + standalone.push("Sign in below:\n\n`) + + standalone.flush(); + expect(out).toBe("Sign in below:\n\n"); + const inline = makeStreamRedactor(patterns); + expect(inline.push(`see ${card()} here`) + inline.flush()).toBe(`see ${card()} here`); + }); +}); + +const owner = { + threadId: ThreadId.make("thread-1"), + providerThreadId: ProviderThreadId.make("provider-thread-1"), +}; +const toolUpdate = ( + toolCallId: string, + fields: Partial>, + sessionId = "session-1", +): EffectAcpSchema.SessionNotification => ({ + sessionId, + update: { sessionUpdate: "tool_call_update", toolCallId, ...fields }, +}); +const textChunk = (text: string, sessionId = "session-1"): EffectAcpSchema.SessionNotification => ({ + sessionId, + update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }, +}); +const challengeUpdate = () => + toolUpdate("call-1", { + status: "completed", + kind: "execute", + rawInput: { CommandLine: "gmail readonly search" }, + rawOutput: { output: challengeText(), exit_code: 1 }, + content: [{ type: "content", content: { type: "text", text: challengeText() } }], + }); +const textOf = (notifications: ReadonlyArray) => + notifications + .map((entry) => + entry.update.sessionUpdate === "agent_message_chunk" && entry.update.content.type === "text" + ? entry.update.content.text + : "", + ) + .join(""); + +describe("makeAntigravityPluginSignIns", () => { + const setup = (options?: { ttlMs?: number }) => { + const signIns = makeAntigravityPluginSignIns(options); + const generation = signIns.openGeneration(); + let ids = 0; + const observe = (notification: EffectAcpSchema.SessionNotification, now = 0) => + signIns.observe({ generation, notification, now, newId: () => `attempt-${++ids}` }); + return { signIns, generation, observe }; + }; + + it("scrubs the page from the projected tool call and offers it to its thread", () => { + const { signIns, observe } = setup(); + const projected = observe(challengeUpdate()); + expect(JSON.stringify(projected)).not.toContain(STATE); + expect(JSON.stringify(projected)).toContain(LINK_REMOVED); + const notice = signIns.takeToolNotice("call-1", owner); + expect(notice?.pluginSignIn).toEqual({ + attemptId: "attempt-1", + plugin: "gmail", + displayName: "Gmail", + }); + expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + expect( + signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), + ).toEqual({ url: URL_OK }); + }); + + it("never opens the page for another thread or session", () => { + const { signIns, observe } = setup(); + observe(challengeUpdate()); + signIns.takeToolNotice("call-1", owner); + const other = { ...owner, threadId: ThreadId.make("thread-2") }; + expect( + signIns.redeem({ + attemptId: "attempt-1", + owner: other, + nativeSessionId: "session-1", + now: 1, + }), + ).toEqual({ failure: "not-found" }); + expect( + signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-2", now: 1 }), + ).toEqual({ failure: "not-found" }); + }); + + it("expires attempts and retires them with their agent process", () => { + const { signIns, generation, observe } = setup({ ttlMs: 1_000 }); + observe(challengeUpdate()); + signIns.takeToolNotice("call-1", owner); + const redeem = (now: number) => + signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now }); + expect(redeem(1_000)).toEqual({ failure: "expired" }); + expect(redeem(999)).toEqual({ url: URL_OK }); + signIns.closeGeneration(generation); + expect(redeem(1)).toEqual({ failure: "expired" }); + }); + + it("ignores model text that writes a card or a page", () => { + const { signIns, observe } = setup(); + const projected = observe(textChunk(challengeText())); + expect(textOf(projected)).toBe(challengeText()); + expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + }); + + it("scrubs a repeated page across chunks and hides the repeated card", () => { + const { signIns, generation, observe } = setup(); + observe(challengeUpdate()); + const reply = `Sign in here: ${URL_OK}\n\n${card()}`; + const projected = [ + ...observe(textChunk(reply.slice(0, 30))), + ...observe(textChunk(reply.slice(30, 300))), + ...observe(textChunk(reply.slice(300))), + ...signIns.flush(generation), + ]; + expect(textOf(projected)).toBe(`Sign in here: ${LINK_REMOVED}\n\n`); + }); + + it("releases held text before the next update", () => { + const { observe } = setup(); + observe(challengeUpdate()); + const held = observe(textChunk("ends with h")); + expect(textOf(held)).toBe("ends with "); + const next = observe({ + sessionId: "session-1", + update: { sessionUpdate: "usage_update", used: 1, size: 2 }, + }); + expect(textOf(next)).toBe("h"); + expect(next.at(-1)?.update.sessionUpdate).toBe("usage_update"); + }); + + it("reports the plugin's next successful call as signed in", () => { + const { signIns, observe } = setup(); + observe(challengeUpdate()); + signIns.takeToolNotice("call-1", owner); + observe( + toolUpdate("call-2", { + status: "completed", + kind: "execute", + rawInput: { CommandLine: "gmail readonly search --max 3" }, + rawOutput: { output: "3 messages", exit_code: 0 }, + }), + ); + expect(signIns.takeToolNotice("call-2", owner)?.pluginSignIn).toEqual({ + attemptId: "attempt-1", + plugin: "gmail", + displayName: "Gmail", + signedIn: true, + }); + expect( + signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), + ).toEqual({ failure: "expired" }); + }); + + it("replaces an older attempt for the same plugin", () => { + const { signIns, observe } = setup(); + observe(challengeUpdate()); + signIns.takeToolNotice("call-1", owner); + const second = challengeText(signInUrl({ state: "second-state" })); + observe(toolUpdate("call-3", { status: "completed", rawOutput: { output: second } })); + signIns.takeToolNotice("call-3", owner); + expect( + signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), + ).toEqual({ failure: "expired" }); + expect( + signIns.redeem({ attemptId: "attempt-2", owner, nativeSessionId: "session-1", now: 1 }), + ).toEqual({ url: signInUrl({ state: "second-state" }) }); + }); +}); diff --git a/apps/server/src/scient/antigravity/pluginSignIn.ts b/apps/server/src/scient/antigravity/pluginSignIn.ts new file mode 100644 index 0000000000..20d475065c --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginSignIn.ts @@ -0,0 +1,603 @@ +/** + * Antigravity plugin sign-in, from the challenge a plugin's failed tool call prints. The live agy + * process listens on the challenge's loopback redirect, so opening the page while it runs + * finishes the sign-in there. Scient keeps the page server-side and never fetches it. + */ +import type { OrchestrationV2PluginSignIn, ProviderThreadId, ThreadId } from "@t3tools/contracts"; +import * as Predicate from "effect/Predicate"; +import type * as EffectAcpSchema from "effect-acp/compat"; + +const CARD_PATTERN = /<\/plugin-card>/u; +const SCHEME_PATTERN = /[a-z][a-z0-9+.-]*:\/\//giu; +const URL_TOKEN_PATTERN = /^[^\s<>"'`]+/u; +const MAX_TEXT_LENGTH = 32_000; +const MAX_URL_LENGTH = 4_096; +const MAX_STATE_LENGTH = 512; +const URL_SAFE_VALUE = /^[A-Za-z0-9._~-]+$/u; +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]); + +/** + * Where a plugin may send the user to sign in, as `host/path`. Only Google's own plugins are + * captured so far; a partner's endpoint joins once its challenge is recorded. + */ +const AUTHORIZATION_ENDPOINTS = new Set(["accounts.google.com/o/oauth2/v2/auth"]); + +const DISPLAY_NAMES: Readonly> = { + gmail: "Gmail", + gdrive: "Google Drive", + gdocs: "Google Docs", + gsheets: "Google Sheets", + gslides: "Google Slides", + gcalendar: "Google Calendar", +}; + +export const LINK_REMOVED = "[sign-in link removed]"; +const VALUE_REMOVED = "[removed]"; + +export interface PluginSignInChallenge { + readonly plugin: string; + readonly authorizationUrl: string; + /** Text to scrub wherever the agent repeats it. */ + readonly secrets: ReadonlyArray; +} + +const single = (params: URLSearchParams, name: string) => { + const values = params.getAll(name); + return values.length === 1 ? values[0] : undefined; +}; + +/** The sign-in page, when it is a known endpoint that redirects to a local agy listener. */ +function validatePluginAuthorizationUrl(raw: string): URL | undefined { + if (raw.length > MAX_URL_LENGTH || raw.includes("#")) return undefined; + let url: URL; + try { + url = new URL(raw); + } catch { + return undefined; + } + if ( + url.protocol !== "https:" || + url.username !== "" || + url.password !== "" || + url.port !== "" || + !AUTHORIZATION_ENDPOINTS.has(`${url.hostname}${url.pathname}`) + ) { + return undefined; + } + const state = single(url.searchParams, "state"); + const redirectUri = single(url.searchParams, "redirect_uri"); + if ( + state === undefined || + state.length === 0 || + state.length > MAX_STATE_LENGTH || + !URL_SAFE_VALUE.test(state) || + redirectUri === undefined || + url.searchParams.getAll("code_challenge").length > 1 + ) { + return undefined; + } + let redirect: URL; + try { + redirect = new URL(redirectUri); + } catch { + return undefined; + } + const port = Number(redirect.port); + if ( + redirect.protocol !== "http:" || + !LOOPBACK_HOSTS.has(redirect.hostname) || + !/^\d+$/u.test(redirect.port) || + port < 1024 || + port > 65_535 || + redirect.pathname !== "/callback" || + redirect.username !== "" || + redirect.password !== "" || + redirect.search !== "" || + redirect.hash !== "" || + redirectUri.includes("#") + ) { + return undefined; + } + return url; +} + +/** + * The challenge in one tool result text: exactly one well-formed card, and exactly one URL, + * which must be a valid sign-in page. + */ +export function extractPluginSignInChallenge(text: string): PluginSignInChallenge | undefined { + if (text.length > MAX_TEXT_LENGTH) return undefined; + if (text.split("plugin-card").length !== 3) return undefined; + const card = CARD_PATTERN.exec(text); + const plugin = card?.[1]; + if (plugin === undefined) return undefined; + const schemes = [...text.matchAll(SCHEME_PATTERN)]; + if (schemes.length !== 1) return undefined; + const token = URL_TOKEN_PATTERN.exec(text.slice(schemes[0]!.index))?.[0]; + if (token === undefined) return undefined; + const url = validatePluginAuthorizationUrl(token); + if (url === undefined) return undefined; + const secrets = [token, url.searchParams.get("state"), url.searchParams.get("code_challenge")]; + return { + plugin, + authorizationUrl: token, + secrets: secrets.filter((value): value is string => Predicate.isString(value) && value !== ""), + }; +} + +function pluginDisplayName(plugin: string): string | undefined { + return DISPLAY_NAMES[plugin]; +} + +function collectStrings(value: unknown, into: Array, depth = 0): void { + if (depth > 12 || into.length > 256) return; + if (Predicate.isString(value)) { + into.push(value); + } else if (Array.isArray(value)) { + for (const entry of value) collectStrings(entry, into, depth + 1); + } else if (Predicate.isObject(value)) { + for (const entry of Object.values(value)) collectStrings(entry, into, depth + 1); + } +} + +const replaceSecrets = (text: string, secrets: ReadonlyArray) => { + let result = text; + for (const [index, secret] of secrets.entries()) { + if (result.includes(secret)) { + result = result.split(secret).join(index === 0 ? LINK_REMOVED : VALUE_REMOVED); + } + } + return result; +}; + +/** A copy of `value` with every secret replaced, in any string at any depth. */ +function redactPluginSignInSecrets(value: A, secrets: ReadonlyArray): A { + const visit = (entry: unknown, depth: number): unknown => { + if (depth > 16) return entry; + if (Predicate.isString(entry)) return replaceSecrets(entry, secrets); + if (Array.isArray(entry)) return entry.map((item) => visit(item, depth + 1)); + if (Predicate.isObject(entry)) { + return Object.fromEntries( + Object.entries(entry).map(([key, item]) => [key, visit(item, depth + 1)]), + ); + } + return entry; + }; + return visit(value, 0) as A; +} + +/** The one challenge the tool's result carries; text the call was given never counts. */ +export function extractToolCallChallenge(update: { + readonly title?: string | null; + readonly rawInput?: unknown; + readonly rawOutput?: unknown; + readonly content?: unknown; +}): PluginSignInChallenge | undefined { + const inputs: Array = []; + collectStrings([update.title, update.rawInput], inputs); + if (inputs.some((text) => text.includes("plugin-card"))) return undefined; + const outputs: Array = []; + collectStrings([update.rawOutput, update.content], outputs); + let found: PluginSignInChallenge | undefined; + for (const text of outputs) { + if (!text.includes("plugin-card")) continue; + const challenge = extractPluginSignInChallenge(text); + if (challenge === undefined) return undefined; + if (found !== undefined && found.authorizationUrl !== challenge.authorizationUrl) { + return undefined; + } + found = challenge; + } + if (found === undefined) return undefined; + const state = found.secrets[1]; + if (state !== undefined && inputs.some((text) => text.includes(state))) return undefined; + return found; +} + +interface StreamPattern { + readonly text: string; + readonly replacement: string; + /** Removed only on a line of its own. */ + readonly standalone?: boolean; +} + +/** The earliest index whose rest of `buffer` begins some pattern without completing it. */ +function partialStart(buffer: string, patterns: ReadonlyArray): number { + let earliest = -1; + for (const pattern of patterns) { + const from = Math.max(0, buffer.length - pattern.text.length + 1); + for (let index = from; index < buffer.length; index++) { + if (earliest !== -1 && index >= earliest) break; + if (pattern.text.startsWith(buffer.slice(index))) { + earliest = index; + break; + } + } + } + return earliest; +} + +/** + * Scrubs patterns from text that arrives in chunks. It holds back a tail that could begin a + * pattern until the next chunk or `flush` decides it. + */ +export function makeStreamRedactor(patterns: () => ReadonlyArray) { + let carry = ""; + let previous = "\n"; + const emit = (text: string) => { + if (text.length > 0) previous = text.at(-1)!; + return text; + }; + const process = (input: string, final: boolean) => { + const active = patterns(); + let buffer = input; + let out = ""; + while (buffer.length > 0) { + let match: { index: number; pattern: StreamPattern } | undefined; + // A longer pattern still arriving holds its start, so a shorter one inside it waits. + const partial = final ? -1 : partialStart(buffer, active); + for (const pattern of active) { + const index = buffer.indexOf(pattern.text); + if (index !== -1 && (match === undefined || index < match.index)) { + match = { index, pattern }; + } + } + if (match === undefined || (partial !== -1 && partial <= match.index)) break; + const { index, pattern } = match; + const before = buffer.slice(0, index); + const end = index + pattern.text.length; + if (pattern.standalone === true) { + const lineStart = (before.length > 0 ? before.at(-1) : (out.at(-1) ?? previous)) === "\n"; + if (end === buffer.length && !final) { + out += before; + carry = buffer.slice(index); + return emit(out); + } + const next = buffer[end]; + const lineEnd = next === undefined || next === "\n" || next === "\r"; + out += before + (lineStart && lineEnd ? pattern.replacement : pattern.text); + } else { + out += before + pattern.replacement; + } + buffer = buffer.slice(end); + } + const start = final ? -1 : partialStart(buffer, active); + const hold = start === -1 ? 0 : buffer.length - start; + out += buffer.slice(0, buffer.length - hold); + carry = buffer.slice(buffer.length - hold); + return emit(out); + }; + return { + push: (chunk: string) => process(carry + chunk, false), + flush: () => { + const held = carry; + carry = ""; + return held.length === 0 ? "" : process(held, true); + }, + get holding() { + return carry.length > 0; + }, + }; +} + +export interface PluginSignInOwner { + readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; +} + +interface Attempt { + readonly id: string; + readonly plugin: string; + readonly url: string; + readonly secrets: ReadonlyArray; + readonly sessionId: string; + readonly generation: number; + readonly expiresAt: number; + owner: PluginSignInOwner | undefined; + live: boolean; + signedIn: boolean; +} + +export type PluginSignInRedeemFailure = "expired" | "not-found"; + +export interface PluginSignInToolNotice { + readonly title: string; + readonly message: string; + readonly level: "warning" | "info"; + readonly pluginSignIn: OrchestrationV2PluginSignIn; +} + +type Notification = EffectAcpSchema.SessionNotification; +type ChunkUpdate = Extract< + EffectAcpSchema.SessionUpdate, + { readonly sessionUpdate: "agent_message_chunk" | "agent_thought_chunk" } +>; + +const commandRunsPlugin = (command: string, plugin: string) => + new RegExp(`(?:^|[;&|]\\s*)${plugin}(?:\\s|$)`, "u").test(command.trim()); + +const exitCodeOf = (rawOutput: unknown) => { + if (!Predicate.isObject(rawOutput)) return undefined; + const code = rawOutput.exit_code ?? rawOutput.exitCode; + return Predicate.isNumber(code) ? code : undefined; +}; + +const commandOf = (rawInput: unknown) => { + if (!Predicate.isObject(rawInput)) return undefined; + const command = + rawInput.CommandLine ?? rawInput.command_line ?? rawInput.commandLine ?? rawInput.command; + return Predicate.isString(command) ? command : undefined; +}; + +/** + * Challenges a live Antigravity adapter has seen. Attempts belong to one agent process + * generation and expire; the notice names an attempt, and only its thread can open it. + */ +export function makeAntigravityPluginSignIns( + options: { + readonly ttlMs?: number; + readonly maxAttempts?: number; + } = {}, +) { + const ttlMs = options.ttlMs ?? 10 * 60_000; + const maxAttempts = options.maxAttempts ?? 64; + const attempts = new Map(); + const pendingNotices = new Map< + string, + { readonly attemptId: string; readonly signedIn: boolean } + >(); + const redactors = new Map< + string, + { readonly redactor: ReturnType; template: Notification } + >(); + // Each session's latest agent process, so a prompt's end releases only its own held text. + const sessionGenerations = new Map(); + let nextGeneration = 0; + + const sessionPatterns = (sessionId: string) => (): ReadonlyArray => { + const patterns: Array = []; + for (const attempt of attempts.values()) { + if (attempt.sessionId !== sessionId) continue; + for (const [index, secret] of attempt.secrets.entries()) { + patterns.push({ text: secret, replacement: index === 0 ? LINK_REMOVED : VALUE_REMOVED }); + } + if (attempt.live) { + patterns.push({ + text: ``, + replacement: "", + standalone: true, + }); + } + } + return patterns; + }; + const sessionHasAttempts = (sessionId: string) => + [...attempts.values()].some((attempt) => attempt.sessionId === sessionId); + const sessionSecrets = (sessionId: string) => + [...attempts.values()] + .filter((attempt) => attempt.sessionId === sessionId) + .flatMap((attempt) => attempt.secrets); + + /** Releases the held text of a session's channels other than `keep`. */ + const flushSession = (sessionId: string, keep?: string): ReadonlyArray => { + const flushed: Array = []; + for (const [key, entry] of redactors) { + if (key === keep || !key.startsWith(`${sessionId}\u0000`)) continue; + const text = entry.redactor.flush(); + if (text.length === 0) continue; + const update = entry.template.update; + flushed.push({ + ...entry.template, + update: + update.sessionUpdate === "tool_call_content_chunk" + ? { ...update, content: { type: "content", content: { type: "text", text } } } + : { ...(update as ChunkUpdate), content: { type: "text", text } }, + }); + } + return flushed; + }; + + const evict = () => { + while (attempts.size > maxAttempts) { + const oldest = attempts.keys().next().value; + if (oldest === undefined) break; + attempts.delete(oldest); + } + }; + + const streamChunk = ( + notification: Notification, + channel: string, + text: string, + rebuild: (text: string) => Notification, + ): ReadonlyArray => { + const key = `${notification.sessionId}\u0000${channel}`; + let entry = redactors.get(key); + if (entry === undefined) { + entry = { + redactor: makeStreamRedactor(sessionPatterns(notification.sessionId)), + template: notification, + }; + redactors.set(key, entry); + } + entry.template = notification; + const others = flushSession(notification.sessionId, key); + const emitted = entry.redactor.push(text); + return emitted.length === 0 ? others : [...others, rebuild(emitted)]; + }; + + return { + openGeneration: () => ++nextGeneration, + /** The agent process ended; its listeners are gone, so its pages can no longer finish. */ + closeGeneration: (generation: number) => { + for (const attempt of attempts.values()) { + if (attempt.generation === generation) attempt.live = false; + } + }, + /** + * The notifications to project in place of `notification`: challenge URLs scrubbed, text + * held back while it could begin one, and held text released before other updates. + */ + observe: (input: { + readonly generation: number; + readonly notification: Notification; + readonly now: number; + readonly newId: () => string; + }): ReadonlyArray => { + const { notification } = input; + const update = notification.update; + const sessionId = notification.sessionId; + sessionGenerations.set(sessionId, input.generation); + if ( + (update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk") && + update.content.type === "text" + ) { + if ( + !sessionHasAttempts(sessionId) && + !redactors.has(`${sessionId}\u0000${update.sessionUpdate}`) + ) { + return [notification]; + } + return streamChunk(notification, update.sessionUpdate, update.content.text, (text) => ({ + ...notification, + update: { ...update, content: { ...update.content, text } }, + })); + } + if (update.sessionUpdate === "tool_call_content_chunk") { + const content = update.content; + if ( + content.type === "content" && + content.content.type === "text" && + sessionHasAttempts(sessionId) + ) { + return streamChunk( + notification, + `tool:${update.toolCallId}`, + content.content.text, + (text) => ({ + ...notification, + update: { ...update, content: { ...content, content: { ...content.content, text } } }, + }), + ); + } + return [...flushSession(sessionId), notification]; + } + const flushed = flushSession(sessionId); + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { + return [...flushed, notification]; + } + const challenge = extractToolCallChallenge(update); + if (challenge !== undefined) { + let attempt = [...attempts.values()].find( + (candidate) => + candidate.sessionId === sessionId && candidate.url === challenge.authorizationUrl, + ); + if (attempt === undefined) { + for (const previous of attempts.values()) { + if (previous.sessionId === sessionId && previous.plugin === challenge.plugin) { + previous.live = false; + } + } + attempt = { + id: input.newId(), + plugin: challenge.plugin, + url: challenge.authorizationUrl, + secrets: challenge.secrets, + sessionId, + generation: input.generation, + expiresAt: input.now + ttlMs, + owner: undefined, + live: true, + signedIn: false, + }; + attempts.set(attempt.id, attempt); + evict(); + } + pendingNotices.set(update.toolCallId, { attemptId: attempt.id, signedIn: false }); + } else if (update.status === "completed" && exitCodeOf(update.rawOutput) === 0) { + const command = commandOf(update.rawInput); + const waiting = [...attempts.values()] + .toReversed() + .find( + (attempt) => + attempt.sessionId === sessionId && + !attempt.signedIn && + command !== undefined && + commandRunsPlugin(command, attempt.plugin), + ); + if (waiting !== undefined) { + waiting.signedIn = true; + waiting.live = false; + pendingNotices.set(update.toolCallId, { attemptId: waiting.id, signedIn: true }); + } + } + const secrets = sessionSecrets(sessionId); + const scrubbed = + secrets.length === 0 + ? notification + : { ...notification, update: redactPluginSignInSecrets(update, secrets) }; + return [...flushed, scrubbed]; + }, + /** Held text of an agent process's sessions, released when its prompt ends. */ + flush: (generation: number) => + [...sessionGenerations] + .filter(([, owner]) => owner === generation) + .flatMap(([sessionId]) => flushSession(sessionId)), + /** The notice a tool call raised, once; it binds the attempt to the thread that shows it. */ + takeToolNotice: ( + toolCallId: string, + owner: PluginSignInOwner, + ): PluginSignInToolNotice | undefined => { + const pending = pendingNotices.get(toolCallId); + if (pending === undefined) return undefined; + pendingNotices.delete(toolCallId); + const attempt = attempts.get(pending.attemptId); + if (attempt === undefined) return undefined; + attempt.owner ??= owner; + const displayName = pluginDisplayName(attempt.plugin); + const name = displayName ?? attempt.plugin; + const pluginSignIn = { + attemptId: attempt.id, + plugin: attempt.plugin, + ...(displayName === undefined ? {} : { displayName }), + ...(pending.signedIn ? { signedIn: true } : {}), + }; + return pending.signedIn + ? { + title: `Signed in to ${name}`, + message: `Antigravity used ${name} after the sign-in.`, + level: "info", + pluginSignIn, + } + : { + title: `Sign in to ${name}`, + message: `${name} needs a sign-in before Antigravity can use it.`, + level: "warning", + pluginSignIn, + }; + }, + /** The sign-in page, only for the thread that showed the attempt while its agent still runs. */ + redeem: (input: { + readonly attemptId: string; + readonly owner: PluginSignInOwner; + readonly nativeSessionId: string | undefined; + readonly now: number; + }): { readonly url: string } | { readonly failure: PluginSignInRedeemFailure } => { + const attempt = attempts.get(input.attemptId); + if ( + attempt === undefined || + attempt.owner === undefined || + attempt.owner.threadId !== input.owner.threadId || + attempt.owner.providerThreadId !== input.owner.providerThreadId || + attempt.sessionId !== input.nativeSessionId + ) { + return { failure: "not-found" }; + } + if (!attempt.live || input.now >= attempt.expiresAt) return { failure: "expired" }; + return { url: attempt.url }; + }, + }; +} + +export type AntigravityPluginSignIns = ReturnType; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 5b9cfd8c6d..0bfc97316a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -345,6 +345,9 @@ import { makeEditorFlushRpcHandlers } from "./scient/editorFlush/EditorFlushRpcH import { makeLiveVoiceRpcHandlers } from "./scient/liveVoice/LiveVoiceRpcHandlers.ts"; import { makeChatGptDictationRpcHandlers } from "./scient/voice/ChatGptDictationRpcHandlers.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — Antigravity plugin sign-in from its chat notice. +import { makePluginSignInRpcHandlers } from "./scient/antigravity/PluginSignInRpcHandlers.ts"; +// SCIENT-FORK:END // SCIENT-FORK:START — Scient Connect on the desktop's own computer. import { makeScientConnectRpcHandlers } from "./scient/connect/ScientConnectRpcHandlers.ts"; // SCIENT-FORK:END @@ -2270,6 +2273,13 @@ export const layerWsRpc = ( }), ...makeChatGptDictationRpcHandlers({ observeRpcEffect, providerInstances }), // SCIENT-FORK:END + // SCIENT-FORK:START — Antigravity plugin sign-in from its chat notice. + ...makePluginSignInRpcHandlers({ + observeRpcEffect, + threadManagement, + providerSessions: providerSessionsV2, + }), + // SCIENT-FORK:END // SCIENT-FORK:START — thread rooms. [WS_METHODS.threadRoomInvite]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( diff --git a/packages/contracts/src/clientRpcPermissions.scient.test.ts b/packages/contracts/src/clientRpcPermissions.scient.test.ts index 56b4c14a5e..501c81331b 100644 --- a/packages/contracts/src/clientRpcPermissions.scient.test.ts +++ b/packages/contracts/src/clientRpcPermissions.scient.test.ts @@ -3,6 +3,7 @@ import { AuthFilesystemWriteScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + AuthProvidersManageScope, AuthSettingsWriteScope, sessionGrantsScope, type AuthSessionState, @@ -82,3 +83,27 @@ describe("Linked results client authorization", () => { } }); }); + +describe("Plugin sign-in client authorization", () => { + it("takes the provider management grant, as an MCP sign-in does", () => { + const operator: AuthSessionState = { + authenticated: true, + scopes: [AuthOrchestrationOperateScope], + permissions: [AuthOrchestrationOperateScope], + auth: { + policy: "remote-reachable", + bootstrapMethods: [], + sessionMethods: [], + sessionCookieName: "synthetic", + }, + }; + const manager = { + ...operator, + scopes: [AuthProvidersManageScope], + permissions: [AuthProvidersManageScope], + }; + const scopes = clientRpcRequiredScopes(WS_METHODS.pluginSignInOpen, {}); + expect(scopes.every((scope) => sessionGrantsScope(operator, scope))).toBe(false); + expect(scopes.every((scope) => sessionGrantsScope(manager, scope))).toBe(true); + }); +}); diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index dca37e5bc3..21f3b8328b 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -107,6 +107,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { // An MCP sign-in stores a credential for the agent, as an account sign-in does. [WS_METHODS.providerMcpSignInStart]: AuthProvidersManageScope, [WS_METHODS.providerMcpSignInComplete]: AuthProvidersManageScope, + // SCIENT-FORK: an Antigravity plugin sign-in takes the same grant as an MCP sign-in. + [WS_METHODS.pluginSignInOpen]: AuthProvidersManageScope, [WS_METHODS.previewClose]: AuthPreviewOperateScope, // Stopping a server signals its processes, as closing a terminal does. [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 71bfe49621..42ad6e94ab 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -189,6 +189,9 @@ export * from "./scient/editorFlush.ts"; export * from "./scient/liveVoice.ts"; export * from "./scient/chatGptDictation.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — Antigravity plugin sign-in contracts (new file, no upstream edits). +export * from "./scient/pluginSignIn.ts"; +// SCIENT-FORK:END // SCIENT-FORK:START — Scient Files panel entry changes (new file, no upstream edits). export * from "./scient/workspaceEntryChanges.ts"; // SCIENT-FORK:END diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 121d99b869..803c501947 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -63,6 +63,9 @@ export { OrchestrationV2ProviderRuntimePolicy, OrchestrationV2SubagentPresentation, } from "./scient/orchestrationV2Schemas.ts"; +// SCIENT-FORK:START — a notice can offer an Antigravity plugin sign-in. +import { OrchestrationV2PluginSignIn } from "./scient/pluginSignIn.ts"; +// SCIENT-FORK:END import { makeMessageForkItems, makeTurnItemBaseFields, @@ -2162,6 +2165,9 @@ export const OrchestrationV2TurnItem = Schema.Union([ message: Schema.String, level: Schema.optional(OrchestrationV2SystemNoticeLevel), mcpSignIn: Schema.optional(OrchestrationV2McpSignIn), + // SCIENT-FORK:START — an Antigravity plugin sign-in the notice offers. + pluginSignIn: Schema.optional(OrchestrationV2PluginSignIn), + // SCIENT-FORK:END }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -3090,6 +3096,9 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ message: Schema.String, level: Schema.optional(OrchestrationV2SystemNoticeLevel), mcpSignIn: Schema.optional(OrchestrationV2McpSignIn), + // SCIENT-FORK:START — an Antigravity plugin sign-in the notice offers. + pluginSignIn: Schema.optional(OrchestrationV2PluginSignIn), + // SCIENT-FORK:END }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index c17e4696ce..00dcbf14ce 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -697,6 +697,9 @@ import { WsVoiceDictateWithChatGptRpc, } from "./scient/chatGptDictation.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — Antigravity plugin sign-in from its chat notice. +import { SCIENT_PLUGIN_SIGN_IN_WS_METHODS, WsPluginSignInOpenRpc } from "./scient/pluginSignIn.ts"; +// SCIENT-FORK:END // SCIENT-FORK:START — Scient editor flush RPCs. import { SCIENT_EDITOR_FLUSH_WS_METHODS, @@ -790,6 +793,9 @@ export const WS_METHODS = { ...SCIENT_LIVE_VOICE_WS_METHODS, ...SCIENT_CHATGPT_DICTATION_WS_METHODS, // SCIENT-FORK:END + // SCIENT-FORK:START — Antigravity plugin sign-in from its chat notice. + ...SCIENT_PLUGIN_SIGN_IN_WS_METHODS, + // SCIENT-FORK:END // SCIENT-FORK:START — Scient Files panel entry changes. ...SCIENT_WORKSPACE_ENTRY_WS_METHODS, // SCIENT-FORK:END @@ -3023,6 +3029,9 @@ export const WsWorkspaceRpcGroup = RpcGroup.make( WsLiveVoiceMuteRpc, WsVoiceDictateWithChatGptRpc, // SCIENT-FORK:END + // SCIENT-FORK:START — Antigravity plugin sign-in from its chat notice. + WsPluginSignInOpenRpc, + // SCIENT-FORK:END // SCIENT-FORK:START — Scient editor flush RPCs. WsEditorsFlushConnectRpc, WsEditorsFlushLeaveRpc, diff --git a/packages/contracts/src/scient/pluginSignIn.ts b/packages/contracts/src/scient/pluginSignIn.ts new file mode 100644 index 0000000000..f9373a949c --- /dev/null +++ b/packages/contracts/src/scient/pluginSignIn.ts @@ -0,0 +1,62 @@ +import * as Schema from "effect/Schema"; +import * as Rpc from "effect/rpc/Rpc"; + +import { EnvironmentAuthorizationError } from "../auth.ts"; +import { ProviderThreadId, ThreadId, TrimmedNonEmptyString } from "../baseSchemas.ts"; +import { SignInUrl } from "../providerSetup.ts"; + +export const PluginSignInAttemptId = TrimmedNonEmptyString.check(Schema.isMaxLength(128)); +export const PluginSignInSlug = Schema.String.check( + Schema.isMaxLength(64), + Schema.isPattern(/^[a-z0-9][a-z0-9_-]*$/u), +); + +/** + * A plugin the agent could not use until the user signs in. The sign-in page stays on the + * environment; the notice only names the attempt that can open it. + */ +export const OrchestrationV2PluginSignIn = Schema.Struct({ + attemptId: PluginSignInAttemptId, + plugin: PluginSignInSlug, + displayName: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(128))), + /** Set on the notice that reports the plugin's next call succeeded. */ + signedIn: Schema.optional(Schema.Boolean), +}); +export type OrchestrationV2PluginSignIn = typeof OrchestrationV2PluginSignIn.Type; + +export const PluginSignInOpenInput = Schema.Struct({ + threadId: ThreadId, + providerThreadId: ProviderThreadId, + attemptId: PluginSignInAttemptId, +}); +export type PluginSignInOpenInput = typeof PluginSignInOpenInput.Type; + +export const PluginSignInOpenResult = Schema.Struct({ + /** The page the running agent waits on; it finishes the sign-in itself. */ + authorizationUrl: SignInUrl, +}); +export type PluginSignInOpenResult = typeof PluginSignInOpenResult.Type; + +/** Safe to show: never carries the sign-in URL. */ +export class PluginSignInError extends Schema.TaggedError()( + "PluginSignInError", + { + reason: Schema.Literals(["expired", "unsupported", "failed"]), + detail: Schema.String, + }, +) { + override get message(): string { + return this.detail; + } +} + +/** Spread into rpc.ts WS_METHODS. */ +export const SCIENT_PLUGIN_SIGN_IN_WS_METHODS = { + pluginSignInOpen: "scient.pluginSignIn.open", +} as const; + +export const WsPluginSignInOpenRpc = Rpc.make(SCIENT_PLUGIN_SIGN_IN_WS_METHODS.pluginSignInOpen, { + payload: PluginSignInOpenInput, + success: PluginSignInOpenResult, + error: Schema.Union([PluginSignInError, EnvironmentAuthorizationError]), +}); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 34de496ada..81d15aa9c1 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -33,6 +33,8 @@ import { type ThreadId, isRuntimeModeAbove, type TurnTokenUsage, + // SCIENT-FORK: plugin sign-in failures are safe to show. + type PluginSignInError, } from "@t3tools/contracts"; import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope"; import { MODEL_TOKEN_LIMIT_MESSAGE, modelSelectionsEqual } from "@t3tools/shared/model"; @@ -788,6 +790,21 @@ export interface AcpAdapterV2Flavor { ) => AcpAdapterV2SubagentUpdate | undefined; readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean; readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; + // SCIENT-FORK:START — typed notices about root tool calls, and the plugin sign-ins they offer. + /** The notice a root tool call raised, taken once; `owner` is the thread that shows it. */ + readonly scientToolNotice?: ( + toolCallId: string, + owner: { readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId }, + ) => ProviderAdapter.ScientToolNotice | undefined; + readonly scientPluginSignIn?: { + readonly open: (input: { + readonly owner: { readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId }; + /** The live root session, or null when no agent process runs. */ + readonly nativeSessionId: string | null; + readonly attemptId: string; + }) => Effect.Effect<{ readonly authorizationUrl: string }, PluginSignInError>; + }; + // SCIENT-FORK:END readonly isCancelledToolCall?: (payload: unknown) => boolean; readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined; readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined; @@ -5435,6 +5452,47 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); }); + // SCIENT-FORK:START — see AcpAdapterV2Flavor.scientToolNotice. + const emitScientToolNotice = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + toolCallId: string, + ) { + const notice = flavor.scientToolNotice?.(toolCallId, { + threadId: context.input.threadId, + providerThreadId: context.input.providerThread.id, + }); + if (notice === undefined) return; + const nativeItemId = `${toolCallId}:plugin-sign-in:${notice.pluginSignIn.attemptId}${ + notice.pluginSignIn.signedIn === true ? ":signed-in" : "" + }`; + const now = yield* DateTime.now; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver, + turnItem: { + id: providerTurnItemId(nativeItemId), + threadId: context.input.threadId, + runId: context.input.runId, + nodeId: context.input.rootNodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" }, + parentItemId: null, + ordinal: yield* resolveItemOrdinal(context, nativeItemId), + type: "system_notice", + status: "completed", + title: notice.title, + message: notice.message, + level: notice.level, + pluginSignIn: notice.pluginSignIn, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); + }); + // SCIENT-FORK:END + const emitPlan = Effect.fnUntraced(function* ( context: ActiveAcpTurn, update: AcpPlanUpdate, @@ -6757,6 +6815,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( for (const event of parsed.events) { if (event._tag === "ToolCallUpdated") { yield* emitTool(context, event.toolCall, undefined, event.rawPayload); + // SCIENT-FORK: see AcpAdapterV2Flavor.scientToolNotice. + yield* emitScientToolNotice(context, event.toolCall.toolCallId); } else if (event._tag === "PlanUpdated") { yield* emitPlan(context, event.payload, update.sessionUpdate !== "plan"); } else if (event._tag === "NoticeReceived") { @@ -11343,6 +11403,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ), ), + // SCIENT-FORK:START — see AcpAdapterV2Flavor.scientPluginSignIn. + ...(flavor.scientPluginSignIn === undefined + ? {} + : { + scientPluginSignIn: { + open: Effect.fn("AcpAdapterV2.scientPluginSignIn.open")(function* ({ + threadId, + providerThread, + attemptId, + }) { + const pluginSignIn = flavor.scientPluginSignIn!; + return yield* pluginSignIn.open({ + owner: { threadId, providerThreadId: providerThread.id }, + nativeSessionId: yield* Ref.get(activeSessionId), + attemptId, + }); + }), + }, + }), + // SCIENT-FORK:END readThreadSnapshot: Effect.fn("AcpAdapterV2.readThreadSnapshot")( function* (snapshotInput) { return yield* runtimeTransitionPermit.withPermit( diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index d7a4e8e2b7..b24fb06a91 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -53,6 +53,10 @@ export * from "./scientTextSnapshots.ts"; import type { ScientLiveVoiceRuntime } from "./scientLiveVoice.ts"; export * from "./scientLiveVoice.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — Antigravity plugin sign-in lives in a Scient module. +import type { ScientPluginSignInRuntime } from "./scientPluginSignIn.ts"; +export * from "./scientPluginSignIn.ts"; +// SCIENT-FORK:END export const ProviderAdapterV2RuntimePolicy = OrchestrationV2ProviderRuntimePolicy; export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type; @@ -930,6 +934,9 @@ export interface ProviderAdapterV2SessionRuntime extends ScientTextSnapshotRunti // SCIENT-FORK:START — a spoken conversation with the running session; absent means none. readonly liveVoice?: ScientLiveVoiceRuntime; // SCIENT-FORK:END + // SCIENT-FORK:START — opens a plugin sign-in the session's notice offered; absent means none. + readonly scientPluginSignIn?: ScientPluginSignInRuntime; + // SCIENT-FORK:END /** Absent when the agent has no way to sign an MCP server in. */ readonly mcpSignIn?: ProviderAdapterV2McpSignIn; readonly rollbackThread: ( diff --git a/packages/provider-core/src/server/scientPluginSignIn.ts b/packages/provider-core/src/server/scientPluginSignIn.ts new file mode 100644 index 0000000000..3441b29f75 --- /dev/null +++ b/packages/provider-core/src/server/scientPluginSignIn.ts @@ -0,0 +1,26 @@ +// Scient plugin sign-in: the provider-side contract for opening a plugin's sign-in page that a +// session's notice offered. Re-exported from ProviderAdapter.ts; only Antigravity implements it. +import type { + OrchestrationV2PluginSignIn, + OrchestrationV2ProviderThread, + PluginSignInError, + ThreadId, +} from "@t3tools/contracts"; +import type * as Effect from "effect/Effect"; + +export interface ScientPluginSignInRuntime { + /** The validated page, only for the thread whose notice named the attempt, while it is live. */ + readonly open: (input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly attemptId: string; + }) => Effect.Effect<{ readonly authorizationUrl: string }, PluginSignInError>; +} + +/** A typed notice an adapter shows after a tool call's row. */ +export interface ScientToolNotice { + readonly title: string; + readonly message: string; + readonly level: "info" | "warning"; + readonly pluginSignIn: OrchestrationV2PluginSignIn; +} From dec6a89565dc8959401cb82de86cdf9bb9a5dafa Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:51:44 +0200 Subject: [PATCH 07/36] feat(web): sign in to an Antigravity plugin from its chat notice A pluginSignIn notice shows "Sign in to " in the timeline's action slot. A click asks the environment for the page and opens it in the user's browser; the running agent receives the callback itself. It then reads "Signed in" once the plugin's next call works or the user says so, asks for a new attempt when the sign-in has ended, and offers nothing on a client that is not on the agent's computer. Co-Authored-By: Claude Opus 5.5 --- .../components/chat/TimelineWorkEntryRow.tsx | 16 +- 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 + .../PluginSignInAction.browser.test.tsx | 128 +++++++++++++++ .../scient/antigravity/PluginSignInAction.tsx | 154 ++++++++++++++++++ .../antigravity/pluginSignInCommands.ts | 10 ++ 14 files changed, 337 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx create mode 100644 apps/web/src/scient/antigravity/PluginSignInAction.tsx create mode 100644 apps/web/src/scient/antigravity/pluginSignInCommands.ts diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 447b7129e3..9d867838ad 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -43,6 +43,9 @@ import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; import { workGroupImageGallery } from "./markdownImageGallery"; import { McpSignInAction } from "./McpSignInAction"; +// SCIENT-FORK:START — Antigravity plugin sign-in from its notice. +import { PluginSignInAction } from "~/scient/antigravity/PluginSignInAction"; +// SCIENT-FORK:END import * as DateTime from "effect/DateTime"; import { ChevronRightIcon, CircleAlertIcon, RotateCcwIcon } from "lucide-react"; import { Button, InlineButton } from "../ui/button"; @@ -467,7 +470,18 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { server={payload.mcpSignIn.server} noticeAt={DateTime.toEpochMillis(payload.updatedAt)} /> - ) : null; + ) : // SCIENT-FORK:START — an Antigravity plugin sign-in takes the same slot. + payload?.type === "system_notice" && + payload.pluginSignIn !== undefined && + payload.providerThreadId !== null ? ( + + ) : // SCIENT-FORK:END + null; const skill = payload?.type === "dynamic_tool" ? claudeSkillInvocation(payload.toolName, payload.input) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0a94ffe835..d6107e50fd 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13634,6 +13634,9 @@ "5e28fbfe8c80326d": "Zeige auf der Taskleistenschaltfläche an, wie viele Threads eine ungelesene Antwort haben. Falls die Zahl nicht erscheint, aktiviere Signale unter Windows-Einstellungen › Personalisierung › Taskleiste.", "1ef20ad33fb24e7a": "Zeige auf dem App-Symbol an, wie viele Threads eine ungelesene Antwort haben, in Docks, die Kennzeichen unterstützen.", "8c29afaa8ee680f1": "Kennzeichen des App-Symbols auf Standard zurücksetzen", + "209eb1a6178759be": "Melde dich auf dem Computer an, auf dem dieser Agent läuft", + "1e408bc92329ef14": "Bitte den Agenten, es erneut zu versuchen", + "d0306d84e8796706": "Ich habe mich angemeldet", "d39168b94ca3c906": "Abbildung neu laden", "d1f9b4871e00639f": "Schwebende Abbildung schließen", "8fc545093daec445": "Abbildung über dem Chat schweben lassen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 908a289a9d..27c2389ae1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13641,6 +13641,9 @@ "5e28fbfe8c80326d": "Show how many threads have an unread answer on the taskbar button. If the count doesn't appear, turn on badges in Windows Settings › Personalization › Taskbar.", "1ef20ad33fb24e7a": "Show how many threads have an unread answer on the app icon, in docks that support badges.", "8c29afaa8ee680f1": "Reset app icon badge to default", + "209eb1a6178759be": "Sign in on the computer that runs this agent", + "1e408bc92329ef14": "Ask the agent to try again", + "d0306d84e8796706": "I've signed in", "d39168b94ca3c906": "Reload figure", "d1f9b4871e00639f": "Close floating figure", "8fc545093daec445": "Float figure over chat", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index e338ea73fd..1ac2032120 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13625,6 +13625,9 @@ "5e28fbfe8c80326d": "Muestra en el botón de la barra de tareas cuántos hilos tienen una respuesta sin leer. Si el número no aparece, activa las insignias en Configuración de Windows › Personalización › Barra de tareas.", "1ef20ad33fb24e7a": "Muestra en el icono de la app cuántos hilos tienen una respuesta sin leer, en los docks que admiten insignias.", "8c29afaa8ee680f1": "Restablecer la insignia del icono de la app al valor predeterminado", + "209eb1a6178759be": "Inicia sesión en el ordenador que ejecuta este agente", + "1e408bc92329ef14": "Pide al agente que lo intente de nuevo", + "d0306d84e8796706": "Ya he iniciado sesión", "d39168b94ca3c906": "Recargar la figura", "d1f9b4871e00639f": "Cerrar la figura flotante", "8fc545093daec445": "Hacer flotar la figura sobre el chat", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 2cd2f9f2a8..70e7ac97c6 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13629,6 +13629,9 @@ "5e28fbfe8c80326d": "Affiche sur le bouton de la barre des tâches le nombre de fils ayant une réponse non lue. Si le nombre n’apparaît pas, activez les badges dans Paramètres Windows › Personnalisation › Barre des tâches.", "1ef20ad33fb24e7a": "Affiche sur l’icône de l’app le nombre de fils ayant une réponse non lue, dans les docks qui prennent en charge les badges.", "8c29afaa8ee680f1": "Rétablir le badge de l’icône de l’app par défaut", + "209eb1a6178759be": "Connecte-toi sur l’ordinateur qui exécute cet agent", + "1e408bc92329ef14": "Demande à l’agent de réessayer", + "d0306d84e8796706": "Je me suis connecté", "d39168b94ca3c906": "Recharger la figure", "d1f9b4871e00639f": "Fermer la figure flottante", "8fc545093daec445": "Faire flotter la figure au-dessus de la discussion", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index cac0f6a899..425fa19281 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13567,6 +13567,9 @@ "5e28fbfe8c80326d": "未読の回答があるスレッドの数をタスクバーのボタンに表示します。数が表示されない場合は、Windows の設定 › 個人用設定 › タスクバー でバッジをオンにしてください。", "1ef20ad33fb24e7a": "バッジに対応した Dock で、未読の回答があるスレッドの数をアプリアイコンに表示します。", "8c29afaa8ee680f1": "アプリアイコンのバッジをデフォルトにリセット", + "209eb1a6178759be": "このエージェントを実行しているコンピューターでサインインしてください", + "1e408bc92329ef14": "エージェントにもう一度試すよう依頼してください", + "d0306d84e8796706": "サインインしました", "d39168b94ca3c906": "図を再読み込み", "d1f9b4871e00639f": "フローティングの図を閉じる", "8fc545093daec445": "図をチャットの上にフロート表示", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 539e1fd702..d3d2b71ae2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13571,6 +13571,9 @@ "5e28fbfe8c80326d": "읽지 않은 답변이 있는 스레드 수를 작업 표시줄 버튼에 표시합니다. 숫자가 표시되지 않으면 Windows 설정 › 개인 설정 › 작업 표시줄에서 배지를 켜세요.", "1ef20ad33fb24e7a": "읽지 않은 답변이 있는 스레드 수를 배지를 지원하는 독의 앱 아이콘에 표시합니다.", "8c29afaa8ee680f1": "앱 아이콘 배지를 기본값으로 재설정", + "209eb1a6178759be": "이 에이전트를 실행하는 컴퓨터에서 로그인하세요", + "1e408bc92329ef14": "에이전트에게 다시 시도하도록 요청하세요", + "d0306d84e8796706": "로그인했습니다", "d39168b94ca3c906": "그림 다시 불러오기", "d1f9b4871e00639f": "플로팅 그림 닫기", "8fc545093daec445": "채팅 위에 그림 띄우기", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index bd0ffca124..c1af0c7b3c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13630,6 +13630,9 @@ "5e28fbfe8c80326d": "Mostra no botão da barra de tarefas quantas threads têm uma resposta não lida. Se a contagem não aparecer, ative os indicadores em Configurações do Windows › Personalização › Barra de tarefas.", "1ef20ad33fb24e7a": "Mostra no ícone do app quantas threads têm uma resposta não lida, em docks compatíveis com indicadores.", "8c29afaa8ee680f1": "Redefinir o indicador do ícone do app para o padrão", + "209eb1a6178759be": "Entre no computador que executa este agente", + "1e408bc92329ef14": "Peça ao agente para tentar novamente", + "d0306d84e8796706": "Já entrei", "d39168b94ca3c906": "Recarregar figura", "d1f9b4871e00639f": "Fechar figura flutuante", "8fc545093daec445": "Flutuar a figura sobre o chat", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 7dce06d54a..e1d6cf26f8 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13632,6 +13632,9 @@ "5e28fbfe8c80326d": "Показывать на кнопке панели задач, сколько тредов с непрочитанным ответом. Если число не появляется, включите индикаторы в «Параметры Windows › Персонализация › Панель задач».", "1ef20ad33fb24e7a": "Показывать на значке приложения, сколько тредов с непрочитанным ответом, в доках с поддержкой индикаторов.", "8c29afaa8ee680f1": "Сбросить индикатор на значке приложения", + "209eb1a6178759be": "Войдите на компьютере, где работает этот агент", + "1e408bc92329ef14": "Попросите агента попробовать снова", + "d0306d84e8796706": "Я вошёл", "d39168b94ca3c906": "Перезагрузить рисунок", "d1f9b4871e00639f": "Закрыть плавающий рисунок", "8fc545093daec445": "Открепить рисунок поверх чата", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 51c0a0bdba..034d37c37d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13638,6 +13638,9 @@ "5e28fbfe8c80326d": "Visa på aktivitetsfältsknappen hur många trådar som har ett oläst svar. Om antalet inte visas, slå på brickor i Windows-inställningar › Anpassning › Aktivitetsfält.", "1ef20ad33fb24e7a": "Visa på appsymbolen hur många trådar som har ett oläst svar, i dockor som stöder brickor.", "8c29afaa8ee680f1": "Återställ appsymbolens bricka till standard", + "209eb1a6178759be": "Logga in på datorn som kör den här agenten", + "1e408bc92329ef14": "Be agenten att försöka igen", + "d0306d84e8796706": "Jag har loggat in", "d39168b94ca3c906": "Läs in figuren igen", "d1f9b4871e00639f": "Stäng flytande figur", "8fc545093daec445": "Låt figuren flyta över chatten", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index b677f46c35..25d597848b 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13661,6 +13661,9 @@ "5e28fbfe8c80326d": "在任务栏按钮上显示有未读回复的会话数量。如果数字没有出现,请在“Windows 设置 › 个性化 › 任务栏”中开启角标。", "1ef20ad33fb24e7a": "在支持角标的程序坞中,在应用图标上显示有未读回复的会话数量。", "8c29afaa8ee680f1": "将应用图标角标重置为默认值", + "209eb1a6178759be": "请在运行此智能体的电脑上登录", + "1e408bc92329ef14": "请让智能体重试", + "d0306d84e8796706": "我已登录", "d39168b94ca3c906": "重新加载图", "d1f9b4871e00639f": "关闭浮动图", "8fc545093daec445": "在聊天上方浮动显示图", diff --git a/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx b/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx new file mode 100644 index 0000000000..71e8e9bfe4 --- /dev/null +++ b/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx @@ -0,0 +1,128 @@ +import "~/index.css"; +import { EnvironmentId, PluginSignInError, ProviderThreadId, ThreadId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { Atom } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; +import { localEnvironmentIdAtom } from "../../state/primaryEnvironment"; +import { PluginSignInAction } from "./PluginSignInAction"; + +const environmentId = EnvironmentId.make("synthetic-local"); +const threadId = ThreadId.make("thread-plugin"); +const providerThreadId = ProviderThreadId.make("provider-thread-plugin"); +const pluginSignIn = { attemptId: "attempt-1", plugin: "gmail", displayName: "Gmail" }; +const SIGN_IN_PAGE = "https://accounts.google.com/o/oauth2/v2/auth?state=synthetic"; + +const fixture = vi.hoisted(() => ({ + items: [] as Array<{ readonly item: unknown }>, + open: vi.fn(), + opening: "opened" as "opened" | "blocked", +})); + +vi.mock("./pluginSignInCommands", () => ({ + pluginSignInOpenCommand: { permissionAtom: () => Atom.make(true) }, +})); +vi.mock("../../state/primaryEnvironment", () => ({ + localEnvironmentIdAtom: Atom.make("synthetic-local"), +})); +vi.mock("../../state/entities", () => ({ + useQuietThreadVisibleTurnItems: () => fixture.items, +})); +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: () => fixture.open, +})); +vi.mock("../extensions/openAuthorizationPage", () => ({ + openAuthorizationPage: async (requestUrl: () => Promise) => { + const url = await requestUrl(); + if (url === null) return { outcome: "not-started" }; + return fixture.opening === "opened" ? { outcome: "opened" } : { outcome: "blocked", url }; + }, +})); + +const local = localEnvironmentIdAtom as Atom.Writable; + +/** Resets the shared fixture when the test ends. */ +function setup() { + return { + [Symbol.dispose]: () => { + fixture.items = []; + fixture.opening = "opened"; + fixture.open.mockReset(); + appAtomRegistry.set(local, "synthetic-local"); + }, + }; +} + +const action = (overrides: Partial = {}) => ( + + + +); + +it("opens the page on a click, then takes the user's word that they signed in", async () => { + using _fixture = setup(); + fixture.open.mockResolvedValue({ _tag: "Success", value: { authorizationUrl: SIGN_IN_PAGE } }); + await using _screen = await render(action()); + await page.getByRole("button", { name: "Sign in to Gmail" }).click(); + expect(fixture.open).toHaveBeenCalledWith({ + environmentId, + input: { threadId, providerThreadId, attemptId: "attempt-1" }, + }); + await page.getByRole("button", { name: "I've signed in" }).click(); + await expect.element(page.getByText("Signed in")).toBeVisible(); +}); + +it("offers the page as a link when the browser blocked the new tab", async () => { + using _fixture = setup(); + fixture.opening = "blocked"; + fixture.open.mockResolvedValue({ _tag: "Success", value: { authorizationUrl: SIGN_IN_PAGE } }); + await using _screen = await render(action()); + await page.getByRole("button", { name: "Sign in to Gmail" }).click(); + await expect + .element(page.getByRole("link", { name: "Open sign-in page" })) + .toHaveAttribute("href", SIGN_IN_PAGE); +}); + +it("asks for a new attempt once the agent's sign-in has ended", async () => { + using _fixture = setup(); + fixture.open.mockResolvedValue({ + _tag: "Failure", + cause: Cause.fail(new PluginSignInError({ reason: "expired", detail: "ended" })), + }); + await using _screen = await render(action()); + await page.getByRole("button", { name: "Sign in to Gmail" }).click(); + await expect.element(page.getByText("Ask the agent to try again")).toBeVisible(); +}); + +it("shows Signed in once the plugin's next call worked", async () => { + using _fixture = setup(); + fixture.items = [ + { + item: { + type: "system_notice", + pluginSignIn: { ...pluginSignIn, signedIn: true }, + }, + }, + ]; + await using _screen = await render(action()); + await expect.element(page.getByText("Signed in")).toBeVisible(); + await expect.element(page.getByRole("button")).not.toBeInTheDocument(); +}); + +it("never offers the page to a client on another computer", async () => { + using _fixture = setup(); + appAtomRegistry.set(local, null); + await using _screen = await render(action()); + await expect + .element(page.getByText("Sign in on the computer that runs this agent")) + .toBeVisible(); + expect(fixture.open).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/scient/antigravity/PluginSignInAction.tsx b/apps/web/src/scient/antigravity/PluginSignInAction.tsx new file mode 100644 index 0000000000..0c22f767c2 --- /dev/null +++ b/apps/web/src/scient/antigravity/PluginSignInAction.tsx @@ -0,0 +1,154 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + type EnvironmentId, + type OrchestrationV2PluginSignIn, + PluginSignInError, + type ProviderThreadId, + type ThreadId, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import * as Cause from "effect/Cause"; +import * as Schema from "effect/Schema"; +import { T, useGT } from "gt-react"; +import { useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; + +import { InlineButton } from "../../components/ui/button"; +import { formatEnvironmentQueryError } from "../../state/query"; +import { useQuietThreadVisibleTurnItems } from "../../state/entities"; +import { localEnvironmentIdAtom } from "../../state/primaryEnvironment"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { openAuthorizationPage } from "../extensions/openAuthorizationPage"; +import { pluginSignInOpenCommand } from "./pluginSignInCommands"; + +type Phase = + | { readonly phase: "idle" | "opening" | "opened" | "expired" | "confirmed" } + | { readonly phase: "blocked"; readonly url: string } + | { readonly phase: "failed"; readonly message: string }; + +const isPluginSignInError = Schema.is(PluginSignInError); +const stopRowToggle = (event: KeyboardEvent | MouseEvent) => + event.stopPropagation(); + +/** + * Signs an Antigravity plugin in from the notice its failed call raised. The running agent + * listens for the browser's return on this computer, so the page opens only here. + */ +export function PluginSignInAction({ + environmentId, + threadId, + providerThreadId, + pluginSignIn, +}: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; + readonly pluginSignIn: OrchestrationV2PluginSignIn; +}) { + const gt = useGT(); + const allowed = useAtomValue(pluginSignInOpenCommand.permissionAtom(environmentId)); + const localEnvironmentId = useAtomValue(localEnvironmentIdAtom); + const items = useQuietThreadVisibleTurnItems(scopeThreadRef(environmentId, threadId)); + const open = useAtomCommand(pluginSignInOpenCommand, { reportFailure: false }); + const [state, setState] = useState({ phase: "idle" }); + // Counts clicks, so a slow answer to an older click changes nothing. + const attempt = useRef(0); + const name = pluginSignIn.displayName ?? pluginSignIn.plugin; + const signedInLater = items.some( + ({ item }) => + item.type === "system_notice" && + item.pluginSignIn?.attemptId === pluginSignIn.attemptId && + item.pluginSignIn.signedIn === true, + ); + + if (pluginSignIn.signedIn === true || signedInLater || state.phase === "confirmed") { + return ( + + Signed in + + ); + } + if (!allowed) return null; + if (localEnvironmentId !== environmentId) { + return ( + + Sign in on the computer that runs this agent + + ); + } + if (state.phase === "expired") { + return ( + + Ask the agent to try again + + ); + } + + const begin = async () => { + const current = ++attempt.current; + setState({ phase: "opening" }); + let failure: Phase | null = null; + const opening = await openAuthorizationPage(async () => { + const result = await open({ + environmentId, + input: { threadId, providerThreadId, attemptId: pluginSignIn.attemptId }, + }); + if (result._tag === "Success") return result.value.authorizationUrl; + const error = Cause.squash(result.cause); + failure = + isPluginSignInError(error) && error.reason === "expired" + ? { phase: "expired" } + : { phase: "failed", message: formatEnvironmentQueryError(result.cause) }; + return null; + }); + if (current !== attempt.current) return; + if (opening.outcome === "opened") setState({ phase: "opened" }); + else if (opening.outcome === "blocked") setState({ phase: "blocked", url: opening.url }); + else setState(failure ?? { phase: "idle" }); + }; + + return ( + <> + {state.phase === "blocked" ? ( + } + onClick={(event) => { + stopRowToggle(event); + setState({ phase: "opened" }); + }} + onKeyDown={stopRowToggle} + > + Open sign-in page + + ) : ( + { + stopRowToggle(event); + void begin(); + }} + onKeyDown={stopRowToggle} + > + {gt("Sign in to {server}", { server: name })} + + )} + {state.phase === "opened" ? ( + { + stopRowToggle(event); + setState({ phase: "confirmed" }); + }} + onKeyDown={stopRowToggle} + > + I've signed in + + ) : null} + {state.phase === "failed" ? ( + + {state.message} + + ) : null} + + ); +} diff --git a/apps/web/src/scient/antigravity/pluginSignInCommands.ts b/apps/web/src/scient/antigravity/pluginSignInCommands.ts new file mode 100644 index 0000000000..2d8e1be955 --- /dev/null +++ b/apps/web/src/scient/antigravity/pluginSignInCommands.ts @@ -0,0 +1,10 @@ +import { createEnvironmentRpcCommand } from "@t3tools/client-runtime/state/runtime"; +import { WS_METHODS } from "@t3tools/contracts"; + +import { connectionAtomRuntime } from "../../connection/runtime.ts"; + +/** Outside the thread's queue: opening a sign-in must not wait on the agent's turn. */ +export const pluginSignInOpenCommand = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "web:plugin-sign-in:open", + tag: WS_METHODS.pluginSignInOpen, +}); From d10f3dbd64b5e828b51c6f8c09a8c2a309e67db8 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 22:57:35 +0200 Subject: [PATCH 08/36] feat(chat): finish an MCP sign-in without pasting when the browser is local When the browser runs on the agent's computer, Codex receives the OAuth callback itself and reports mcpServer/oauthLogin/completed, but the sign-in dialog still asked for the landing address. complete now accepts no address and then waits, bounded to five minutes, for the agent's own success report. The dialog starts that wait when it opens the sign-in page and closes with "Signed in"; pasting stays for remote setups. Claude reports no finished sign-in, so without an address it only succeeds when the server already shows as connected. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 7 ++ .../CodexAdapterV2.mcpSignIn.scient.test.ts | 112 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 23 +++- .../McpSignInAction.scient.browser.test.tsx | 89 ++++++++++++++ .../src/components/chat/McpSignInAction.tsx | 19 ++- packages/contracts/src/provider.ts | 4 +- .../src/server/ProviderAdapter.ts | 4 +- 7 files changed, 250 insertions(+), 8 deletions(-) create mode 100644 apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.mcpSignIn.scient.test.ts create mode 100644 apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9e1b870c65..6ef1285955 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -15915,6 +15915,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); // A browser on this machine may already have finished it on Claude's own page. if (statuses.find((status) => status.name === server)?.status === "connected") return; + // SCIENT-FORK:START — Claude reports no finished sign-in, so it needs the address. + if (callbackUrl === undefined) { + return yield* fail( + "Paste the address your browser went to after you approved to finish the sign-in.", + ); + } + // SCIENT-FORK:END const pasted = yield* Effect.try({ try: () => pastedUrl(callbackUrl).toString(), catch: () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.mcpSignIn.scient.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.mcpSignIn.scient.test.ts new file mode 100644 index 0000000000..143525ba03 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.mcpSignIn.scient.test.ts @@ -0,0 +1,112 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +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 { TestClock } from "effect/testing"; +import type * as CodexReplay from "effect-codex-app-server/replay"; + +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { + codexReplayPreamble, + makeCodexReplayHarness, + makeCodexReplayTranscript, +} from "./CodexAdapterV2.replay.testkit.ts"; + +const nativeThreadId = "mcp-sign-in-browser-thread"; +const authorizationUrl = + "https://linear.example/authorize?redirect_uri=http%3A%2F%2F127.0.0.1%3A50123%2Fcallback&state=s1"; + +const signInEntries = (completed: boolean): Array => [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "unused", prompt: "work" }).slice(0, 5), + { + type: "expect_outbound", + label: "mcpServerStatus/list", + frame: { + id: 3, + method: "mcpServerStatus/list", + params: { serverName: "linear", threadId: nativeThreadId, detail: "toolsAndAuthOnly" }, + }, + }, + { + type: "emit_inbound", + label: "mcpServerStatus/list", + frame: { id: 3, result: { data: [] } }, + }, + { + type: "expect_outbound", + label: "mcpServer/oauth/login", + frame: { + id: 4, + method: "mcpServer/oauth/login", + params: { name: "linear", threadId: nativeThreadId }, + }, + }, + { + type: "emit_inbound", + label: "mcpServer/oauth/login", + frame: { id: 4, result: { authorizationUrl } }, + }, + ...(completed + ? [ + { + type: "emit_inbound" as const, + label: "mcpServer/oauthLogin/completed", + frame: { + method: "mcpServer/oauthLogin/completed", + params: { name: "linear", threadId: nativeThreadId, success: true }, + }, + }, + ] + : []), +]; + +const layer = Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, +); + +describe("CodexAdapterV2 MCP sign-in without a pasted address", () => { + it.effect("finishes once Codex reports its own callback page was reached", () => + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-mcp-sign-in-browser", + entries: signInEntries(true), + }), + ); + const mcpSignIn = harness.runtime.mcpSignIn!; + const input = { providerThread: harness.providerThread, server: "linear" }; + assert.deepEqual(yield* mcpSignIn.start(input), { authorizationUrl }); + yield* mcpSignIn.complete({ ...input, callbackUrl: undefined }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("gives up after a bounded wait so the address can still be pasted", () => + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-mcp-sign-in-browser-silent", + entries: signInEntries(false), + }), + ); + const mcpSignIn = harness.runtime.mcpSignIn!; + const input = { providerThread: harness.providerThread, server: "linear" }; + yield* mcpSignIn.start(input); + const waiting = yield* mcpSignIn + .complete({ ...input, callbackUrl: undefined }) + .pipe(Effect.exit, Effect.forkChild); + yield* TestClock.adjust("4 minutes"); + assert.isUndefined(waiting.pollUnsafe()); + yield* TestClock.adjust("1 minute"); + const exit = yield* Fiber.join(waiting); + assert.isTrue(Exit.isFailure(exit)); + assert.include(String(Exit.isFailure(exit) ? exit.cause : ""), "Paste the address"); + }).pipe(Effect.provide(layer)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 202850c7bc..ebbe7ff715 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1031,6 +1031,8 @@ interface CodexMcpSignIn { } const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); +// SCIENT-FORK: how long a sign-in without a pasted address waits for Codex to report it. +const CODEX_MCP_SIGN_IN_BROWSER_WAIT = "5 minutes"; const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* ( providerThread: OrchestrationV2ProviderThread, @@ -9282,7 +9284,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (signIn === undefined) return yield* fail(`Start the sign-in to ${server} again.`); // A browser on this machine may already have opened Codex's callback page. let delivered = true; - if (!(yield* Deferred.isDone(signIn.succeeded))) { + // SCIENT-FORK:START — no address waits for a browser here to reach Codex's own page. + const waitsForBrowser = callbackUrl === undefined; + if (!waitsForBrowser && !(yield* Deferred.isDone(signIn.succeeded))) { + // SCIENT-FORK:END const callback = yield* Effect.try({ try: () => oauthCallbackUrl(callbackUrl, signIn.redirectUri, signIn.state), catch: () => @@ -9308,15 +9313,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } const succeeded = yield* Deferred.await(signIn.succeeded).pipe( Effect.timeoutOrElse({ - duration: delivered ? "30 seconds" : "2 seconds", + // SCIENT-FORK:START — see waitsForBrowser. + duration: waitsForBrowser + ? CODEX_MCP_SIGN_IN_BROWSER_WAIT + : delivered + ? "30 seconds" + : "2 seconds", orElse: () => Effect.fail( fail( - delivered - ? `Codex didn't finish the sign-in to ${server}. Start again.` - : `Codex didn't take the sign-in to ${server}. Start again.`, + waitsForBrowser + ? `Codex didn't hear back from the sign-in to ${server}. Paste the address your browser went to, or start again.` + : delivered + ? `Codex didn't finish the sign-in to ${server}. Start again.` + : `Codex didn't take the sign-in to ${server}. Start again.`, ), ), + // SCIENT-FORK:END }), ); // A newer start may have replaced this sign-in while it finished. diff --git a/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx b/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx new file mode 100644 index 0000000000..43c3d61f87 --- /dev/null +++ b/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx @@ -0,0 +1,89 @@ +import "~/index.css"; +import { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { McpSignInAction } from "./McpSignInAction"; + +const fixture = vi.hoisted(() => ({ + start: vi.fn(), + complete: vi.fn(), + openExternal: vi.fn(), +})); + +vi.mock("../../state/threads", () => { + const start = { permissionAtom: () => Atom.make(true) }; + const complete = {}; + return { + threadEnvironment: { + mcpSignInStart: start, + mcpSignInComplete: complete, + mcpSignedInAtom: () => Atom.make(false), + }, + }; +}); +vi.mock("../../state/use-atom-command", async () => { + const { threadEnvironment } = await import("../../state/threads"); + return { + useAtomCommand: (command: unknown) => + command === threadEnvironment.mcpSignInStart ? fixture.start : fixture.complete, + }; +}); +vi.mock("../../localApi", () => ({ + ensureLocalApi: () => ({ shell: { openExternal: fixture.openExternal } }), +})); + +function setup() { + fixture.start.mockResolvedValue({ + _tag: "Success", + value: { authorizationUrl: "https://linear.example/authorize", signedInAt: null }, + }); + return { + [Symbol.dispose]: () => { + fixture.start.mockReset(); + fixture.complete.mockReset(); + fixture.openExternal.mockReset(); + }, + }; +} + +const action = ( + +); + +it("finishes without a pasted address once the agent reports the browser reached it", async () => { + using _fixture = setup(); + fixture.complete.mockResolvedValue({ _tag: "Success", value: { signedInAt: "2026-01-01" } }); + await using _screen = await render(action); + await page.getByRole("button", { name: "Sign in to linear" }).click(); + await page.getByRole("button", { name: "Open sign-in page" }).click(); + expect(fixture.openExternal).toHaveBeenCalledWith("https://linear.example/authorize"); + await expect.element(page.getByRole("dialog")).not.toBeInTheDocument(); + expect(fixture.complete).toHaveBeenCalledWith({ + environmentId: "synthetic", + input: { + threadId: "thread-mcp", + providerThreadId: "provider-thread-mcp", + server: "linear", + }, + }); +}); + +it("keeps the paste field when the agent never reports the sign-in", async () => { + using _fixture = setup(); + fixture.complete.mockResolvedValue({ _tag: "Failure", cause: undefined }); + await using _screen = await render(action); + await page.getByRole("button", { name: "Sign in to linear" }).click(); + await page.getByRole("button", { name: "Open sign-in page" }).click(); + await expect + .element(page.getByRole("textbox", { name: "Address of the page your browser opened" })) + .toBeVisible(); +}); diff --git a/apps/web/src/components/chat/McpSignInAction.tsx b/apps/web/src/components/chat/McpSignInAction.tsx index 63c5d9e49d..f121ba7c6e 100644 --- a/apps/web/src/components/chat/McpSignInAction.tsx +++ b/apps/web/src/components/chat/McpSignInAction.tsx @@ -61,6 +61,8 @@ export function McpSignInAction({ const [callbackUrl, setCallbackUrl] = useState(""); // Counts attempts, so a result that lands after a close or a restart changes nothing. const attempt = useRef(0); + // SCIENT-FORK: the attempt already waiting for the agent's report; see awaitBrowser. + const awaiting = useRef(-1); if (!allowed) return null; const input = { threadId, providerThreadId, server }; @@ -101,6 +103,17 @@ export function McpSignInAction({ done(); } }; + // SCIENT-FORK:START — a browser on the agent's computer reaches its callback page itself, so + // the sign-in finishes when the agent reports it; pasting stays for other setups. + const awaitBrowser = async () => { + const current = attempt.current; + if (awaiting.current === current) return; + awaiting.current = current; + const result = await complete({ environmentId, input }); + if (current !== attempt.current || result._tag === "Failure") return; + done(); + }; + // SCIENT-FORK:END const url = signIn !== null && signIn.phase !== "starting" ? signIn.url : null; return ( @@ -156,7 +169,11 @@ export function McpSignInAction({ + + + ); +} + +/** + * An Antigravity agent's row for a service its marketplace has as a plugin. Shown only once the + * store answers and can add plugins; being added claims nothing about the plugin's own sign-in. + */ +function AntigravityServiceRow({ + route, + provider, +}: { + readonly route: AccountServiceRoute & { readonly storeEntryId: string }; + readonly provider: ServerProvider; +}) { + const gt = useGT(); + const { environmentId } = useExtensionsEnvironment(); + const registry = useContext(RegistryContext); + const atom = extensionsProviderStoreEntry({ + environmentId, + input: { instanceId: route.instanceId, entryId: route.storeEntryId }, + }); + const entry = useEnvironmentQuery(atom); + const plugin = provider.plugins?.find((item) => item.id === route.storeEntryId); + if (entry.error || entry.data?.storeUnavailable) return null; + const state = + entry.data === null || entry.data.installationStateKnown === false ? "checking" : route.state; + return ( + + + + {route.label} + + {state === "added" + ? gt("Added · signs in the first time a chat uses it") + : state === "add" && entry.data?.disabledReason + ? entry.data.disabledReason + : gt("Through its Antigravity Marketplace plugin")} + + + {state === "checking" ? ( + + Checking… + + ) : state === "off" ? ( + plugin?.canSetEnabled ? ( + + ) : ( + + Off in Antigravity + + ) + ) : state === "added" ? null : ( + + registry.refresh(atom)} + /> + + )} + + ); +} + /** Each agent's place for a service, with its action, as on Gmail's page and plugin pages. */ export function ServiceAgents({ service }: { readonly service: AccountService }) { const gt = useGT(); @@ -146,6 +251,14 @@ export function ServiceAgents({ service }: { readonly service: AccountService })
{routes.map((route) => { const provider = providers.find((entry) => entry.instanceId === route.instanceId); + if (route.family === "antigravity") + return provider && route.storeEntryId ? ( + + ) : null; // Scient Agent signs in to ChatGPT right here; the agent runs the sign-in. const inline = route.driver === "scient" && provider?.connection?.accounts; return ( diff --git a/apps/web/src/scient/extensions/accountServices.test.ts b/apps/web/src/scient/extensions/accountServices.test.ts index 9337c4381d..c791b15960 100644 --- a/apps/web/src/scient/extensions/accountServices.test.ts +++ b/apps/web/src/scient/extensions/accountServices.test.ts @@ -236,4 +236,62 @@ describe("account services", () => { false, ); }); + + it("routes Antigravity through its marketplace plugin, never as connected", () => { + const entryId = "gmail@antigravity-plugins-official"; + const antigravity = (plugins: ServerProvider["plugins"]) => + provider("antigravity", plugins === undefined ? {} : { plugins }); + const plugin = (enabled: boolean) => ({ + id: entryId, + name: "gmail", + source: "local" as const, + enabled, + }); + const state = (plugins: ServerProvider["plugins"]) => + accountServiceRoutes(gmail, [antigravity(plugins)]).map((route) => [ + route.family, + route.state, + ]); + expect(state(undefined)).toEqual([["antigravity", "checking"]]); + expect(state([])).toEqual([["antigravity", "add"]]); + expect(state([plugin(true)])).toEqual([["antigravity", "added"]]); + expect(state([plugin(false)])).toEqual([["antigravity", "off"]]); + // A same-name plugin from another source is not the marketplace entry. + expect(state([{ ...plugin(true), id: "antigravity:gmail" }])).toEqual([["antigravity", "add"]]); + const routes = accountServiceRoutes(gmail, [antigravity([plugin(true)])]); + expect(accountServiceAudience(routes)).toEqual({ + layer: "account", + connected: [], + pending: [], + }); + expect(nextAccountServiceStep(routes)).toBeUndefined(); + expect(installedAccountServices([antigravity([plugin(false)])], null)).toEqual([]); + // A service without an Antigravity plugin gets no Antigravity row. + expect( + accountServiceRoutes(accountServiceForApp({ name: "Pets", id: "connector_pets" })!, [ + antigravity([]), + ]), + ).toEqual([]); + }); + + it("names exact Antigravity plugins for services and hides only those store duplicates", () => { + expect(gmail.stores?.antigravity).toBe("gmail@antigravity-plugins-official"); + expect(accountServiceForApp({ name: "Canva", id: "connector_canva" })?.stores).toEqual({ + antigravity: "canva@antigravity-plugins-partners", + }); + const entry = (id: string, name: string, displayName: string) => ({ + id, + name, + displayName, + apps: [], + }); + expect( + isAccountServiceStoreEntry( + entry("gdrive@antigravity-plugins-official", "gdrive", "Drive files"), + ), + ).toBe(true); + expect( + isAccountServiceStoreEntry(entry("canva@antigravity-plugins-partners", "canva", "Canva")), + ).toBe(false); + }); }); diff --git a/apps/web/src/scient/extensions/accountServices.ts b/apps/web/src/scient/extensions/accountServices.ts index 0d144b0857..c495fea25a 100644 --- a/apps/web/src/scient/extensions/accountServices.ts +++ b/apps/web/src/scient/extensions/accountServices.ts @@ -9,7 +9,7 @@ import { msg } from "gt-react"; import { m, type MessageResolver } from "~/i18n/messages"; import CLAUDE_CONNECTORS from "./claudeConnectors.json" with { type: "json" }; -import { providerLabel } from "./extensionsView"; +import { providerAvailable, providerLabel } from "./extensionsView"; /** * A service people connect to an agent's own account: a ChatGPT app and a claude.ai connector @@ -36,6 +36,10 @@ export interface AccountService { * Absent, Claude has no route to it and none is offered. */ readonly claude?: { readonly name: string; readonly page: string } | undefined; + /** Exact agent-store entries for the same service; Antigravity's is `@`. */ + readonly stores?: + | { readonly claude?: string; readonly codex?: string; readonly antigravity?: string } + | undefined; } const comparable = (name: string) => name.toLowerCase().replace(/[^a-z0-9]/g, ""); @@ -88,6 +92,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ websiteUrl: "https://mail.google.com", chatgptAppId: "connector_2128aebfecb84f64a069897515042a44", claude: claudeConnectorFor("Gmail"), + stores: { antigravity: "gmail@antigravity-plugins-official" }, }, { id: "google-calendar", @@ -100,6 +105,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ websiteUrl: "https://calendar.google.com", chatgptAppId: "connector_947e0d954944416db111db556030eea6", claude: claudeConnectorFor("Google Calendar"), + stores: { antigravity: "gcalendar@antigravity-plugins-official" }, }, { id: "google-drive", @@ -112,6 +118,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ websiteUrl: "https://drive.google.com", chatgptAppId: "connector_5f3c8c41a1e54ad7a76272c89e2554fa", claude: claudeConnectorFor("Google Drive"), + stores: { antigravity: "gdrive@antigravity-plugins-official" }, }, ]; @@ -140,6 +147,29 @@ const slug = (name: string) => /** The ChatGPT app id at the end of a `chatgpt.com/apps//` page. */ const appIdOf = (url: string | undefined) => url?.match(/\/apps\/[^/]+\/([A-Za-z0-9_-]+)/)?.[1]; +/** ChatGPT apps whose service is exactly an Antigravity Marketplace plugin, by app name. */ +const ANTIGRAVITY_PLUGINS_BY_APP: Readonly> = { + googledocs: "gdocs@antigravity-plugins-official", + googlesheets: "gsheets@antigravity-plugins-official", + googleslides: "gslides@antigravity-plugins-official", + dropbox: "dropbox@antigravity-plugins-partners", + notion: "notion@antigravity-plugins-partners", + linear: "linear@antigravity-plugins-partners", + figma: "figma@antigravity-plugins-partners", + canva: "canva@antigravity-plugins-partners", + atlassian: "atlassian-twg-cli@antigravity-plugins-partners", + monday: "monday@antigravity-plugins-partners", + mondaycom: "monday@antigravity-plugins-partners", + clickup: "clickup@antigravity-plugins-partners", + zapier: "zapier@antigravity-plugins-partners", + stripe: "stripe@antigravity-plugins-partners", + intercom: "intercom@antigravity-plugins-partners", + trello: "trello@antigravity-plugins-partners", + granola: "granola@antigravity-plugins-partners", + docusign: "docusign@antigravity-plugins-partners", + pandadoc: "pandadoc@antigravity-plugins-partners", +}; + /** * Any other ChatGPT app is a service too: Codex and Scient Agent reach it through ChatGPT, and * Claude through a claude.ai connector of the same name, if it has one. @@ -157,6 +187,7 @@ export function accountServiceForApp(app: { const id = app.id ?? appIdOf(app.installUrl); if (!id) return undefined; const claude = claudeConnectorFor(app.name); + const antigravity = ANTIGRAVITY_PLUGINS_BY_APP[comparable(app.name)]; return { id: slug(app.name), name: app.name, @@ -173,6 +204,7 @@ export function accountServiceForApp(app: { categories: [], chatgptAppId: id, claude, + ...(antigravity ? { stores: { antigravity } } : {}), }; } @@ -239,13 +271,16 @@ export function installedAccountServices( ) || accountServiceRoutes(service, providers).some( (route) => - (route.state === "connected" || route.state === "off") && chosen(route.instanceId), + route.family !== "antigravity" && + (route.state === "connected" || route.state === "off") && + chosen(route.instanceId), ), ); } /** A Codex store entry that is only one of these services' apps, which Scient lists itself. */ export function isAccountServiceStoreEntry(entry: { + readonly id?: string | undefined; readonly name: string; readonly displayName: string; readonly apps: ReadonlyArray<{ readonly id?: string | undefined; readonly name: string }>; @@ -255,6 +290,7 @@ export function isAccountServiceStoreEntry(entry: { (service) => names.includes(service.name.toLowerCase()) || names.includes(service.id) || + (entry.id !== undefined && service.stores?.antigravity === entry.id) || entry.apps.some((app) => app.id === service.chatgptAppId), ); } @@ -264,13 +300,27 @@ export interface AccountServiceRoute { readonly instanceId: ServerProvider["instanceId"]; readonly driver: ServerProvider["driver"]; readonly label: string; - /** ChatGPT apps reach Codex and Scient Agent; claude.ai connectors reach Claude. */ - readonly family: "chatgpt" | "claude"; + /** + * ChatGPT apps reach Codex and Scient Agent; claude.ai connectors reach Claude; an Antigravity + * Marketplace plugin reaches Antigravity. + */ + readonly family: "chatgpt" | "claude" | "antigravity"; /** * `off`: the agent has it but the person turned it off there. `checking`: the agent's - * inventory is not read yet, so nothing is claimed. + * inventory is not read yet, so nothing is claimed. Store plugins are `add` until installed, + * then `added`, never `connected`: their sign-in happens in a chat. */ - readonly state: "connected" | "connect" | "sign-in" | "off" | "checking" | "update"; + readonly state: + | "connected" + | "connect" + | "sign-in" + | "off" + | "checking" + | "update" + | "add" + | "added"; + /** The store entry a store-plugin route installs. */ + readonly storeEntryId?: string | undefined; /** Why the agent does not have it yet. */ readonly reason?: string; /** The page that connects it, or manages it once connected. */ @@ -446,6 +496,26 @@ function accountServiceRoutesFromInventory( }, ]; } + const antigravityEntry = service.stores?.antigravity; + if (provider.driver === "antigravity" && antigravityEntry && providerAvailable(provider)) { + const plugin = provider.plugins?.find((item) => item.id === antigravityEntry); + return [ + { + ...base, + family: "antigravity", + storeEntryId: antigravityEntry, + page: `/settings/extensions/item/store/${provider.instanceId}/${antigravityEntry}`, + state: + provider.plugins === undefined + ? "checking" + : plugin === undefined + ? "add" + : plugin.enabled + ? "added" + : "off", + }, + ]; + } // Claude only for a service claude.ai has, with Anthropic's own page for it. if (provider.driver === "claudeAgent" && service.claude) { const claude = { ...base, family: "claude" as const, page: service.claude.page }; @@ -483,7 +553,7 @@ function accountServiceRoutesFromInventory( */ export function nextAccountServiceStep( routes: ReadonlyArray, -): { readonly page: string; readonly family: "chatgpt" | "claude" } | undefined { +): { readonly page: string; readonly family: AccountServiceRoute["family"] } | undefined { const pending = routes.filter((route) => route.state === "connect"); const next = pending.find((route) => route.family === "chatgpt") ?? pending[0]; return next ? { page: next.page, family: next.family } : undefined; From c1422ff6b8af863a32b72aa121a689d3f97d09e7 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:20:06 +0200 Subject: [PATCH 18/36] docs: note Antigravity on account service pages Co-Authored-By: Claude Opus 5.5 --- docs/user/extensions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/user/extensions.md b/docs/user/extensions.md index edd3baedbe..53865318ca 100644 --- a/docs/user/extensions.md +++ b/docs/user/extensions.md @@ -299,6 +299,11 @@ for your user account on the computer Scient runs on, so the Antigravity app there gets it too. Installed lists it with an On/Off switch and **Remove from Antigravity**. +Gmail, Google Drive, Google Calendar and other services with a matching +Antigravity plugin list Antigravity under **Your agents** on their page, with +**Add to Antigravity** right there. Once added, the row says the plugin signs in +the first time a chat uses it; Scient does not see that sign-in. + ## See what a conversation received When a conversation's agent has received connected services, a small plug From 752de920c511987af398fa4c51335140a44cb2d2 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:37:05 +0200 Subject: [PATCH 19/36] fix(server): list MCP servers from Antigravity plugins' mcp_config.json Installed Antigravity plugins (Canva and other partners) declare their MCP servers in mcp_config.json, which the bounded local reader did not read, so their detail pages left the servers out. Co-Authored-By: Claude Opus 5.5 --- .../scient/extensions/LocalPluginContents.test.ts | 12 ++++++++++++ .../src/scient/extensions/LocalPluginContents.ts | 2 ++ 2 files changed, 14 insertions(+) diff --git a/apps/server/src/scient/extensions/LocalPluginContents.test.ts b/apps/server/src/scient/extensions/LocalPluginContents.test.ts index aee3a6581a..0c765c3946 100644 --- a/apps/server/src/scient/extensions/LocalPluginContents.test.ts +++ b/apps/server/src/scient/extensions/LocalPluginContents.test.ts @@ -200,3 +200,15 @@ it("keeps requirements unknown when a manifest is invalid, escapes containment, await NodeFSP.rm(manifest); expect((await readLocalPluginContents(root)).requiredKeys).toEqual([]); }); + +it("lists the MCP servers an Antigravity plugin declares in mcp_config.json", async () => { + await using cleanup = new AsyncDisposableStack(); + const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "scient-agy-plugin-")); + cleanup.defer(() => NodeFSP.rm(root, { recursive: true, force: true })); + await NodeFSP.writeFile(NodePath.join(root, "plugin.json"), '{"name":"canva"}'); + await NodeFSP.writeFile( + NodePath.join(root, "mcp_config.json"), + '{"mcpServers":{"canva":{"serverUrl":"https://mcp.canva.com/mcp"}}}', + ); + expect((await readLocalPluginContents(root)).mcpServers).toEqual([{ name: "canva" }]); +}); diff --git a/apps/server/src/scient/extensions/LocalPluginContents.ts b/apps/server/src/scient/extensions/LocalPluginContents.ts index d59d7782f7..db212523b6 100644 --- a/apps/server/src/scient/extensions/LocalPluginContents.ts +++ b/apps/server/src/scient/extensions/LocalPluginContents.ts @@ -113,6 +113,8 @@ async function readLocalPluginMcpContents(root: string) { ".omp-plugin/plugin.json", ".codex-plugin/plugin.json", "plugin.json", + // Antigravity plugins declare their servers here, as `mcpServers`. + "mcp_config.json", ]) { const text = await readContainedPluginText(root, file).catch((error: unknown) => { if ( From 6e9a406b933c250e6fa38f4befeb9349cc0186a8 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:40:13 +0200 Subject: [PATCH 20/36] fix(server): re-check Antigravity's plugins right before installing agy has no no-replace install and overwrites a same-name plugin folder. Add now downloads, verifies and unpacks into staging first, then re-reads `agy plugin list --json` immediately before `agy plugin install` and stops, replacing nothing, if a same-name plugin appeared meanwhile (for example from the Antigravity app during the download). Co-Authored-By: Claude Opus 5.5 --- .../AntigravityProviderStore.test.ts | 42 +++++++++++++++++-- .../extensions/AntigravityProviderStore.ts | 13 ++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index 183fe4ebe1..66902a10e9 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -41,7 +41,10 @@ interface Fixture { readonly routes: Map; readonly fetched: string[]; readonly calls: string[][]; - readonly installed: Map; + readonly installed: Map< + string, + { enabled: boolean; version?: string; path: string; source?: string | null } + >; readonly stagedScriptModes: number[]; listOutput?: string; unavailable?: string; @@ -133,7 +136,7 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff name, enabled: plugin.enabled, ...(plugin.version ? { version: plugin.version } : {}), - source: "antigravity", + ...(plugin.source === null ? {} : { source: plugin.source ?? "antigravity" }), path: plugin.path, })), ); @@ -144,6 +147,10 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff if (yield* fs.exists(script)) fixture.stagedScriptModes.push(Number((yield* fs.stat(script)).mode)); const parsed = yield* decodeManifest(manifest); + // Like agy: the staged folder is copied, replacing any same-name folder. + yield* fs.remove(pluginPath(parsed.name), { recursive: true, force: true }); + yield* fs.makeDirectory(path.dirname(pluginPath(parsed.name)), { recursive: true }); + yield* fs.copy(target!, pluginPath(parsed.name)); fixture.installed.set(parsed.name, { enabled: true, version: parsed.version, @@ -151,7 +158,10 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff }); return ""; } - if (command === "uninstall") fixture.installed.delete(target!); + if (command === "uninstall") { + fixture.installed.delete(target!); + yield* fs.remove(pluginPath(target!), { recursive: true, force: true }); + } if (command === "enable" || command === "disable") { const plugin = fixture.installed.get(target!); if (plugin) plugin.enabled = command === "enable"; @@ -368,6 +378,32 @@ describe("AntigravityProviderStore", () => { ), ); + it.effect("does not replace a same-name plugin installed while the archive downloaded", () => + provide( + Effect.gen(function* () { + const { store, fixture, stateDir, pluginPath, fs, path } = yield* setup((fixture, zips) => + fixture.routes.set(GMAIL_ZIP, () => { + fixture.installed.set("gmail", { + enabled: true, + version: "1.0.0", + path: "/app/plugins/gmail", + }); + return new Response(zips.gmail); + }), + ); + const installedMeanwhile = fixture.installed; + const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); + expect(error.message).toMatch(/while Scient was preparing/); + expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); + expect(installedMeanwhile.get("gmail")?.version).toBe("1.0.0"); + expect(yield* fs.exists(pluginPath("gmail"))).toBe(false); + expect( + yield* fs.readDirectory(path.join(stateDir, "antigravity-plugins", "staging")), + ).toEqual([]); + }), + ), + ); + it.effect("treats a malformed installed list as unknown, never as empty", () => provide( Effect.gen(function* () { diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index 5394cff894..f5ef90bd5a 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -383,6 +383,19 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi ? { message: cause.message } : { message: "Scient could not prepare this plugin to add." }, ), + // agy has no no-replace install and overwrites a same-name folder, so the download + // window must not hide a plugin the Antigravity app installed meanwhile. + Effect.tap(() => + list().pipe( + Effect.flatMap((current) => + current.plugins.some((plugin) => plugin.name === item.plugin.name) + ? fail( + `Antigravity got a plugin named ${item.plugin.name} while Scient was preparing this one, so Scient did not replace it.`, + ) + : Effect.void, + ), + ), + ), Effect.flatMap((directory) => options.run(["plugin", "install", directory])), ), ).pipe( From 27d6603e59b5d2b80f12b1e2f323f88cd5363f18 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:41:39 +0200 Subject: [PATCH 21/36] fix(server): tie Antigravity install receipts to one exact installed copy A receipt matched on name, folder and (optionally) version, so after the plugin was removed and another copy installed in the Antigravity app, an old receipt could still make Marketplace Remove target the replacement. - Receipts now record agy's native source and an installation identity: the installed folder's device, inode and birth time plus its plugin.json digest. - A listed plugin is the catalog entry only when name, folder, version (a missing native version never matches), source and identity all match; otherwise it is a local plugin with its own id, which Marketplace Remove does not target. Co-Authored-By: Claude Opus 5.5 --- .../extensions/AntigravityPluginArchive.ts | 3 + .../AntigravityProviderStore.test.ts | 43 ++++++++++ .../extensions/AntigravityProviderStore.ts | 85 ++++++++++++++++--- 3 files changed, 118 insertions(+), 13 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityPluginArchive.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts index b4ebe98dce..b4ca2de621 100644 --- a/apps/server/src/scient/extensions/AntigravityPluginArchive.ts +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts @@ -16,6 +16,9 @@ import type * as Yauzl from "yauzl"; import { openZipArchive } from "../../zipArchive.ts"; import { getGstatic, isAntigravityGstaticUrl } from "./AntigravityPluginCatalog.ts"; +export const sha256Hex = (bytes: Uint8Array) => + NodeCrypto.createHash("sha256").update(bytes).digest("hex"); + export const ARCHIVE_LIMITS = { archiveBytes: 64 * 1024 * 1024, unpackedBytes: 256 * 1024 * 1024, diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index 66902a10e9..fa1310a3bf 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -404,6 +404,49 @@ describe("AntigravityProviderStore", () => { ), ); + it.effect("treats a replaced copy at the same name, version and folder as a local plugin", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture, pluginPath, fs, path } = yield* setup(); + const id = "gmail@antigravity-plugins-official"; + yield* store.install(id); + expect((yield* actions.listPlugins({})).plugins[0]!.id).toBe(id); + // Removed and installed again in the Antigravity app: same name, version and folder. + yield* fs.remove(pluginPath("gmail"), { recursive: true }); + yield* fs.makeDirectory(pluginPath("gmail"), { recursive: true }); + yield* fs.writeFileString( + path.join(pluginPath("gmail"), "plugin.json"), + encode({ name: "gmail", version: "0.0.7", description: "another copy" }), + ); + const [replaced] = (yield* actions.listPlugins({})).plugins; + expect(replaced).toMatchObject({ id: "antigravity:gmail" }); + expect((yield* store.entry(id)).installed).toBe(false); + expect((yield* actions.uninstall({ pluginId: id }).pipe(Effect.flip)).message).toMatch( + /no longer installed/, + ); + expect(fixture.calls.some((call) => call[1] === "uninstall")).toBe(false); + }), + ), + ); + + it.effect("needs agy's version and source to match the receipt", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture } = yield* setup(); + const id = "gmail@antigravity-plugins-official"; + yield* store.install(id); + const gmail = fixture.installed.get("gmail")!; + const { version: _version, ...unversioned } = gmail; + fixture.installed.set("gmail", unversioned); + expect((yield* actions.listPlugins({})).plugins[0]!.id).toBe("antigravity:gmail"); + fixture.installed.set("gmail", { ...gmail, source: "gemini" }); + expect((yield* actions.listPlugins({})).plugins[0]!.id).toBe("antigravity:gmail"); + fixture.installed.set("gmail", gmail); + expect((yield* actions.listPlugins({})).plugins[0]!.id).toBe(id); + }), + ), + ); + it.effect("treats a malformed installed list as unknown, never as empty", () => provide( Effect.gen(function* () { diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index f5ef90bd5a..e5a6b85dc6 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -14,6 +14,7 @@ import type { import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import type * as Scope from "effect/Scope"; @@ -39,7 +40,9 @@ import { type AntigravityMarketplace, } from "./AntigravityPluginCatalog.ts"; import { + ARCHIVE_LIMITS, isAntigravityPluginArchiveError, + sha256Hex, stageAntigravityPlugin, } from "./AntigravityPluginArchive.ts"; import { resolveBrandIcon } from "./BrandIcons.ts"; @@ -72,6 +75,10 @@ const Receipt = Schema.Struct({ sha256: Schema.String, path: Schema.String, displayName: Schema.optional(Schema.String), + /** agy's own `source` for the installed copy, when it reported one. */ + source: Schema.optional(Schema.String), + /** The installed folder's identity and its plugin.json digest at Add (`installationIdentity`). */ + installation: Schema.optional(Schema.String), }); type Receipt = typeof Receipt.Type; const ReceiptFile = Schema.fromJsonString( @@ -86,6 +93,7 @@ const encodeReceipts = Schema.encodeEffect(ReceiptFile); /** One plugin `agy plugin list --json` reported, with its folder. */ export type AntigravityInstalledPlugin = ServerProviderPlugin & { readonly path: string; + readonly nativeSource?: string | undefined; readonly skills: ReadonlyArray; readonly mcpServers: ReadonlyArray; }; @@ -97,20 +105,56 @@ export const ANTIGRAVITY_NOT_CLI = const INVENTORY_UNAVAILABLE = "Scient could not read Antigravity's installed plugins, so Add and Remove are paused. Refresh to try again."; -/** Which listed plugin a receipt vouches for: same name, same folder and, when known, same version. */ -function receiptFor( +/** + * One installed copy: its folder's device, inode and birth time, and its plugin.json digest. A + * copy replaced in Antigravity, even at the same name, version and folder, gets another identity. + */ +const installationIdentity = Effect.fn("AntigravityProviderStore.installationIdentity")(function* ( + folder: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const info = yield* fs.stat(folder); + const manifestFile = path.join(folder, "plugin.json"); + const manifestInfo = yield* fs.stat(manifestFile); + if ( + info.type !== "Directory" || + manifestInfo.type !== "File" || + Number(manifestInfo.size) > ARCHIVE_LIMITS.manifestBytes + ) + return yield* fail("Not a plugin folder."); + const manifest = yield* fs.readFile(manifestFile); + const born = Option.match(info.birthtime, { onNone: () => "", onSome: (at) => at.getTime() }); + const inode = Option.getOrElse(info.ino, () => 0n); + return `${info.dev}:${inode}:${born}:${sha256Hex(manifest)}`; +}); + +/** + * The receipt for this exact listed copy: same name, folder, version and native source, and the + * identity recorded at Add. Anything else is a local plugin of its own. + */ +const receiptFor = Effect.fn("AntigravityProviderStore.receiptFor")(function* ( receipts: ReadonlyArray, - plugin: { readonly name: string; readonly path: string; readonly version?: string | undefined }, -): Receipt | undefined { - return receipts.find( + plugin: { + readonly name: string; + readonly path: string; + readonly version?: string | undefined; + readonly source?: string | undefined; + }, +) { + const candidate = receipts.find( (receipt) => receipt.name === plugin.name && receipt.path === plugin.path && - (receipt.version === undefined || - plugin.version === undefined || - receipt.version === plugin.version), + receipt.version !== undefined && + receipt.version === plugin.version && + receipt.source === plugin.source && + receipt.installation !== undefined, ); -} + if (!candidate) return undefined; + const identity = yield* installationIdentity(plugin.path).pipe(Effect.option); + return Option.getOrUndefined(identity) === candidate.installation ? candidate : undefined; +}); /** `agy plugin list --json` as provider plugins; any malformed listing fails as a whole. */ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList")(function* ( @@ -126,7 +170,13 @@ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList return yield* fail("Antigravity listed its plugins in an unexpected form."); names.add(item.name); const version = item.version?.trim() || undefined; - const receipt = receiptFor(receipts, { name: item.name, path: item.path, version }); + const source = item.source?.trim() || undefined; + const receipt = yield* receiptFor(receipts, { + name: item.name, + path: item.path, + version, + source, + }); plugins.push({ id: receipt ? entryId(item.name, receipt.marketplace) : `antigravity:${item.name}`, name: item.name, @@ -140,6 +190,7 @@ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList sourceLabel: receipt ? "Antigravity Marketplace" : "Antigravity's plugins", scope: "user", path: item.path, + ...(source ? { nativeSource: source } : {}), skills: item.skills ?? [], mcpServers: item.mcpServers ?? [], }); @@ -226,6 +277,7 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi return { plugins, sequence }; }, Effect.provideService(Path.Path, path), + Effect.provideService(FileSystem.FileSystem, fs), Effect.mapError(() => ({ message: "Could not read Antigravity's installed plugins." })), ); const list = Effect.fn("AntigravityProviderStore.list")(function* () { @@ -406,17 +458,24 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const after = yield* list(); const listed = after.plugins.find((plugin) => plugin.name === item.plugin.name); if (!listed) return yield* fail("Antigravity did not list the plugin after adding it."); + const installation = yield* installationIdentity(listed.path).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.mapError(() => ({ + message: "The plugin was added, but Scient could not read its installed folder.", + })), + ); yield* writeReceipts((receipts) => [ ...receipts.filter((receipt) => receipt.name !== listed.name), { name: listed.name, marketplace: item.plugin.marketplace, - ...((listed.version ?? item.plugin.version) - ? { version: listed.version ?? item.plugin.version } - : {}), + ...(listed.version ? { version: listed.version } : {}), + ...(listed.nativeSource ? { source: listed.nativeSource } : {}), sha256: archive.sha256, path: listed.path, displayName: item.plugin.displayName, + installation, }, ]).pipe( Effect.mapError(() => ({ From 444d24865656a157ab34787efacdf0df9793d370 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:44:43 +0200 Subject: [PATCH 22/36] fix(server): refresh every Antigravity instance sharing a plugin folder agy installs plugins per OS user, so Add, Remove or enable/disable through one Antigravity instance changes what every instance with the same home sees, but only the acting instance republished its list. - Each instance registers under its resolved plugin folder (/.gemini/config/plugins); after any change every live instance there publishes its verified list, without a workspace key. - Remove and enable/disable refuse a workspace-scoped request: these plugins belong to the user account, not a workspace. Co-Authored-By: Claude Opus 5.5 --- .../AntigravityProviderStore.test.ts | 69 +++++++++++++++- .../extensions/AntigravityProviderStore.ts | 81 ++++++++++++++----- 2 files changed, 130 insertions(+), 20 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index fa1310a3bf..f1983acd0c 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -5,8 +5,10 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import type * as Scope from "effect/Scope"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -297,9 +299,9 @@ describe("AntigravityProviderStore", () => { pluginId: "gmail@antigravity-plugins-official", enabled: false, }); - expect(fixture.calls.at(-1)).toEqual(["plugin", "disable", "gmail"]); + expect(fixture.calls).toContainEqual(["plugin", "disable", "gmail"]); yield* actions.uninstall({ pluginId: "gmail@antigravity-plugins-official" }); - expect(fixture.calls.at(-1)).toEqual(["plugin", "uninstall", "gmail"]); + expect(fixture.calls).toContainEqual(["plugin", "uninstall", "gmail"]); expect((yield* store.entry("gmail@antigravity-plugins-official")).installed).toBe(false); }), ), @@ -511,6 +513,69 @@ describe("AntigravityProviderStore", () => { ); }); +it.live("refreshes every instance that shares the plugin folder after a change", () => + provide( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const shared = path.join(stateDir, "home", ".gemini", "config", "plugins"); + const other = path.join(stateDir, "other", ".gemini", "config", "plugins"); + const enabled = new Map([["canva", true]]); + const run = (args: ReadonlyArray) => + Effect.sync(() => { + const [, command, name] = args; + if (command === "enable" || command === "disable") + enabled.set(name!, command === "enable"); + return command === "list" + ? encode( + [...enabled].map(([plugin, on]) => ({ + name: plugin, + enabled: on, + path: path.join(shared, plugin), + })), + ) + : ""; + }); + const http = HttpClient.make((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 404 }))), + ); + const instance = (pluginHome: string) => + makeAntigravityPluginActions({ + stateDir, + run, + unavailable: Effect.undefined, + pluginHome, + }).pipe(Effect.provideService(HttpClient.HttpClient, http)); + const [acting, peer, elsewhere] = yield* Effect.all([ + instance(shared), + instance(shared), + instance(other), + ]); + const latest = (reports: typeof peer.reports) => + Stream.runHead(reports).pipe(Effect.timeoutOption("1 second"), Effect.map(Option.flatten)); + const refused = yield* acting.actions.setEnabled!({ + pluginId: "antigravity:canva", + enabled: false, + cwd: "/work", + }).pipe(Effect.flip); + expect(refused.message).toMatch(/not a workspace/); + expect(enabled.get("canva")).toBe(true); + + yield* acting.actions.setEnabled!({ pluginId: "antigravity:canva", enabled: false }); + for (const reports of [acting.reports, peer.reports]) { + const report = yield* latest(reports); + expect(report._tag).toBe("Some"); + if (report._tag === "Some") { + expect(report.value.cwd).toBeUndefined(); + expect(report.value.plugins?.map((plugin) => plugin.enabled)).toEqual([false]); + } + } + expect((yield* latest(elsewhere.reports))._tag).toBe("None"); + }), + ), +); + it("files catalog plugins under reviewed Discover categories, then the catalog's own labels", () => { expect(antigravityCategories("scientific-literature", [], [])).toEqual(["papers"]); expect(antigravityCategories("gmail", ["Productivity"], [])).toEqual(["communication"]); diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index e5a6b85dc6..332b9bad1b 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -216,6 +216,15 @@ function declaredContents(plugin: AntigravityCatalogPlugin): ExtensionPluginCont }; } +/** + * Each live instance's inventory refresh, by the plugin folder it shares: agy installs per OS + * user, so one instance's change is every same-home instance's change. + */ +const instancesByPluginHome = new Map>>(); + +const WORKSPACE_REFUSED = + "Antigravity plugins belong to your user account, not a workspace. Change them from the agent's own list."; + export interface AntigravityPluginStoreOptions { /** Scient's state folder: receipts and the private staging folder live under it. */ readonly stateDir: string; @@ -223,6 +232,8 @@ export interface AntigravityPluginStoreOptions { readonly run: (args: ReadonlyArray) => Effect.Effect; /** Why this instance cannot manage plugins (it is not the agy CLI), or `undefined`. */ readonly unavailable: Effect.Effect; + /** The resolved plugin folder agy writes, shared by every instance with the same home. */ + readonly pluginHome?: string | undefined; readonly marketplaces?: ReadonlyArray; } @@ -496,12 +507,36 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const listing = yield* list(); yield* PubSub.publish(reports, { plugins: listing.plugins, sequence: listing.sequence }); }); + const refreshThis = Effect.suspend(() => publish()).pipe(Effect.ignore); + const home = options.pluginHome; + if (home !== undefined) { + const peers = instancesByPluginHome.get(home) ?? new Set(); + peers.add(refreshThis); + instancesByPluginHome.set(home, peers); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + peers.delete(refreshThis); + if (peers.size === 0 && instancesByPluginHome.get(home) === peers) + instancesByPluginHome.delete(home); + }), + ); + } + /** After a change, every instance sharing this plugin folder publishes its verified list. */ + const announce = Effect.suspend(() => + Effect.forEach( + home === undefined ? [refreshThis] : [...(instancesByPluginHome.get(home) ?? [refreshThis])], + (refresh) => refresh, + { concurrency: "unbounded", discard: true }, + ), + ); + const changeAll = (change: Effect.Effect) => + writes.withPermits(1)(change.pipe(Effect.ensuring(announce))); const actions: ProviderPluginActions = { store: { search, entry: (id) => find(id).pipe(Effect.flatMap(({ entry, plugin }) => withIcon(entry, plugin))), - install: (id) => writes.withPermits(1)(install(id)), + install: (id) => changeAll(install(id)), contents: (id) => find(id).pipe( Effect.flatMap(({ entry, plugin, installed }) => { @@ -540,24 +575,28 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi ), readMcpServer: () => Effect.undefined, setEnabled: (input) => - writes.withPermits(1)( - nativePlugin(input.pluginId).pipe( - Effect.flatMap((plugin) => - options.run(["plugin", input.enabled ? "enable" : "disable", plugin.name]), + input.cwd !== undefined + ? fail(WORKSPACE_REFUSED) + : changeAll( + nativePlugin(input.pluginId).pipe( + Effect.flatMap((plugin) => + options.run(["plugin", input.enabled ? "enable" : "disable", plugin.name]), + ), + Effect.asVoid, + ), ), - Effect.asVoid, - ), - ), uninstall: (input) => - writes.withPermits(1)( - Effect.gen(function* () { - const plugin = yield* nativePlugin(input.pluginId); - yield* options.run(["plugin", "uninstall", plugin.name]); - yield* writeReceipts((receipts) => - receipts.filter((receipt) => receipt.name !== plugin.name), - ).pipe(Effect.ignore); - }), - ), + input.cwd !== undefined + ? fail(WORKSPACE_REFUSED) + : changeAll( + Effect.gen(function* () { + const plugin = yield* nativePlugin(input.pluginId); + yield* options.run(["plugin", "uninstall", plugin.name]); + yield* writeReceipts((receipts) => + receipts.filter((receipt) => receipt.name !== plugin.name), + ).pipe(Effect.ignore); + }), + ), startMcpSignIn: () => fail("Sign in to this plugin's service from an Antigravity chat when it asks."), isRetired: Deferred.isDone(retired), @@ -642,6 +681,12 @@ export const makeAntigravityInstancePlugins = Effect.fn("makeAntigravityInstance ), Effect.orElseSucceed(() => "Install Antigravity to add its plugins."), ); - return yield* makeAntigravityPluginActions({ stateDir: input.stateDir, run, unavailable }); + const home = input.environment.HOME ?? input.environment.USERPROFILE; + return yield* makeAntigravityPluginActions({ + stateDir: input.stateDir, + run, + unavailable, + pluginHome: home ? path.resolve(home, ".gemini", "config", "plugins") : undefined, + }); }, ); From b59d75ff150c8563e50d179a9e4b85db91458755 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:44:31 +0200 Subject: [PATCH 23/36] fix(antigravity): scrub every sign-in URL and trust only the plugin's own CLI Redaction no longer depends on a recognized attempt. Any URL whose redirect_uri is loopback is scrubbed from tool snapshots and from every streamed channel, including a tool's first content chunk. A stream holds a possible partial URL, secret or card, bounded, until that stream ends: a tool's output ends with the call, a reply when a tool call or the prompt ends. Interleaved updates no longer release half of a page, and a challenge that arrives only as streamed chunks is found when its call ends. A challenge earns a notice only from a plain shell run of a CLI that the installed plugin's auth.json declares (~/.gemini/config/plugins), whose plugin.json name matches the card, and whose page matches that manifest's authorizeUrl and clientId. Anything else stays redacted with no notice. Only the fields Scient checks are decoded from auth.json. Co-Authored-By: Claude Opus 5.5 --- .../AntigravityAdapterV2.scient.test.ts | 351 +++++++----- .../Adapters/AntigravityAdapterV2.ts | 43 +- .../antigravity/pluginAuthManifest.test.ts | 69 +++ .../scient/antigravity/pluginAuthManifest.ts | 88 +++ .../scient/antigravity/pluginSignIn.test.ts | 228 +++++--- .../src/scient/antigravity/pluginSignIn.ts | 503 +++++++++++------- 6 files changed, 853 insertions(+), 429 deletions(-) create mode 100644 apps/server/src/scient/antigravity/pluginAuthManifest.test.ts create mode 100644 apps/server/src/scient/antigravity/pluginAuthManifest.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts index 98381e1bac..985c0fe4ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts @@ -16,6 +16,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; 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 Path from "effect/Path"; import * as Stream from "effect/Stream"; @@ -57,157 +58,195 @@ const CHALLENGE = [ `Only if the card can't be shown, give them this sign-in link instead: ${SIGN_IN_URL}\r`, ].join("\n"); +/** An installed Gmail plugin whose manifest names `clientId` as its OAuth client. */ +const installGmail = Effect.fn("installGmail")(function* (clientId: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const plugins = yield* fileSystem.makeTempDirectoryScoped(); + const folder = path.join(plugins, "gmail"); + yield* fileSystem.makeDirectory(folder); + yield* fileSystem.writeFileString( + path.join(folder, "plugin.json"), + JSON.stringify({ name: "gmail", displayName: "Gmail" }), + ); + yield* fileSystem.writeFileString( + path.join(folder, "auth.json"), + JSON.stringify({ + providers: { + google: { + clis: ["gmail"], + oauth2: { authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth", clientId }, + }, + }, + }), + ); + return plugins; +}); + +/** One turn whose tool ran `command` and printed the Gmail challenge, then repeated it. */ +const runChallengeTurn = Effect.fn("runChallengeTurn")(function* (turn: { + readonly command: string; + readonly manifestClientId: string; +}) { + const pluginsDirectory = yield* installGmail(turn.manifestClientId); + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("antigravity-plugin-sign-in-test"); + const threadId = ThreadId.make("thread-antigravity-plugin-sign-in"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const rawInput = { CommandLine: turn.command }; + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "call-gmail", + title: turn.command, + kind: "execute", + status: "in_progress", + rawInput, + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call-gmail", + kind: "execute", + status: "completed", + rawInput, + rawOutput: { output: CHALLENGE, exit_code: 1 }, + content: [{ type: "content", content: { type: "text", text: CHALLENGE } }], + }); + const reply = `Sign in with ${SIGN_IN_URL}\n\n${CARD}`; + for (const text of [reply.slice(0, 40), reply.slice(40, 120), reply.slice(120)]) { + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text }, + }); + } + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + pluginsDirectory, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-plugin-sign-in"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-plugin-sign-in"), + title: "Antigravity plugin sign-in", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + 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, + }, + threadId, + runId: RunId.make("run-antigravity-plugin-sign-in"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-plugin-sign-in"), + rootNodeId: NodeId.make("node-antigravity-plugin-sign-in"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-plugin-sign-in"), + text: "list my three newest emails", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const notices = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice" + ? [event.turnItem] + : [], + ); + return { events, notices, session, providerThread, threadId }; +}); + describe("AntigravityAdapterV2 plugin sign-in", () => { it.effect("offers a plugin sign-in and keeps its page off the transcript", () => Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const crypto = yield* SecureRandom.SecureRandom; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdate: Parameters[0] | undefined; - const instanceId = ProviderInstanceId.make("antigravity-plugin-sign-in-test"); - const threadId = ThreadId.make("thread-antigravity-plugin-sign-in"); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe( - Effect.provideService(SecureRandom.SecureRandom, crypto), - Effect.map((runtime): RuntimeService => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => - Effect.gen(function* () { - const send = (update: EffectAcpSchema.SessionUpdate) => - sessionUpdate === undefined - ? Effect.die("the adapter must handle session updates") - : sessionUpdate( - normalizeAntigravitySessionUpdate({ - sessionId: "mock-session-1", - update, - }), - ); - const rawInput = { CommandLine: "gmail readonly search --max 3" }; - yield* send({ - sessionUpdate: "tool_call", - toolCallId: "call-gmail", - title: "gmail readonly search --max 3", - kind: "execute", - status: "in_progress", - rawInput, - }); - yield* send({ - sessionUpdate: "tool_call_update", - toolCallId: "call-gmail", - kind: "execute", - status: "completed", - rawInput, - rawOutput: { output: CHALLENGE, exit_code: 1 }, - content: [{ type: "content", content: { type: "text", text: CHALLENGE } }], - }); - const reply = `Sign in with ${SIGN_IN_URL}\n\n${CARD}`; - for (const text of [reply.slice(0, 40), reply.slice(40, 120), reply.slice(120)]) { - yield* send({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text }, - }); - } - return { stopReason: "end_turn" as const }; - }), - })), - ), - withProcess: (_stop, task) => task, - defaultModel: Effect.undefined, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), + const { events, notices, session, providerThread, threadId } = yield* runChallengeTurn({ + command: "gmail readonly search --max 3", + manifestClientId: "synthetic-client.example", }); - const modelSelection = { instanceId, model: "gemini-test-low" } as const; - const session = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-antigravity-plugin-sign-in"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* session.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* session.startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-plugin-sign-in"), - title: "Antigravity plugin sign-in", - providerInstanceId: instanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: process.cwd(), - 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, - }, - threadId, - runId: RunId.make("run-antigravity-plugin-sign-in"), - runOrdinal: 1, - providerTurnOrdinal: 1, - attemptId: RunAttemptId.make("attempt-antigravity-plugin-sign-in"), - rootNodeId: NodeId.make("node-antigravity-plugin-sign-in"), - providerThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-antigravity-plugin-sign-in"), - text: "list my three newest emails", - attachments: [], - }, - modelSelection, - runtimePolicy, - }); - const events = Array.from( - yield* session.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, - ), - ); - const serialized = JSON.stringify(events); assert.notInclude(serialized, STATE); assert.notInclude(serialized, "synthetic-challenge"); - const notices = events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "system_notice" - ? [event.turnItem] - : [], - ); assert.strictEqual(notices.length, 1); const pluginSignIn = notices[0]?.pluginSignIn; assert.deepInclude(pluginSignIn, { plugin: "gmail", displayName: "Gmail" }); @@ -236,6 +275,28 @@ describe("AntigravityAdapterV2 plugin sign-in", () => { attemptId: pluginSignIn!.attemptId, }).pipe(Effect.exit); assert.isTrue(Exit.isFailure(otherThread)); - }).pipe(Effect.provide(layerSession)), + }).pipe(Effect.scoped, Effect.provide(layerSession)), + ); + + // regression: any tool's output, or another OAuth client, used to earn a trusted notice. + it.effect.each([ + { + label: "a tool that is not the plugin's CLI", + command: "cat notes.txt", + client: "synthetic-client.example", + }, + { + label: "a page for another OAuth client", + command: "gmail readonly search", + client: "other-client.example", + }, + ])( + "offers no sign-in for $label, and still keeps the page off the transcript", + ({ command, client }) => + Effect.gen(function* () { + const { events, notices } = yield* runChallengeTurn({ command, manifestClientId: client }); + assert.strictEqual(notices.length, 0); + assert.notInclude(JSON.stringify(events), STATE); + }).pipe(Effect.scoped, Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 1370747950..10b680649a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -60,6 +60,7 @@ import { scientAntigravityBridge } from "./ScientAcpApplicationBridge.ts"; // SCIENT-FORK:END Scient ACP application bridge // SCIENT-FORK:START — plugin sign-in challenges from tool results. import { makeAntigravityPluginSignIns } from "../../scient/antigravity/pluginSignIn.ts"; +import { verifyPluginSignIn } from "../../scient/antigravity/pluginAuthManifest.ts"; // SCIENT-FORK:END import { AcpProviderCapabilitiesV2, @@ -116,6 +117,10 @@ export interface AntigravityAdapterV2Options { readonly continuationRequests?: Parameters[0]["continuationRequests"]; /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */ readonly profileDirectory?: string; + // SCIENT-FORK:START — where `agy` installs plugins; their manifests vouch for sign-ins. + /** Defaults to `~/.gemini/config/plugins`; without plugins no sign-in notice is offered. */ + readonly pluginsDirectory?: string; + // SCIENT-FORK:END } /** @@ -158,7 +163,7 @@ interface AntigravityFlavorServices { export function makeAntigravityAcpAdapterFlavor( options: AntigravityAdapterV2Options & AntigravityFlavorServices, ): AcpAdapterV2Flavor { - const { profileDirectory } = options; + const { profileDirectory, pluginsDirectory } = options; // SCIENT-FORK:START — daemon commands tracked as background work. A later update can carry only // the tool ID and status, so a tracked daemon is known by its ID until it ends. const daemonToolCallIds = new Set(); @@ -263,18 +268,27 @@ export function makeAntigravityAcpAdapterFlavor( updates.withPermit( // SCIENT-FORK:START — challenges are kept and scrubbed before anything projects them. Effect.gen(function* () { - const repaired = reads.repair(notification); - const toolUpdate = - repaired.update.sessionUpdate === "tool_call" || - repaired.update.sessionUpdate === "tool_call_update"; - const attemptId = toolUpdate ? yield* options.random.uuidV4() : ""; - const projected = pluginSignIns.observe({ + const { notifications, candidate } = pluginSignIns.observe({ generation, - notification: repaired, - now: yield* Clock.currentTimeMillis, - newId: () => attemptId, + notification: reads.repair(notification), }); - yield* Effect.forEach(projected, handler, { discard: true }); + // Only the installed plugin's own CLI and OAuth client earn a sign-in notice. + const verified = + candidate === undefined || pluginsDirectory === undefined + ? undefined + : yield* verifyPluginSignIn({ pluginsDirectory, candidate }).pipe( + Effect.provideService(FileSystem.FileSystem, options.fileSystem), + Effect.provideService(Path.Path, options.path), + ); + if (candidate !== undefined && verified !== undefined) { + pluginSignIns.admit(candidate, { + attemptId: yield* options.random.uuidV4(), + displayName: verified.displayName, + programs: verified.programs, + now: yield* Clock.currentTimeMillis, + }); + } + yield* Effect.forEach(notifications, handler, { discard: true }); }), // SCIENT-FORK:END ), @@ -470,9 +484,14 @@ export const makeAntigravityAdapterV2 = Effect.fn("makeAntigravityAdapterV2")(fu path: yield* Path.Path, host: yield* ProviderHost.ProviderHost, }; + // SCIENT-FORK:START — the agy CLI loads plugins from the OS user's home, not GEMINI_HOME. + const pluginsDirectory = + options.pluginsDirectory ?? + services.path.join(yield* HostProcess.HomeDirectory, ".gemini", "config", "plugins"); + // SCIENT-FORK:END return yield* makeAcpAdapterV2({ instanceId: options.instanceId, - flavor: makeAntigravityAcpAdapterFlavor({ ...options, ...services }), + flavor: makeAntigravityAcpAdapterFlavor({ ...options, ...services, pluginsDirectory }), selfInvocation: options.selfInvocation, ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }), ...(options.continuationRequests === undefined diff --git a/apps/server/src/scient/antigravity/pluginAuthManifest.test.ts b/apps/server/src/scient/antigravity/pluginAuthManifest.test.ts new file mode 100644 index 0000000000..d72bb9a82d --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginAuthManifest.test.ts @@ -0,0 +1,69 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { verifyPluginSignIn } from "./pluginAuthManifest.ts"; +import type { PluginSignInCandidate } from "./pluginSignIn.ts"; + +const ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"; +const CLIENT = "synthetic-client.example"; + +const candidate = (overrides: { + readonly plugin?: string; + readonly program?: string; + readonly clientId?: string; + readonly endpoint?: string; +}): PluginSignInCandidate => ({ + sessionId: "session-1", + toolCallId: "call-1", + generation: 1, + program: overrides.program ?? "gmail", + challenge: { + plugin: overrides.plugin ?? "gmail", + authorizationUrl: `${ENDPOINT}?client_id=${CLIENT}`, + endpoint: overrides.endpoint ?? ENDPOINT, + clientId: overrides.clientId ?? CLIENT, + secrets: [], + }, +}); + +const installGmail = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const plugins = yield* fileSystem.makeTempDirectoryScoped(); + const folder = path.join(plugins, "gmail"); + yield* fileSystem.makeDirectory(folder); + yield* fileSystem.writeFileString( + path.join(folder, "plugin.json"), + JSON.stringify({ name: "gmail", displayName: "Gmail" }), + ); + yield* fileSystem.writeFileString( + path.join(folder, "auth.json"), + JSON.stringify({ + providers: { + google: { + type: "oauth2", + clis: ["gmail"], + oauth2: { authorizeUrl: ENDPOINT, clientId: CLIENT, clientSecret: "synthetic" }, + }, + }, + }), + ); + return plugins; +}); + +it.effect("admits only what the installed plugin's manifest declares", () => + Effect.gen(function* () { + const pluginsDirectory = yield* installGmail; + const verify = (overrides: Parameters[0]) => + verifyPluginSignIn({ pluginsDirectory, candidate: candidate(overrides) }); + assert.deepEqual(yield* verify({}), { displayName: "Gmail", programs: ["gmail"] }); + // regression: a page for another OAuth client used to earn a trusted notice. + assert.isUndefined(yield* verify({ clientId: "attacker-client.example" })); + assert.isUndefined(yield* verify({ endpoint: "https://evil.example/o/oauth2/v2/auth" })); + assert.isUndefined(yield* verify({ program: "cat" })); + assert.isUndefined(yield* verify({ plugin: "gdrive" })); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/scient/antigravity/pluginAuthManifest.ts b/apps/server/src/scient/antigravity/pluginAuthManifest.ts new file mode 100644 index 0000000000..f014f0771b --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginAuthManifest.ts @@ -0,0 +1,88 @@ +/** + * Whether an installed Antigravity plugin vouches for a sign-in challenge: its folder names the + * card's plugin, and its `auth.json` declares the CLI that printed the challenge together with + * the page's endpoint and OAuth client. Only those fields are decoded; secrets stay unread. + */ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import type { PluginSignInCandidate } from "./pluginSignIn.ts"; + +const MAX_MANIFEST_BYTES = 64 * 1024; + +const PluginManifest = Schema.fromJsonString( + Schema.Struct({ name: Schema.String, displayName: Schema.optional(Schema.String) }), +); +const AuthManifest = Schema.fromJsonString( + Schema.Struct({ + providers: Schema.Record( + Schema.String, + Schema.Struct({ + clis: Schema.optional(Schema.Array(Schema.String)), + oauth2: Schema.optional( + Schema.Struct({ authorizeUrl: Schema.String, clientId: Schema.String }), + ), + }), + ), + }), +); +const decodePluginManifest = Schema.decodeUnknownOption(PluginManifest); +const decodeAuthManifest = Schema.decodeUnknownOption(AuthManifest); + +const endpointOf = (value: string) => { + try { + const url = new URL(value); + return `${url.origin}${url.pathname}`; + } catch { + return undefined; + } +}; + +const readBounded = Effect.fnUntraced(function* (file: string) { + const fileSystem = yield* FileSystem.FileSystem; + const info = yield* fileSystem.stat(file); + if (info.type !== "File" || Number(info.size) > MAX_MANIFEST_BYTES) return undefined; + return yield* fileSystem.readFileString(file); +}); + +export interface VerifiedPluginSignIn { + readonly displayName: string | undefined; + /** Every CLI the plugin's sign-in covers; a later successful run of one confirms it. */ + readonly programs: ReadonlyArray; +} + +/** Undefined unless the installed plugin declares exactly what the candidate printed. */ +export const verifyPluginSignIn = Effect.fn("AntigravityPluginSignIn.verify")( + function* (input: { + readonly pluginsDirectory: string; + readonly candidate: PluginSignInCandidate; + }) { + const path = yield* Path.Path; + const { challenge, program } = input.candidate; + const folder = path.join(input.pluginsDirectory, challenge.plugin); + const plugin = Option.getOrUndefined( + decodePluginManifest(yield* readBounded(path.join(folder, "plugin.json"))), + ); + if (plugin?.name !== challenge.plugin) return undefined; + const auth = Option.getOrUndefined( + decodeAuthManifest(yield* readBounded(path.join(folder, "auth.json"))), + ); + if (auth === undefined) return undefined; + for (const provider of Object.values(auth.providers)) { + const clis = provider.clis ?? []; + if ( + clis.includes(program) && + provider.oauth2 !== undefined && + endpointOf(provider.oauth2.authorizeUrl) === challenge.endpoint && + provider.oauth2.clientId === challenge.clientId + ) { + return { displayName: plugin.displayName, programs: clis } satisfies VerifiedPluginSignIn; + } + } + return undefined; + }, + Effect.orElseSucceed(() => undefined), +); diff --git a/apps/server/src/scient/antigravity/pluginSignIn.test.ts b/apps/server/src/scient/antigravity/pluginSignIn.test.ts index f373c3da38..7272078eef 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.test.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.test.ts @@ -8,6 +8,8 @@ import { LINK_REMOVED, makeAntigravityPluginSignIns, makeStreamRedactor, + plainCommandProgram, + type PluginSignInCandidate, } from "./pluginSignIn.ts"; const STATE = "synthetic-state-0123456789"; @@ -43,11 +45,15 @@ const challengeText = (url = URL_OK, cardText = card()) => ].join("\n"); describe("extractPluginSignInChallenge", () => { - it("reads the card and the loopback sign-in page", () => { + it("reads the card, the loopback sign-in page and its OAuth client", () => { const challenge = extractPluginSignInChallenge(challengeText()); - expect(challenge?.plugin).toBe("gmail"); - expect(challenge?.authorizationUrl).toBe(URL_OK); - expect(challenge?.secrets).toEqual([URL_OK, STATE, CHALLENGE_CODE]); + expect(challenge).toMatchObject({ + plugin: "gmail", + authorizationUrl: URL_OK, + endpoint: "https://accounts.google.com/o/oauth2/v2/auth", + clientId: "synthetic-client.example", + secrets: [URL_OK, STATE, CHALLENGE_CODE], + }); }); it.each([ @@ -61,7 +67,6 @@ describe("extractPluginSignInChallenge", () => { ["an oversized slug", challengeText(URL_OK, card("g".repeat(65)))], ["two URLs", `${challengeText()} see https://example.com/help`], ["a non-https page", challengeText(URL_OK.replace("https://", "http://"))], - ["an unknown endpoint", challengeText(signInUrl({}, "https://evil.example/o/oauth2/v2/auth"))], [ "a remote redirect", challengeText(signInUrl({ redirect_uri: "http://10.0.0.5:57512/callback" })), @@ -83,6 +88,7 @@ describe("extractPluginSignInChallenge", () => { challengeText(signInUrl({ redirect_uri: "http://127.0.0.1:57512/other" })), ], ["no state", challengeText(URL_OK.replace(`&state=${STATE}`, ""))], + ["no client", challengeText(URL_OK.replace("client_id=synthetic-client.example&", ""))], ["two states", challengeText(`${URL_OK}&state=second`)], [ "two redirects", @@ -94,14 +100,6 @@ describe("extractPluginSignInChallenge", () => { ])("refuses %s", (_label, text) => { expect(extractPluginSignInChallenge(text)).toBeUndefined(); }); - - it("accepts [::1] and localhost loopback redirects", () => { - for (const redirect_uri of ["http://[::1]:4000/callback", "http://localhost:4000/callback"]) { - expect( - extractPluginSignInChallenge(challengeText(signInUrl({ redirect_uri }))), - ).toBeDefined(); - } - }); }); describe("extractToolCallChallenge", () => { @@ -109,10 +107,11 @@ describe("extractToolCallChallenge", () => { it("reads a tool result whose fields repeat the same text", () => { expect( extractToolCallChallenge({ - title: "gmail readonly search", - rawInput: { CommandLine: "gmail readonly search" }, - rawOutput: { output, exit_code: 1 }, - content: [{ type: "content", content: { type: "text", text: output } }], + inputs: ["gmail readonly search", { CommandLine: "gmail readonly search" }], + outputs: [ + { output, exit_code: 1 }, + [{ type: "content", content: { type: "text", text: output } }], + ], })?.plugin, ).toBe("gmail"); }); @@ -120,9 +119,8 @@ describe("extractToolCallChallenge", () => { it("refuses a challenge the call's own input wrote", () => { expect( extractToolCallChallenge({ - title: "echo", - rawInput: { CommandLine: `echo '${output}'` }, - rawOutput: { output }, + inputs: ["echo", { CommandLine: `echo '${output}'` }], + outputs: [{ output }], }), ).toBeUndefined(); }); @@ -130,29 +128,47 @@ describe("extractToolCallChallenge", () => { it("refuses fields that disagree on the page", () => { expect( extractToolCallChallenge({ - rawOutput: { output }, - content: [ - { - type: "content", - content: { type: "text", text: challengeText(signInUrl({ state: "other-state" })) }, - }, - ], + inputs: [], + outputs: [{ output }, challengeText(signInUrl({ state: "other-state" }))], }), ).toBeUndefined(); }); }); +describe("plainCommandProgram", () => { + it("names the program of a plain command and nothing that shell syntax could feed", () => { + expect(plainCommandProgram(`gmail readonly search "" --max 3`)).toBe("gmail"); + for (const command of [ + "cat notes.txt; gmail search", + "gmail search | cat", + "gmail search && echo done", + "gmail $(cat x)", + "gmail search > out.txt", + ]) { + expect(plainCommandProgram(command)).toBeUndefined(); + } + }); +}); + describe("makeStreamRedactor", () => { - it("scrubs a pattern split across chunks and keeps the other text", () => { - const redactor = makeStreamRedactor(() => [{ text: URL_OK, replacement: LINK_REMOVED }]); + const none = () => ({ secrets: [], cards: [] }); + + it("scrubs a sign-in URL split across chunks without knowing it first", () => { + const redactor = makeStreamRedactor(none); const text = `Open ${URL_OK} now.`; const chunks = [text.slice(0, 9), text.slice(9, 60), text.slice(60, 200), text.slice(200)]; const emitted = chunks.map((chunk) => redactor.push(chunk)).join("") + redactor.flush(); expect(emitted).toBe(`Open ${LINK_REMOVED} now.`); }); + it("keeps an ordinary link", () => { + const redactor = makeStreamRedactor(none); + const emitted = redactor.push("see https://example.com/docs ") + redactor.flush(); + expect(emitted).toBe("see https://example.com/docs "); + }); + it("drops a standalone card and keeps an inline one", () => { - const patterns = () => [{ text: card(), replacement: "", standalone: true }]; + const patterns = () => ({ secrets: [], cards: [card()] }); const standalone = makeStreamRedactor(patterns); const out = standalone.push("Sign in below:\n\n; const toolUpdate = ( toolCallId: string, - fields: Partial>, + fields: Partial, sessionId = "session-1", ): EffectAcpSchema.SessionNotification => ({ sessionId, update: { sessionUpdate: "tool_call_update", toolCallId, ...fields }, }); +const toolChunk = (toolCallId: string, text: string): EffectAcpSchema.SessionNotification => ({ + sessionId: "session-1", + update: { + sessionUpdate: "tool_call_content_chunk", + toolCallId, + content: { type: "content", content: { type: "text", text } }, + }, +}); const textChunk = (text: string, sessionId = "session-1"): EffectAcpSchema.SessionNotification => ({ sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }, }); -const challengeUpdate = () => +const usage: EffectAcpSchema.SessionNotification = { + sessionId: "session-1", + update: { sessionUpdate: "usage_update", used: 1, size: 2 }, +}; +const gmailRun = { CommandLine: "gmail readonly search" }; +const challengeUpdate = (fields: Partial = {}) => toolUpdate("call-1", { status: "completed", kind: "execute", - rawInput: { CommandLine: "gmail readonly search" }, + rawInput: gmailRun, rawOutput: { output: challengeText(), exit_code: 1 }, content: [{ type: "content", content: { type: "text", text: challengeText() } }], + ...fields, }); const textOf = (notifications: ReadonlyArray) => notifications .map((entry) => entry.update.sessionUpdate === "agent_message_chunk" && entry.update.content.type === "text" ? entry.update.content.text - : "", + : entry.update.sessionUpdate === "tool_call_content_chunk" && + entry.update.content.type === "content" && + entry.update.content.content.type === "text" + ? entry.update.content.content.text + : "", ) .join(""); @@ -202,18 +237,28 @@ describe("makeAntigravityPluginSignIns", () => { const signIns = makeAntigravityPluginSignIns(options); const generation = signIns.openGeneration(); let ids = 0; - const observe = (notification: EffectAcpSchema.SessionNotification, now = 0) => - signIns.observe({ generation, notification, now, newId: () => `attempt-${++ids}` }); - return { signIns, generation, observe }; + const observe = (notification: EffectAcpSchema.SessionNotification) => + signIns.observe({ generation, notification }); + const admit = (candidate: PluginSignInCandidate | undefined, now = 0) => { + expect(candidate).toBeDefined(); + signIns.admit(candidate!, { + attemptId: `attempt-${++ids}`, + displayName: "Gmail", + programs: ["gmail"], + now, + }); + }; + return { signIns, generation, observe, admit }; }; - it("scrubs the page from the projected tool call and offers it to its thread", () => { - const { signIns, observe } = setup(); - const projected = observe(challengeUpdate()); - expect(JSON.stringify(projected)).not.toContain(STATE); - expect(JSON.stringify(projected)).toContain(LINK_REMOVED); - const notice = signIns.takeToolNotice("call-1", owner); - expect(notice?.pluginSignIn).toEqual({ + it("scrubs the page from the projected tool call and offers it once admitted", () => { + const { signIns, observe, admit } = setup(); + const { notifications, candidate } = observe(challengeUpdate()); + expect(JSON.stringify(notifications)).not.toContain(STATE); + expect(JSON.stringify(notifications)).toContain(LINK_REMOVED); + expect(candidate).toMatchObject({ program: "gmail", toolCallId: "call-1" }); + admit(candidate); + expect(signIns.takeToolNotice("call-1", owner)?.pluginSignIn).toEqual({ attemptId: "attempt-1", plugin: "gmail", displayName: "Gmail", @@ -224,9 +269,40 @@ describe("makeAntigravityPluginSignIns", () => { ).toEqual({ url: URL_OK }); }); - it("never opens the page for another thread or session", () => { + // regression: a stream-only challenge used to reach the projector before it was recognized. + it("never projects the first streamed chunk of a page, and admits a stream-only challenge", () => { + const { observe } = setup(); + observe(toolUpdate("call-s", { status: "in_progress", kind: "execute", rawInput: gmailRun })); + const text = challengeText(); + const projected = [70, 260, 400, text.length].flatMap( + (end, index, ends) => + observe(toolChunk("call-s", text.slice(index === 0 ? 0 : ends[index - 1], end))) + .notifications, + ); + const ending = observe(toolUpdate("call-s", { status: "failed" })); + const all = [...projected, ...ending.notifications]; + expect(JSON.stringify(all)).not.toContain(STATE); + expect(JSON.stringify(all)).not.toContain(CHALLENGE_CODE); + expect(textOf(all)).toContain(LINK_REMOVED); + expect(ending.candidate?.challenge.authorizationUrl).toBe(URL_OK); + }); + + it("scrubs a page from a tool that earns no notice", () => { const { signIns, observe } = setup(); - observe(challengeUpdate()); + for (const fields of [ + { kind: "other" as const, rawInput: { url: "https://example.com" } }, + { rawInput: { CommandLine: "cat notes.txt; gmail readonly search" } }, + ]) { + const { notifications, candidate } = observe(challengeUpdate(fields)); + expect(candidate).toBeUndefined(); + expect(JSON.stringify(notifications)).not.toContain(STATE); + } + expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + }); + + it("never opens the page for another thread or session", () => { + const { signIns, observe, admit } = setup(); + admit(observe(challengeUpdate()).candidate); signIns.takeToolNotice("call-1", owner); const other = { ...owner, threadId: ThreadId.make("thread-2") }; expect( @@ -243,8 +319,8 @@ describe("makeAntigravityPluginSignIns", () => { }); it("expires attempts and retires them with their agent process", () => { - const { signIns, generation, observe } = setup({ ttlMs: 1_000 }); - observe(challengeUpdate()); + const { signIns, generation, observe, admit } = setup({ ttlMs: 1_000 }); + admit(observe(challengeUpdate()).candidate); signIns.takeToolNotice("call-1", owner); const redeem = (now: number) => signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now }); @@ -256,40 +332,41 @@ describe("makeAntigravityPluginSignIns", () => { it("ignores model text that writes a card or a page", () => { const { signIns, observe } = setup(); - const projected = observe(textChunk(challengeText())); - expect(textOf(projected)).toBe(challengeText()); + const { candidate } = observe(textChunk(challengeText())); + expect(candidate).toBeUndefined(); expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); }); it("scrubs a repeated page across chunks and hides the repeated card", () => { - const { signIns, generation, observe } = setup(); - observe(challengeUpdate()); + const { signIns, generation, observe, admit } = setup(); + admit(observe(challengeUpdate()).candidate); const reply = `Sign in here: ${URL_OK}\n\n${card()}`; const projected = [ - ...observe(textChunk(reply.slice(0, 30))), - ...observe(textChunk(reply.slice(30, 300))), - ...observe(textChunk(reply.slice(300))), + ...observe(textChunk(reply.slice(0, 30))).notifications, + ...observe(textChunk(reply.slice(30, 300))).notifications, + ...observe(textChunk(reply.slice(300))).notifications, ...signIns.flush(generation), ]; expect(textOf(projected)).toBe(`Sign in here: ${LINK_REMOVED}\n\n`); }); - it("releases held text before the next update", () => { - const { observe } = setup(); - observe(challengeUpdate()); - const held = observe(textChunk("ends with h")); - expect(textOf(held)).toBe("ends with "); - const next = observe({ - sessionId: "session-1", - update: { sessionUpdate: "usage_update", used: 1, size: 2 }, - }); - expect(textOf(next)).toBe("h"); - expect(next.at(-1)?.update.sessionUpdate).toBe("usage_update"); + // regression: an interleaved update used to release half of a split page. + it("holds a split page across interleaved updates until its stream ends", () => { + const { signIns, generation, observe } = setup(); + const reply = `Open ${URL_OK} please`; + const projected = [ + ...observe(textChunk(reply.slice(0, 120))).notifications, + ...observe(usage).notifications, + ...observe(textChunk(reply.slice(120))).notifications, + ...signIns.flush(generation), + ]; + expect(JSON.stringify(projected)).not.toContain(STATE); + expect(textOf(projected)).toBe(`Open ${LINK_REMOVED} please`); }); it("reports the plugin's next successful call as signed in", () => { - const { signIns, observe } = setup(); - observe(challengeUpdate()); + const { signIns, observe, admit } = setup(); + admit(observe(challengeUpdate()).candidate); signIns.takeToolNotice("call-1", owner); observe( toolUpdate("call-2", { @@ -311,11 +388,20 @@ describe("makeAntigravityPluginSignIns", () => { }); it("replaces an older attempt for the same plugin", () => { - const { signIns, observe } = setup(); - observe(challengeUpdate()); + const { signIns, observe, admit } = setup(); + admit(observe(challengeUpdate()).candidate); signIns.takeToolNotice("call-1", owner); const second = challengeText(signInUrl({ state: "second-state" })); - observe(toolUpdate("call-3", { status: "completed", rawOutput: { output: second } })); + admit( + observe( + toolUpdate("call-3", { + status: "completed", + kind: "execute", + rawInput: gmailRun, + rawOutput: { output: second }, + }), + ).candidate, + ); signIns.takeToolNotice("call-3", owner); expect( signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), diff --git a/apps/server/src/scient/antigravity/pluginSignIn.ts b/apps/server/src/scient/antigravity/pluginSignIn.ts index 20d475065c..e8b0a5cf73 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.ts @@ -10,17 +10,17 @@ import type * as EffectAcpSchema from "effect-acp/compat"; const CARD_PATTERN = /<\/plugin-card>/u; const SCHEME_PATTERN = /[a-z][a-z0-9+.-]*:\/\//giu; const URL_TOKEN_PATTERN = /^[^\s<>"'`]+/u; +const URL_IN_TEXT = /https?:\/\/[^\s<>"'`]+/giu; +const URL_STARTS = ["https://", "http://"]; +const AUTHORIZATION_PARAMS = /[?&](?:redirect_uri|state|code_challenge)=/iu; const MAX_TEXT_LENGTH = 32_000; const MAX_URL_LENGTH = 4_096; +const MAX_HOLD = 8_192; const MAX_STATE_LENGTH = 512; const URL_SAFE_VALUE = /^[A-Za-z0-9._~-]+$/u; const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]); - -/** - * Where a plugin may send the user to sign in, as `host/path`. Only Google's own plugins are - * captured so far; a partner's endpoint joins once its challenge is recorded. - */ -const AUTHORIZATION_ENDPOINTS = new Set(["accounts.google.com/o/oauth2/v2/auth"]); +// Unquoted shell syntax that would let a command print text the plugin's CLI did not. +const SHELL_CONTROL = /[;&|<>`$(){}\\\n\r]/u; const DISPLAY_NAMES: Readonly> = { gmail: "Gmail", @@ -37,6 +37,9 @@ const VALUE_REMOVED = "[removed]"; export interface PluginSignInChallenge { readonly plugin: string; readonly authorizationUrl: string; + /** The page's origin and path, which the plugin's installed manifest must declare. */ + readonly endpoint: string; + readonly clientId: string; /** Text to scrub wherever the agent repeats it. */ readonly secrets: ReadonlyArray; } @@ -46,44 +49,51 @@ const single = (params: URLSearchParams, name: string) => { return values.length === 1 ? values[0] : undefined; }; -/** The sign-in page, when it is a known endpoint that redirects to a local agy listener. */ -function validatePluginAuthorizationUrl(raw: string): URL | undefined { - if (raw.length > MAX_URL_LENGTH || raw.includes("#")) return undefined; - let url: URL; +const parseUrl = (value: string) => { try { - url = new URL(raw); + return new URL(value); } catch { return undefined; } +}; + +const isLoopbackRedirect = (value: string) => { + const redirect = parseUrl(value); + return redirect !== undefined && LOOPBACK_HOSTS.has(redirect.hostname); +}; + +/** An HTTPS page with one client, one state and one loopback `/callback` redirect. */ +function validatePluginAuthorizationUrl(raw: string): URL | undefined { + if (raw.length > MAX_URL_LENGTH || raw.includes("#")) return undefined; + const url = parseUrl(raw); if ( + url === undefined || url.protocol !== "https:" || url.username !== "" || url.password !== "" || - url.port !== "" || - !AUTHORIZATION_ENDPOINTS.has(`${url.hostname}${url.pathname}`) + url.port !== "" ) { return undefined; } const state = single(url.searchParams, "state"); const redirectUri = single(url.searchParams, "redirect_uri"); + const clientId = single(url.searchParams, "client_id"); if ( state === undefined || state.length === 0 || state.length > MAX_STATE_LENGTH || !URL_SAFE_VALUE.test(state) || + clientId === undefined || + clientId.length === 0 || redirectUri === undefined || url.searchParams.getAll("code_challenge").length > 1 ) { return undefined; } - let redirect: URL; - try { - redirect = new URL(redirectUri); - } catch { - return undefined; - } - const port = Number(redirect.port); + const redirect = parseUrl(redirectUri); + const port = Number(redirect?.port); if ( + redirect === undefined || redirect.protocol !== "http:" || !LOOPBACK_HOSTS.has(redirect.hostname) || !/^\d+$/u.test(redirect.port) || @@ -108,8 +118,7 @@ function validatePluginAuthorizationUrl(raw: string): URL | undefined { export function extractPluginSignInChallenge(text: string): PluginSignInChallenge | undefined { if (text.length > MAX_TEXT_LENGTH) return undefined; if (text.split("plugin-card").length !== 3) return undefined; - const card = CARD_PATTERN.exec(text); - const plugin = card?.[1]; + const plugin = CARD_PATTERN.exec(text)?.[1]; if (plugin === undefined) return undefined; const schemes = [...text.matchAll(SCHEME_PATTERN)]; if (schemes.length !== 1) return undefined; @@ -121,6 +130,8 @@ export function extractPluginSignInChallenge(text: string): PluginSignInChalleng return { plugin, authorizationUrl: token, + endpoint: `${url.origin}${url.pathname}`, + clientId: url.searchParams.get("client_id")!, secrets: secrets.filter((value): value is string => Predicate.isString(value) && value !== ""), }; } @@ -129,6 +140,24 @@ function pluginDisplayName(plugin: string): string | undefined { return DISPLAY_NAMES[plugin]; } +/** A URL that sends a sign-in back to this computer; an unfinished one counts once it looks like one. */ +function isSignInUrl(token: string, unfinished: boolean): boolean { + const url = parseUrl(token); + if (url?.searchParams.getAll("redirect_uri").some(isLoopbackRedirect) === true) return true; + return unfinished && AUTHORIZATION_PARAMS.test(token); +} + +/** Text with every sign-in URL and known secret replaced. */ +function scrubSignInText(text: string, secrets: ReadonlyArray, openEnd = false): string { + let result = text.replace(URL_IN_TEXT, (token, offset: number) => + isSignInUrl(token, openEnd && offset + token.length === text.length) ? LINK_REMOVED : token, + ); + for (const secret of secrets) { + if (result.includes(secret)) result = result.split(secret).join(VALUE_REMOVED); + } + return result; +} + function collectStrings(value: unknown, into: Array, depth = 0): void { if (depth > 12 || into.length > 256) return; if (Predicate.isString(value)) { @@ -140,21 +169,11 @@ function collectStrings(value: unknown, into: Array, depth = 0): void { } } -const replaceSecrets = (text: string, secrets: ReadonlyArray) => { - let result = text; - for (const [index, secret] of secrets.entries()) { - if (result.includes(secret)) { - result = result.split(secret).join(index === 0 ? LINK_REMOVED : VALUE_REMOVED); - } - } - return result; -}; - -/** A copy of `value` with every secret replaced, in any string at any depth. */ -function redactPluginSignInSecrets(value: A, secrets: ReadonlyArray): A { +/** A copy of `value` with every string scrubbed, at any depth. */ +function scrubPayload(value: A, secrets: ReadonlyArray): A { const visit = (entry: unknown, depth: number): unknown => { if (depth > 16) return entry; - if (Predicate.isString(entry)) return replaceSecrets(entry, secrets); + if (Predicate.isString(entry)) return scrubSignInText(entry, secrets); if (Array.isArray(entry)) return entry.map((item) => visit(item, depth + 1)); if (Predicate.isObject(entry)) { return Object.fromEntries( @@ -166,18 +185,19 @@ function redactPluginSignInSecrets(value: A, secrets: ReadonlyArray): return visit(value, 0) as A; } -/** The one challenge the tool's result carries; text the call was given never counts. */ +/** + * The one challenge a tool's result carries: its outputs must agree, and the call's own input + * never contains the card or the state. + */ export function extractToolCallChallenge(update: { - readonly title?: string | null; - readonly rawInput?: unknown; - readonly rawOutput?: unknown; - readonly content?: unknown; + readonly inputs: ReadonlyArray; + readonly outputs: ReadonlyArray; }): PluginSignInChallenge | undefined { const inputs: Array = []; - collectStrings([update.title, update.rawInput], inputs); + collectStrings(update.inputs, inputs); if (inputs.some((text) => text.includes("plugin-card"))) return undefined; const outputs: Array = []; - collectStrings([update.rawOutput, update.content], outputs); + collectStrings(update.outputs, outputs); let found: PluginSignInChallenge | undefined; for (const text of outputs) { if (!text.includes("plugin-card")) continue; @@ -194,21 +214,24 @@ export function extractToolCallChallenge(update: { return found; } -interface StreamPattern { - readonly text: string; - readonly replacement: string; - /** Removed only on a line of its own. */ - readonly standalone?: boolean; +/** The program a plain shell command runs, or undefined when shell syntax could add output. */ +export function plainCommandProgram(command: string): string | undefined { + const trimmed = command.trim(); + if (trimmed.length === 0 || trimmed.length > 4_096 || SHELL_CONTROL.test(trimmed)) { + return undefined; + } + return /^[A-Za-z0-9._-]+(?=\s|$)/u.exec(trimmed)?.[0]; } -/** The earliest index whose rest of `buffer` begins some pattern without completing it. */ -function partialStart(buffer: string, patterns: ReadonlyArray): number { +/** The earliest index whose rest of `buffer` begins some text without completing it. */ +function partialStart(buffer: string, texts: ReadonlyArray): number { let earliest = -1; - for (const pattern of patterns) { - const from = Math.max(0, buffer.length - pattern.text.length + 1); + const lower = buffer.toLowerCase(); + for (const text of texts) { + const from = Math.max(0, buffer.length - text.length + 1); for (let index = from; index < buffer.length; index++) { if (earliest !== -1 && index >= earliest) break; - if (pattern.text.startsWith(buffer.slice(index))) { + if (text.startsWith(text === text.toLowerCase() ? lower.slice(index) : buffer.slice(index))) { earliest = index; break; } @@ -218,54 +241,66 @@ function partialStart(buffer: string, patterns: ReadonlyArray): n } /** - * Scrubs patterns from text that arrives in chunks. It holds back a tail that could begin a - * pattern until the next chunk or `flush` decides it. + * Scrubs text that arrives in chunks. A tail that could begin a sign-in URL, a known secret or a + * card is held, bounded, until a later chunk completes it or the stream ends (`flush`). */ -export function makeStreamRedactor(patterns: () => ReadonlyArray) { +export function makeStreamRedactor( + patterns: () => { + readonly secrets: ReadonlyArray; + readonly cards: ReadonlyArray; + }, +) { let carry = ""; let previous = "\n"; - const emit = (text: string) => { - if (text.length > 0) previous = text.at(-1)!; - return text; - }; - const process = (input: string, final: boolean) => { - const active = patterns(); - let buffer = input; - let out = ""; - while (buffer.length > 0) { - let match: { index: number; pattern: StreamPattern } | undefined; - // A longer pattern still arriving holds its start, so a shorter one inside it waits. - const partial = final ? -1 : partialStart(buffer, active); - for (const pattern of active) { - const index = buffer.indexOf(pattern.text); - if (index !== -1 && (match === undefined || index < match.index)) { - match = { index, pattern }; - } + const holdPoint = ( + buffer: string, + secrets: ReadonlyArray, + cards: ReadonlyArray, + ) => { + let hold = buffer.length; + for (const match of buffer.matchAll(URL_IN_TEXT)) { + if ( + match.index + match[0].length === buffer.length && + buffer.length - match.index <= MAX_HOLD + ) { + hold = Math.min(hold, match.index); } - if (match === undefined || (partial !== -1 && partial <= match.index)) break; - const { index, pattern } = match; - const before = buffer.slice(0, index); - const end = index + pattern.text.length; - if (pattern.standalone === true) { - const lineStart = (before.length > 0 ? before.at(-1) : (out.at(-1) ?? previous)) === "\n"; - if (end === buffer.length && !final) { - out += before; - carry = buffer.slice(index); - return emit(out); + } + const partial = partialStart(buffer, [...URL_STARTS, ...secrets, ...cards]); + if (partial !== -1) hold = Math.min(hold, partial); + for (const card of cards) { + if (buffer.endsWith(card)) hold = Math.min(hold, buffer.length - card.length); + } + return hold; + }; + const dropStandaloneCards = (text: string, cards: ReadonlyArray, next: string) => { + let result = text; + for (const card of cards) { + let from = 0; + for (;;) { + const index = result.indexOf(card, from); + if (index === -1) break; + const before = index === 0 ? previous : result[index - 1]; + const after = result[index + card.length] ?? next; + if (before === "\n" && (after === "\n" || after === "\r" || after === "")) { + result = result.slice(0, index) + result.slice(index + card.length); + from = index; + } else { + from = index + card.length; } - const next = buffer[end]; - const lineEnd = next === undefined || next === "\n" || next === "\r"; - out += before + (lineStart && lineEnd ? pattern.replacement : pattern.text); - } else { - out += before + pattern.replacement; } - buffer = buffer.slice(end); } - const start = final ? -1 : partialStart(buffer, active); - const hold = start === -1 ? 0 : buffer.length - start; - out += buffer.slice(0, buffer.length - hold); - carry = buffer.slice(buffer.length - hold); - return emit(out); + return result; + }; + const process = (buffer: string, final: boolean) => { + const { secrets, cards } = patterns(); + const hold = final ? buffer.length : holdPoint(buffer, secrets, cards); + const region = buffer.slice(0, hold); + carry = buffer.slice(hold); + const scrubbed = scrubSignInText(region, secrets, hold === buffer.length); + const out = dropStandaloneCards(scrubbed, cards, final ? "" : (carry[0] ?? "\u0000")); + if (out.length > 0) previous = out.at(-1)!; + return out; }; return { push: (chunk: string) => process(carry + chunk, false), @@ -274,9 +309,6 @@ export function makeStreamRedactor(patterns: () => ReadonlyArray) carry = ""; return held.length === 0 ? "" : process(held, true); }, - get holding() { - return carry.length > 0; - }, }; } @@ -285,11 +317,22 @@ export interface PluginSignInOwner { readonly providerThreadId: ProviderThreadId; } +/** A challenge seen in a plain run of a CLI; it offers a sign-in only once the plugin vouches for it. */ +export interface PluginSignInCandidate { + readonly sessionId: string; + readonly toolCallId: string; + readonly generation: number; + /** The program the command ran. */ + readonly program: string; + readonly challenge: PluginSignInChallenge; +} + interface Attempt { readonly id: string; readonly plugin: string; + readonly displayName: string | undefined; + readonly programs: ReadonlyArray; readonly url: string; - readonly secrets: ReadonlyArray; readonly sessionId: string; readonly generation: number; readonly expiresAt: number; @@ -298,6 +341,13 @@ interface Attempt { signedIn: boolean; } +interface TrackedTool { + kind?: string | null | undefined; + title?: string | null | undefined; + rawInput?: unknown; + streamed: string; +} + export type PluginSignInRedeemFailure = "expired" | "not-found"; export interface PluginSignInToolNotice { @@ -313,9 +363,6 @@ type ChunkUpdate = Extract< { readonly sessionUpdate: "agent_message_chunk" | "agent_thought_chunk" } >; -const commandRunsPlugin = (command: string, plugin: string) => - new RegExp(`(?:^|[;&|]\\s*)${plugin}(?:\\s|$)`, "u").test(command.trim()); - const exitCodeOf = (rawOutput: unknown) => { if (!Predicate.isObject(rawOutput)) return undefined; const code = rawOutput.exit_code ?? rawOutput.exitCode; @@ -329,9 +376,13 @@ const commandOf = (rawInput: unknown) => { return Predicate.isString(command) ? command : undefined; }; +const isTerminal = (status: string | null | undefined) => + status === "completed" || status === "failed"; + /** - * Challenges a live Antigravity adapter has seen. Attempts belong to one agent process - * generation and expire; the notice names an attempt, and only its thread can open it. + * Challenges a live Antigravity adapter has seen. Every sign-in URL is scrubbed before + * projection; an attempt exists only for a candidate the caller admitted, belongs to one agent + * process generation and expires, and only the thread that showed it can open it. */ export function makeAntigravityPluginSignIns( options: { @@ -350,39 +401,33 @@ export function makeAntigravityPluginSignIns( string, { readonly redactor: ReturnType; template: Notification } >(); + const tools = new Map(); + // Secrets of every challenge a session printed, admitted or not. + const secretsBySession = new Map>(); // Each session's latest agent process, so a prompt's end releases only its own held text. const sessionGenerations = new Map(); let nextGeneration = 0; - const sessionPatterns = (sessionId: string) => (): ReadonlyArray => { - const patterns: Array = []; - for (const attempt of attempts.values()) { - if (attempt.sessionId !== sessionId) continue; - for (const [index, secret] of attempt.secrets.entries()) { - patterns.push({ text: secret, replacement: index === 0 ? LINK_REMOVED : VALUE_REMOVED }); - } - if (attempt.live) { - patterns.push({ - text: ``, - replacement: "", - standalone: true, - }); - } - } - return patterns; + const sessionPatterns = (sessionId: string) => () => ({ + secrets: secretsBySession.get(sessionId) ?? [], + cards: [...attempts.values()] + .filter((attempt) => attempt.sessionId === sessionId && attempt.live) + .map((attempt) => ``), + }); + + const rememberSecrets = (sessionId: string, secrets: ReadonlyArray) => { + const known = secretsBySession.get(sessionId) ?? []; + for (const secret of secrets) if (!known.includes(secret)) known.push(secret); + secretsBySession.set(sessionId, known.slice(-32)); }; - const sessionHasAttempts = (sessionId: string) => - [...attempts.values()].some((attempt) => attempt.sessionId === sessionId); - const sessionSecrets = (sessionId: string) => - [...attempts.values()] - .filter((attempt) => attempt.sessionId === sessionId) - .flatMap((attempt) => attempt.secrets); - - /** Releases the held text of a session's channels other than `keep`. */ - const flushSession = (sessionId: string, keep?: string): ReadonlyArray => { + + /** Ends the session's streams that `ends` selects, releasing what they held, in order. */ + const flushStreams = (sessionId: string, ends: (channel: string) => boolean) => { const flushed: Array = []; + const prefix = `${sessionId}\u0000`; for (const [key, entry] of redactors) { - if (key === keep || !key.startsWith(`${sessionId}\u0000`)) continue; + if (!key.startsWith(prefix) || !ends(key.slice(prefix.length))) continue; + redactors.delete(key); const text = entry.redactor.flush(); if (text.length === 0) continue; const update = entry.template.update; @@ -397,14 +442,6 @@ export function makeAntigravityPluginSignIns( return flushed; }; - const evict = () => { - while (attempts.size > maxAttempts) { - const oldest = attempts.keys().next().value; - if (oldest === undefined) break; - attempts.delete(oldest); - } - }; - const streamChunk = ( notification: Notification, channel: string, @@ -421,9 +458,31 @@ export function makeAntigravityPluginSignIns( redactors.set(key, entry); } entry.template = notification; - const others = flushSession(notification.sessionId, key); const emitted = entry.redactor.push(text); - return emitted.length === 0 ? others : [...others, rebuild(emitted)]; + return emitted.length === 0 ? [] : [rebuild(emitted)]; + }; + + const trackTool = (sessionId: string, toolCallId: string) => { + const key = `${sessionId}\u0000${toolCallId}`; + let tool = tools.get(key); + if (tool === undefined) { + tool = { streamed: "" }; + tools.set(key, tool); + while (tools.size > 512) { + const oldest = tools.keys().next().value; + if (oldest === undefined) break; + tools.delete(oldest); + } + } + return { key, tool }; + }; + + const evict = () => { + while (attempts.size > maxAttempts) { + const oldest = attempts.keys().next().value; + if (oldest === undefined) break; + attempts.delete(oldest); + } }; return { @@ -435,15 +494,16 @@ export function makeAntigravityPluginSignIns( } }, /** - * The notifications to project in place of `notification`: challenge URLs scrubbed, text - * held back while it could begin one, and held text released before other updates. + * The notifications to project in place of `notification`, with every sign-in URL and known + * secret scrubbed, and the challenge a plain CLI run printed, for the caller to verify. */ observe: (input: { readonly generation: number; readonly notification: Notification; - readonly now: number; - readonly newId: () => string; - }): ReadonlyArray => { + }): { + readonly notifications: ReadonlyArray; + readonly candidate: PluginSignInCandidate | undefined; + } => { const { notification } = input; const update = notification.update; const sessionId = notification.sessionId; @@ -453,25 +513,28 @@ export function makeAntigravityPluginSignIns( update.sessionUpdate === "agent_thought_chunk") && update.content.type === "text" ) { - if ( - !sessionHasAttempts(sessionId) && - !redactors.has(`${sessionId}\u0000${update.sessionUpdate}`) - ) { - return [notification]; - } - return streamChunk(notification, update.sessionUpdate, update.content.text, (text) => ({ - ...notification, - update: { ...update, content: { ...update.content, text } }, - })); + return { + notifications: streamChunk( + notification, + update.sessionUpdate, + update.content.text, + (text) => ({ + ...notification, + update: { ...update, content: { ...update.content, text } }, + }), + ), + candidate: undefined, + }; } if (update.sessionUpdate === "tool_call_content_chunk") { const content = update.content; - if ( - content.type === "content" && - content.content.type === "text" && - sessionHasAttempts(sessionId) - ) { - return streamChunk( + if (content.type !== "content" || content.content.type !== "text") { + return { notifications: [notification], candidate: undefined }; + } + const { tool } = trackTool(sessionId, update.toolCallId); + tool.streamed = (tool.streamed + content.content.text).slice(-MAX_TEXT_LENGTH); + return { + notifications: streamChunk( notification, `tool:${update.toolCallId}`, content.content.text, @@ -479,52 +542,52 @@ export function makeAntigravityPluginSignIns( ...notification, update: { ...update, content: { ...content, content: { ...content.content, text } } }, }), - ); - } - return [...flushSession(sessionId), notification]; + ), + candidate: undefined, + }; } - const flushed = flushSession(sessionId); if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { - return [...flushed, notification]; + return { notifications: [notification], candidate: undefined }; } - const challenge = extractToolCallChallenge(update); + // A tool call ends the reply streams; its own output stream ends with the call. + const terminal = isTerminal(update.status); + const flushed = flushStreams( + sessionId, + (channel) => + !channel.startsWith("tool:") || (terminal && channel === `tool:${update.toolCallId}`), + ); + const { key, tool } = trackTool(sessionId, update.toolCallId); + if (update.kind !== undefined) tool.kind = update.kind; + if (update.title !== undefined) tool.title = update.title; + if (update.rawInput !== undefined) tool.rawInput = update.rawInput; + const challenge = extractToolCallChallenge({ + inputs: [tool.title, tool.rawInput], + outputs: [update.rawOutput, update.content, terminal ? tool.streamed : undefined], + }); + const command = commandOf(tool.rawInput); + let candidate: PluginSignInCandidate | undefined; if (challenge !== undefined) { - let attempt = [...attempts.values()].find( - (candidate) => - candidate.sessionId === sessionId && candidate.url === challenge.authorizationUrl, - ); - if (attempt === undefined) { - for (const previous of attempts.values()) { - if (previous.sessionId === sessionId && previous.plugin === challenge.plugin) { - previous.live = false; - } - } - attempt = { - id: input.newId(), - plugin: challenge.plugin, - url: challenge.authorizationUrl, - secrets: challenge.secrets, + rememberSecrets(sessionId, challenge.secrets); + const program = command === undefined ? undefined : plainCommandProgram(command); + if (tool.kind === "execute" && program !== undefined) { + candidate = { sessionId, + toolCallId: update.toolCallId, generation: input.generation, - expiresAt: input.now + ttlMs, - owner: undefined, - live: true, - signedIn: false, + program, + challenge, }; - attempts.set(attempt.id, attempt); - evict(); } - pendingNotices.set(update.toolCallId, { attemptId: attempt.id, signedIn: false }); } else if (update.status === "completed" && exitCodeOf(update.rawOutput) === 0) { - const command = commandOf(update.rawInput); + const program = command === undefined ? undefined : plainCommandProgram(command); const waiting = [...attempts.values()] .toReversed() .find( (attempt) => attempt.sessionId === sessionId && !attempt.signedIn && - command !== undefined && - commandRunsPlugin(command, attempt.plugin), + program !== undefined && + attempt.programs.includes(program), ); if (waiting !== undefined) { waiting.signedIn = true; @@ -532,18 +595,57 @@ export function makeAntigravityPluginSignIns( pendingNotices.set(update.toolCallId, { attemptId: waiting.id, signedIn: true }); } } - const secrets = sessionSecrets(sessionId); - const scrubbed = - secrets.length === 0 - ? notification - : { ...notification, update: redactPluginSignInSecrets(update, secrets) }; - return [...flushed, scrubbed]; + if (terminal) tools.delete(key); + const scrubbed = { + ...notification, + update: scrubPayload(update, secretsBySession.get(sessionId) ?? []), + }; + return { notifications: [...flushed, scrubbed], candidate }; + }, + /** Offers the sign-in a verified candidate printed, replacing the plugin's older attempt. */ + admit: ( + candidate: PluginSignInCandidate, + verified: { + readonly attemptId: string; + readonly displayName: string | undefined; + readonly programs: ReadonlyArray; + readonly now: number; + }, + ) => { + const { challenge, sessionId } = candidate; + let attempt = [...attempts.values()].find( + (existing) => + existing.sessionId === sessionId && existing.url === challenge.authorizationUrl, + ); + if (attempt === undefined) { + for (const previous of attempts.values()) { + if (previous.sessionId === sessionId && previous.plugin === challenge.plugin) { + previous.live = false; + } + } + attempt = { + id: verified.attemptId, + plugin: challenge.plugin, + displayName: verified.displayName ?? pluginDisplayName(challenge.plugin), + programs: verified.programs, + url: challenge.authorizationUrl, + sessionId, + generation: candidate.generation, + expiresAt: verified.now + ttlMs, + owner: undefined, + live: true, + signedIn: false, + }; + attempts.set(attempt.id, attempt); + evict(); + } + pendingNotices.set(candidate.toolCallId, { attemptId: attempt.id, signedIn: false }); }, - /** Held text of an agent process's sessions, released when its prompt ends. */ + /** Ends every stream of an agent process's sessions when its prompt ends. */ flush: (generation: number) => [...sessionGenerations] .filter(([, owner]) => owner === generation) - .flatMap(([sessionId]) => flushSession(sessionId)), + .flatMap(([sessionId]) => flushStreams(sessionId, () => true)), /** The notice a tool call raised, once; it binds the attempt to the thread that shows it. */ takeToolNotice: ( toolCallId: string, @@ -555,12 +657,11 @@ export function makeAntigravityPluginSignIns( const attempt = attempts.get(pending.attemptId); if (attempt === undefined) return undefined; attempt.owner ??= owner; - const displayName = pluginDisplayName(attempt.plugin); - const name = displayName ?? attempt.plugin; + const name = attempt.displayName ?? attempt.plugin; const pluginSignIn = { attemptId: attempt.id, plugin: attempt.plugin, - ...(displayName === undefined ? {} : { displayName }), + ...(attempt.displayName === undefined ? {} : { displayName: attempt.displayName }), ...(pending.signedIn ? { signedIn: true } : {}), }; return pending.signedIn From 69fcb484c2b47ab497f533820d24cc2cf238b8e0 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:47:02 +0200 Subject: [PATCH 24/36] fix(web): offer local-only sign-ins only on a proven same-computer connection A browser opened against a Scient server on another machine took that server for its own computer: the Antigravity action opened a page whose loopback callback its agent never hears, and the Codex dialog waited for the agent's own callback. Only the desktop app talking to its managed backend, or to the background service sharing its home, now counts as the same computer. Elsewhere Antigravity says to sign in on the agent's computer and Codex keeps only the paste path. Co-Authored-By: Claude Opus 5.5 --- .../McpSignInAction.scient.browser.test.tsx | 38 ++++++++++++++---- .../src/components/chat/McpSignInAction.tsx | 6 ++- .../PluginSignInAction.browser.test.tsx | 12 +++--- .../scient/antigravity/PluginSignInAction.tsx | 6 +-- apps/web/src/scient/sameHost.ts | 23 +++++++++++ .../src/scient/sameHostEnvironments.test.ts | 39 +++++++++++++++++++ apps/web/src/scient/sameHostEnvironments.ts | 19 +++++++++ 7 files changed, 126 insertions(+), 17 deletions(-) create mode 100644 apps/web/src/scient/sameHost.ts create mode 100644 apps/web/src/scient/sameHostEnvironments.test.ts create mode 100644 apps/web/src/scient/sameHostEnvironments.ts diff --git a/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx b/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx index 43c3d61f87..737d8f4a9d 100644 --- a/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx +++ b/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx @@ -5,6 +5,8 @@ import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import { render } from "../../../test/render"; +import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; +import { sameHostEnvironmentIdsAtom } from "../../scient/sameHost"; import { McpSignInAction } from "./McpSignInAction"; const fixture = vi.hoisted(() => ({ @@ -31,6 +33,9 @@ vi.mock("../../state/use-atom-command", async () => { command === threadEnvironment.mcpSignInStart ? fixture.start : fixture.complete, }; }); +vi.mock("../../scient/sameHost", () => ({ + sameHostEnvironmentIdsAtom: Atom.make>(new Set(["synthetic"])), +})); vi.mock("../../localApi", () => ({ ensureLocalApi: () => ({ shell: { openExternal: fixture.openExternal } }), })); @@ -42,6 +47,7 @@ function setup() { }); return { [Symbol.dispose]: () => { + appAtomRegistry.set(sameHost, new Set(["synthetic"])); fixture.start.mockReset(); fixture.complete.mockReset(); fixture.openExternal.mockReset(); @@ -49,14 +55,18 @@ function setup() { }; } +const sameHost = sameHostEnvironmentIdsAtom as Atom.Writable>; + const action = ( - + + + ); it("finishes without a pasted address once the agent reports the browser reached it", async () => { @@ -87,3 +97,17 @@ it("keeps the paste field when the agent never reports the sign-in", async () => .element(page.getByRole("textbox", { name: "Address of the page your browser opened" })) .toBeVisible(); }); + +// regression: a browser on another computer used to wait for a callback its agent never hears. +it("only offers pasting when the agent may run on another computer", async () => { + using _fixture = setup(); + appAtomRegistry.set(sameHost, new Set()); + fixture.complete.mockResolvedValue({ _tag: "Success", value: { signedInAt: "2026-01-01" } }); + await using _screen = await render(action); + await page.getByRole("button", { name: "Sign in to linear" }).click(); + await page.getByRole("button", { name: "Open sign-in page" }).click(); + await expect + .element(page.getByRole("textbox", { name: "Address of the page your browser opened" })) + .toBeVisible(); + expect(fixture.complete).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/chat/McpSignInAction.tsx b/apps/web/src/components/chat/McpSignInAction.tsx index f121ba7c6e..d56becd35d 100644 --- a/apps/web/src/components/chat/McpSignInAction.tsx +++ b/apps/web/src/components/chat/McpSignInAction.tsx @@ -21,6 +21,8 @@ import { } from "../ui/dialog"; import { Input } from "../ui/input"; import { toastManager } from "../ui/toast"; +// SCIENT-FORK: only a verified same-computer connection waits for the agent's own callback. +import { sameHostEnvironmentIdsAtom } from "~/scient/sameHost"; type SignIn = | { readonly phase: "starting" } @@ -51,6 +53,8 @@ export function McpSignInAction({ const gt = useGT(); const formId = useId(); const allowed = useAtomValue(threadEnvironment.mcpSignInStart.permissionAtom(environmentId)); + // SCIENT-FORK: only the desktop app proves the agent shares its computer; see awaitBrowser. + const sameHost = useAtomValue(sameHostEnvironmentIdsAtom).has(environmentId); const signedIn = useAtomValue( threadEnvironment.mcpSignedInAtom(environmentId, { threadId, server, noticeAt }), ); @@ -107,7 +111,7 @@ export function McpSignInAction({ // the sign-in finishes when the agent reports it; pasting stays for other setups. const awaitBrowser = async () => { const current = attempt.current; - if (awaiting.current === current) return; + if (!sameHost || awaiting.current === current) return; awaiting.current = current; const result = await complete({ environmentId, input }); if (current !== attempt.current || result._tag === "Failure") return; diff --git a/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx b/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx index 71e8e9bfe4..ea4dbc779a 100644 --- a/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx +++ b/apps/web/src/scient/antigravity/PluginSignInAction.browser.test.tsx @@ -7,7 +7,7 @@ import { page } from "vite-plus/test/browser"; import { render } from "../../../test/render"; import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; -import { localEnvironmentIdAtom } from "../../state/primaryEnvironment"; +import { sameHostEnvironmentIdsAtom } from "../sameHost"; import { PluginSignInAction } from "./PluginSignInAction"; const environmentId = EnvironmentId.make("synthetic-local"); @@ -25,8 +25,8 @@ const fixture = vi.hoisted(() => ({ vi.mock("./pluginSignInCommands", () => ({ pluginSignInOpenCommand: { permissionAtom: () => Atom.make(true) }, })); -vi.mock("../../state/primaryEnvironment", () => ({ - localEnvironmentIdAtom: Atom.make("synthetic-local"), +vi.mock("../sameHost", () => ({ + sameHostEnvironmentIdsAtom: Atom.make>(new Set(["synthetic-local"])), })); vi.mock("../../state/entities", () => ({ useQuietThreadVisibleTurnItems: () => fixture.items, @@ -42,7 +42,7 @@ vi.mock("../extensions/openAuthorizationPage", () => ({ }, })); -const local = localEnvironmentIdAtom as Atom.Writable; +const sameHost = sameHostEnvironmentIdsAtom as Atom.Writable>; /** Resets the shared fixture when the test ends. */ function setup() { @@ -51,7 +51,7 @@ function setup() { fixture.items = []; fixture.opening = "opened"; fixture.open.mockReset(); - appAtomRegistry.set(local, "synthetic-local"); + appAtomRegistry.set(sameHost, new Set(["synthetic-local"])); }, }; } @@ -119,7 +119,7 @@ it("shows Signed in once the plugin's next call worked", async () => { it("never offers the page to a client on another computer", async () => { using _fixture = setup(); - appAtomRegistry.set(local, null); + appAtomRegistry.set(sameHost, new Set()); await using _screen = await render(action()); await expect .element(page.getByText("Sign in on the computer that runs this agent")) diff --git a/apps/web/src/scient/antigravity/PluginSignInAction.tsx b/apps/web/src/scient/antigravity/PluginSignInAction.tsx index 0c22f767c2..108a7df5b5 100644 --- a/apps/web/src/scient/antigravity/PluginSignInAction.tsx +++ b/apps/web/src/scient/antigravity/PluginSignInAction.tsx @@ -15,7 +15,7 @@ import { useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; import { InlineButton } from "../../components/ui/button"; import { formatEnvironmentQueryError } from "../../state/query"; import { useQuietThreadVisibleTurnItems } from "../../state/entities"; -import { localEnvironmentIdAtom } from "../../state/primaryEnvironment"; +import { sameHostEnvironmentIdsAtom } from "../sameHost"; import { useAtomCommand } from "../../state/use-atom-command"; import { openAuthorizationPage } from "../extensions/openAuthorizationPage"; import { pluginSignInOpenCommand } from "./pluginSignInCommands"; @@ -46,7 +46,7 @@ export function PluginSignInAction({ }) { const gt = useGT(); const allowed = useAtomValue(pluginSignInOpenCommand.permissionAtom(environmentId)); - const localEnvironmentId = useAtomValue(localEnvironmentIdAtom); + const sameHost = useAtomValue(sameHostEnvironmentIdsAtom).has(environmentId); const items = useQuietThreadVisibleTurnItems(scopeThreadRef(environmentId, threadId)); const open = useAtomCommand(pluginSignInOpenCommand, { reportFailure: false }); const [state, setState] = useState({ phase: "idle" }); @@ -68,7 +68,7 @@ export function PluginSignInAction({ ); } if (!allowed) return null; - if (localEnvironmentId !== environmentId) { + if (!sameHost) { return ( Sign in on the computer that runs this agent diff --git a/apps/web/src/scient/sameHost.ts b/apps/web/src/scient/sameHost.ts new file mode 100644 index 0000000000..8835284e31 --- /dev/null +++ b/apps/web/src/scient/sameHost.ts @@ -0,0 +1,23 @@ +import { Atom } from "effect/reactivity"; + +import { readPrimaryEnvironmentTarget } from "../environments/primary/target"; +import { hostEnvironmentIdAtom, primaryEnvironmentIdAtom } from "../state/primaryEnvironment"; +import { sameHostEnvironmentIds } from "./sameHostEnvironments"; + +const desktopManagedPrimary = () => { + try { + return readPrimaryEnvironmentTarget()?.source === "desktop-managed"; + } catch { + return false; + } +}; + +/** See `sameHostEnvironmentIds`; a browser's loopback is not the agent's. */ +export const sameHostEnvironmentIdsAtom = Atom.make((get) => + sameHostEnvironmentIds({ + desktopApp: window.desktopBridge !== undefined, + desktopManagedPrimary: desktopManagedPrimary(), + primaryEnvironmentId: get(primaryEnvironmentIdAtom), + hostEnvironmentId: get(hostEnvironmentIdAtom), + }), +).pipe(Atom.withLabel("scient-same-host-environment-ids")); diff --git a/apps/web/src/scient/sameHostEnvironments.test.ts b/apps/web/src/scient/sameHostEnvironments.test.ts new file mode 100644 index 0000000000..0285b33cf6 --- /dev/null +++ b/apps/web/src/scient/sameHostEnvironments.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { sameHostEnvironmentIds } from "./sameHostEnvironments"; + +describe("sameHostEnvironmentIds", () => { + // regression: a browser opened against a remote server took its page origin for this computer. + it("trusts no environment from a browser, whatever its page origin serves", () => { + expect( + sameHostEnvironmentIds({ + desktopApp: false, + desktopManagedPrimary: false, + primaryEnvironmentId: "remote-server", + hostEnvironmentId: null, + }).size, + ).toBe(0); + }); + + it("trusts the desktop app's own backend and the service sharing its home", () => { + expect([ + ...sameHostEnvironmentIds({ + desktopApp: true, + desktopManagedPrimary: true, + primaryEnvironmentId: "local", + hostEnvironmentId: "service", + }), + ]).toEqual(["local", "service"]); + }); + + it("does not trust a desktop app's primary that points at another server", () => { + expect([ + ...sameHostEnvironmentIds({ + desktopApp: true, + desktopManagedPrimary: false, + primaryEnvironmentId: "configured-remote", + hostEnvironmentId: null, + }), + ]).toEqual([]); + }); +}); diff --git a/apps/web/src/scient/sameHostEnvironments.ts b/apps/web/src/scient/sameHostEnvironments.ts new file mode 100644 index 0000000000..0883812005 --- /dev/null +++ b/apps/web/src/scient/sameHostEnvironments.ts @@ -0,0 +1,19 @@ +/** + * Environments whose server runs on this computer, as only the desktop app can prove: its own + * managed backend, or the background service sharing its home. A browser has none, since the + * server behind its page origin may be another machine. + */ +export function sameHostEnvironmentIds(input: { + readonly desktopApp: boolean; + readonly desktopManagedPrimary: boolean; + readonly primaryEnvironmentId: string | null; + readonly hostEnvironmentId: string | null; +}): ReadonlySet { + const ids = new Set(); + if (!input.desktopApp) return ids; + if (input.desktopManagedPrimary && input.primaryEnvironmentId !== null) { + ids.add(input.primaryEnvironmentId); + } + if (input.hostEnvironmentId !== null) ids.add(input.hostEnvironmentId); + return ids; +} From 8fd675e97ddf9738fb5298806ad3beb49475b0e1 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sat, 21 Nov 2026 23:48:05 +0200 Subject: [PATCH 25/36] docs: record plugin sign-in provenance and same-computer gating The Extensions internals describe redaction before projection, the installed-manifest checks a plugin challenge must pass, and the desktop-only same-computer rule. Help says plugin and no-paste MCP sign-ins work from the desktop app on the agent's computer. Co-Authored-By: Claude Opus 5.5 --- docs/internals/scient-extensions.md | 45 ++++++++++++++++++----------- docs/user/providers-antigravity.md | 9 +++--- docs/user/providers-codex.md | 4 +-- 3 files changed, 35 insertions(+), 23 deletions(-) diff --git a/docs/internals/scient-extensions.md b/docs/internals/scient-extensions.md index efa79a6a33..ec509154b4 100644 --- a/docs/internals/scient-extensions.md +++ b/docs/internals/scient-extensions.md @@ -840,7 +840,8 @@ ServerProviderMcpServer { name; status: "connected" | "failed" | "needs-auth" | `complete` without a callback address waits up to five minutes for Codex's `mcpServer/oauthLogin/completed`, which Codex sends when a browser on its computer reached its own callback page; the dialog starts that wait when it - opens the page and keeps the paste field for remote setups. Claude reports no + opens the page, only on a connection the desktop app proves is on the agent's + computer, and keeps the paste field for every setup. Claude reports no finished sign-in, so without an address it succeeds only when the server already shows as connected. A finished or already-valid sign-in refreshes the provider instance, so this section stops showing needs-sign-in. @@ -852,23 +853,33 @@ ServerProviderMcpServer { name; status: "connected" | "failed" | "needs-auth" | live in `CODEX_HOME/.credentials.json`, which a shadow home links to the shared home only if the file existed when the shadow home was built. Two instances sharing a home can then disagree until each signs in. -- **Antigravity plugins** (`scient/antigravity/pluginSignIn.ts`): a plugin's - failed tool call prints a `` and a sign-in link - whose loopback redirect the running agy process serves. The adapter accepts a - challenge only from a tool result with exactly one well-formed card and one - URL, never from the call's own input or model text. The URL must be HTTPS at a - listed authorization endpoint (Google's today; a partner's joins once its - challenge is captured), without userinfo or fragment, with one `state` and one - `redirect_uri` that is HTTP loopback with a port of 1024 or above and path - `/callback`. The page stays server-side for ten minutes, bound to the session, +- **Antigravity plugins** (`scient/antigravity/pluginSignIn.ts`, + `pluginAuthManifest.ts`): a plugin's failed tool call prints a + `` and a sign-in link whose loopback redirect the + running agy process serves. Every URL whose `redirect_uri` is loopback is + scrubbed from tool snapshots and from every streamed channel before anything + projects it, whether or not a notice follows, together with the `state` and + `code_challenge` of any challenge seen. A stream holds a possible partial URL, + secret or card (bounded) until that stream ends: a tool's output with its call, + a reply at the next tool call or the prompt's end. A challenge needs exactly one + well-formed card and one URL in the tool's result, never in its input; streamed + output counts once its call ends. It earns a notice only from a plain shell run + (no pipes, chaining, redirection or substitution) of a CLI that the installed + plugin's `auth.json` lists under `providers.*.clis`, read bounded from + `~/.gemini/config/plugins//`, whose `plugin.json` name equals the card's + `catalog-id`, and whose `oauth2.authorizeUrl` and `oauth2.clientId` match the + page's origin, path and `client_id`. The page must also be HTTPS with no + userinfo or fragment, one `state`, and one `redirect_uri` that is HTTP loopback + with a port of 1024 or above and path `/callback`. Partner plugins that sign in + through MCP OAuth declare no CLI, so they get no button until their challenge + is captured. The page stays server-side for ten minutes, bound to the session, the agent process (an exit or replacement retires it) and the thread that - showed the notice; a newer challenge for the plugin replaces it. Tool output and - streamed text are scrubbed of the URL, `state` and `code_challenge` before - anything projects them, holding back text that could begin one until the next - update or the prompt's end. A model-repeated card on its own line is dropped - while the attempt is live. `scient.pluginSignIn.open` (providers-manage grant) - returns the page only on a click from the agent's own computer; the next - successful call of the plugin's command raises a signed-in notice. + showed the notice; a newer challenge for the plugin replaces it. A + model-repeated card on its own line is dropped while the attempt is live. + `scient.pluginSignIn.open` (providers-manage grant) returns the page only on a + click from a connection the desktop app proves is on the agent's computer + (`scient/sameHost.ts`); the next successful run of one of the plugin's CLIs + raises a signed-in notice. ### Shared plugins source diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 8233af21df..af842e39a3 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -209,10 +209,11 @@ the running agent receives the approval itself. Then ask the agent to try again. **Signed in** once the plugin's next call works, or after you choose **I've signed in**. The sign-in page works only while the agent that asked for it is still running, for up to ten -minutes, and only in a browser on the computer that runs the agent. If the notice says to ask the -agent to try again, send a message so the plugin asks for a new sign-in. Scient keeps the sign-in -link out of the conversation, and never reads or stores the plugin's credentials. Signing in needs -permission to manage providers. +minutes, and only from the Scient desktop app on the computer that runs the agent. If the notice +says to ask the agent to try again, send a message so the plugin asks for a new sign-in. Scient +keeps sign-in links out of the conversation, and never reads or stores the plugin's credentials. +Only Google's plugins that sign in through their own command offer the button for now. Signing in +needs permission to manage providers. ## Run a native goal diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index a5b15a0fa3..5bac98e081 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -147,8 +147,8 @@ contains a copied Codex setup. Use a fresh shadow directory and sign in again. ## Sign in to an MCP server When an MCP server you added to Codex needs you to sign in, the thread shows a notice with -**Sign in**; on mobile, tap the notice. Approve access on the page it opens. When your browser runs -on the computer that runs Codex, Codex receives the approval itself and the dialog closes with +**Sign in**; on mobile, tap the notice. Approve access on the page it opens. In the Scient desktop +app on the computer that runs Codex, Codex receives the approval itself and the dialog closes with **Signed in**. Otherwise your browser goes to a page that may not load: copy that page's address, paste it into Scient, and choose **Finish sign-in**. Codex reconnects the server in that thread and keeps the sign-in for other threads on the same Codex instance, and **Extensions** shows the server From 46d1728af352106b3015eab597286a82491ee21a Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 00:34:51 +0200 Subject: [PATCH 26/36] fix(extensions): recognise the Antigravity plugins a user already has A plugin agy installed from its own marketplace showed as "from another source" because only Scient's install receipt counted. Origin now comes from agy's own record first, then Scient's receipt, then, for copies installed before agy recorded origins, the installed plugin.json matching the catalog's repository, author or description. Add uses agy's own marketplace install when agy is signed in, so agy records the origin and keeps the plugin updated; the checked archive stays the fallback. A service row for a plugin Scient can't add explains why and links to Installed instead of showing a disabled Add. Co-Authored-By: Claude Opus 5.5 --- .../extensions/AntigravityPluginCatalog.ts | 14 ++ .../AntigravityProviderStore.test.ts | 114 ++++++++++++++- .../extensions/AntigravityProviderStore.ts | 133 +++++++++++++++--- .../extensions/Extensions.browser.test.tsx | 9 ++ .../src/scient/extensions/ServiceAgents.tsx | 11 +- 5 files changed, 257 insertions(+), 24 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts index 874bc08b6b..662e5bed29 100644 --- a/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts +++ b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts @@ -52,6 +52,7 @@ const FeedPlugin = Schema.Struct({ logo: Schema.optional(Schema.Unknown), author: Schema.optional(Schema.Unknown), homepage: Schema.optional(Schema.Unknown), + repository: Schema.optional(Schema.Unknown), category: Schema.optional(Schema.Unknown), keywords: Schema.optional(Schema.Unknown), skills: Schema.optional(Schema.Unknown), @@ -84,6 +85,14 @@ export interface AntigravityCatalogPlugin { readonly mcpServers: ReadonlyArray; /** Absent when the catalog's download is not a checksummed gstatic archive. */ readonly archive?: { readonly url: string; readonly sha256: string } | undefined; + /** The manifest fields an installed copy shares with this entry, as the feed states them. */ + readonly identity: AntigravityPluginIdentity; +} + +export interface AntigravityPluginIdentity { + readonly repository?: string | undefined; + readonly author?: string | undefined; + readonly description?: string | undefined; } export interface AntigravityCatalogRead { @@ -318,6 +327,11 @@ function catalogPlugin( skills, mcpServers, archive, + identity: { + repository: nonBlank(plugin.repository), + author, + description: nonBlank(plugin.description), + }, }; } diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index f1983acd0c..e571570583 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -50,8 +50,14 @@ interface Fixture { readonly stagedScriptModes: number[]; listOutput?: string; unavailable?: string; + /** Whether agy itself is signed in, which its own marketplace install needs. */ + nativeSignedIn?: boolean; } +const GMAIL_DESCRIPTION = "Search, read, draft, and send emails in Gmail."; +const isArchiveInstall = (call: ReadonlyArray) => + call[1] === "install" && !call[2]!.includes("@"); + const officialFeed = (gmail: Buffer, overrides: Record = {}) => ({ name: OFFICIAL.name, plugins: [ @@ -59,7 +65,7 @@ const officialFeed = (gmail: Buffer, overrides: Record = {}) => name: "gmail", displayName: "Gmail", version: "0.0.7", - description: "Search, read, draft, and send emails in Gmail.", + description: GMAIL_DESCRIPTION, logo: "https://www.gstatic.com/images/gmail.svg", source: { type: "archive", url: GMAIL_ZIP, sha256: sha256(gmail) }, ...overrides, @@ -143,6 +149,23 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff })), ); } + if (command === "install" && target!.includes("@")) { + // agy's own marketplace install: it records the marketplace as the plugin's source. + if (!fixture.nativeSignedIn) return yield* Effect.fail("unknown marketplace"); + const [name, marketplace] = target!.split("@") as [string, string]; + yield* fs.makeDirectory(pluginPath(name), { recursive: true }); + yield* fs.writeFileString( + path.join(pluginPath(name), "plugin.json"), + encode({ name, version: "0.0.7", description: GMAIL_DESCRIPTION }), + ); + fixture.installed.set(name, { + enabled: true, + version: "0.0.7", + path: pluginPath(name), + source: marketplace, + }); + return ""; + } if (command === "install") { const manifest = yield* fs.readFileString(path.join(target!, "plugin.json")); const script = path.join(target!, "skills", "gmail", "scripts", "gmail"); @@ -271,7 +294,7 @@ describe("AntigravityProviderStore", () => { Effect.gen(function* () { const { store, actions, fixture, stateDir, pluginPath, fs, path } = yield* setup(); yield* store.install("gmail@antigravity-plugins-official"); - const install = fixture.calls.find((call) => call[1] === "install")!; + const install = fixture.calls.find(isArchiveInstall)!; expect(install.slice(0, 2)).toEqual(["plugin", "install"]); expect(path.basename(install[2]!)).toBe("gmail"); expect(yield* fs.exists(install[2]!)).toBe(false); @@ -315,7 +338,7 @@ describe("AntigravityProviderStore", () => { ); const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); expect(error.message).toMatch(/checksum/); - expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); const staging = path.join(stateDir, "antigravity-plugins", "staging"); if (yield* fs.exists(staging)) expect(yield* fs.readDirectory(staging)).toEqual([]); }), @@ -339,7 +362,7 @@ describe("AntigravityProviderStore", () => { }); const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); expect(error.message).toMatch(/archive/); - expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); expect( yield* fs.readDirectory(path.join(stateDir, "antigravity-plugins", "staging")), ).toEqual([]); @@ -359,10 +382,10 @@ describe("AntigravityProviderStore", () => { }); const entry = yield* store.entry("gmail@antigravity-plugins-official"); expect(entry.installed).toBe(false); - expect(entry.disabledReason).toMatch(/another source/); + expect(entry.disabledReason).toMatch(/different plugin named gmail/); expect( (yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip)).message, - ).toMatch(/another source/); + ).toMatch(/different plugin named gmail/); expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); expect( (yield* actions @@ -396,7 +419,7 @@ describe("AntigravityProviderStore", () => { const installedMeanwhile = fixture.installed; const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); expect(error.message).toMatch(/while Scient was preparing/); - expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); expect(installedMeanwhile.get("gmail")?.version).toBe("1.0.0"); expect(yield* fs.exists(pluginPath("gmail"))).toBe(false); expect( @@ -449,6 +472,83 @@ describe("AntigravityProviderStore", () => { ), ); + it.effect("adds through agy's own marketplace install when agy is signed in", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture, stateDir, fs, path } = yield* setup((fixture) => { + fixture.nativeSignedIn = true; + }); + const id = "gmail@antigravity-plugins-official"; + yield* store.install(id); + expect(fixture.calls).toContainEqual(["plugin", "install", id]); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); + expect(fixture.fetched).not.toContain(GMAIL_ZIP); + expect((yield* store.entry(id)).installed).toBe(true); + expect((yield* actions.listPlugins({})).plugins[0]).toMatchObject({ + id, + sourceLabel: "Antigravity Marketplace", + }); + const receipts = path.join(stateDir, "antigravity-plugins", "receipts.json"); + if (yield* fs.exists(receipts)) + expect(yield* fs.readFileString(receipts)).not.toContain('"gmail"'); + }), + ), + ); + + it.effect("recognises a plugin agy installed from its marketplace outside Scient", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture, pluginPath } = yield* setup(); + const id = "gmail@antigravity-plugins-official"; + fixture.installed.set("gmail", { + enabled: true, + version: "0.0.7", + path: pluginPath("gmail"), + source: "antigravity-plugins-official", + }); + const entry = yield* store.entry(id); + expect(entry.installed).toBe(true); + expect(entry.disabledReason).toBeUndefined(); + expect((yield* actions.listPlugins({})).plugins[0]).toMatchObject({ + id, + displayName: "Gmail", + }); + yield* actions.uninstall({ pluginId: id }); + expect(fixture.calls).toContainEqual(["plugin", "uninstall", "gmail"]); + }), + ), + ); + + it.effect("recognises a copy installed before agy recorded origins by its manifest", () => + provide( + Effect.gen(function* () { + const { store, fixture, pluginPath, fs, path } = yield* setup(); + const id = "gmail@antigravity-plugins-official"; + const older = (description: string) => + Effect.gen(function* () { + yield* fs.makeDirectory(pluginPath("gmail"), { recursive: true }); + yield* fs.writeFileString( + path.join(pluginPath("gmail"), "plugin.json"), + encode({ name: "gmail", version: "0.0.5", description }), + ); + fixture.installed.set("gmail", { + enabled: true, + version: "0.0.5", + path: pluginPath("gmail"), + source: null, + }); + }); + yield* older(GMAIL_DESCRIPTION); + expect((yield* store.entry(id)).installed).toBe(true); + // Same name, nothing else in common: someone else's plugin, never claimed. + yield* older("My own mail helper"); + const entry = yield* store.entry(id); + expect(entry.installed).toBe(false); + expect(entry.disabledReason).toMatch(/different plugin named gmail/); + }), + ), + ); + it.effect("treats a malformed installed list as unknown, never as empty", () => provide( Effect.gen(function* () { diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index 332b9bad1b..036ed847aa 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -1,8 +1,8 @@ /** - * The Antigravity Marketplace in Scient: Google's two catalogs, added through `agy plugin install` - * of a checked archive into the OS user's Antigravity plugins (shared with their Antigravity app), - * removed with `agy plugin uninstall`. A small receipt per Add records which catalog entry an - * installed folder came from, since agy's own listing does not. + * The Antigravity Marketplace in Scient: Google's two catalogs, added to the OS user's Antigravity + * plugins (shared with their Antigravity app) by agy's own marketplace install, or, when agy is not + * signed in, by installing the catalog's checked archive. A receipt records an archive Add's origin, + * which agy lists only for its own marketplace installs. */ import type { ExtensionPluginContents, @@ -38,6 +38,7 @@ import { makeAntigravityPluginCatalog, type AntigravityCatalogPlugin, type AntigravityMarketplace, + type AntigravityPluginIdentity, } from "./AntigravityPluginCatalog.ts"; import { ARCHIVE_LIMITS, @@ -156,10 +157,86 @@ const receiptFor = Effect.fn("AntigravityProviderStore.receiptFor")(function* ( return Option.getOrUndefined(identity) === candidate.installation ? candidate : undefined; }); +const MARKETPLACE_NAMES: ReadonlySet = new Set( + ANTIGRAVITY_MARKETPLACES.map((item) => item.name), +); +const InstalledManifest = Schema.Struct({ + name: Schema.optional(Schema.Unknown), + repository: Schema.optional(Schema.Unknown), + author: Schema.optional(Schema.Unknown), + description: Schema.optional(Schema.Unknown), +}); +const decodeInstalledManifest = Schema.decodeUnknownEffect( + Schema.fromJsonString(InstalledManifest), +); +const text = (value: unknown) => + typeof value === "string" && value.trim() ? value.trim() : undefined; +const comparableRepository = (value: string | undefined) => + value + ?.toLowerCase() + .replace(/\.git$/u, "") + .replace(/\/+$/u, ""); + +/** + * Whether a copy installed without a recorded origin is this catalog plugin: same name in its + * plugin.json, and the same repository, author or description the catalog states for it. + */ +const manifestMatches = Effect.fn("AntigravityProviderStore.manifestMatches")(function* ( + folder: string, + name: string, + identity: AntigravityPluginIdentity, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const file = path.join(folder, "plugin.json"); + const info = yield* fs.stat(file); + if (info.type !== "File" || Number(info.size) > ARCHIVE_LIMITS.manifestBytes) return false; + const manifest = yield* decodeInstalledManifest(yield* fs.readFileString(file)); + if (text(manifest.name) !== name) return false; + const author = + typeof manifest.author === "object" && manifest.author !== null && "name" in manifest.author + ? text(manifest.author.name) + : text(manifest.author); + const repository = comparableRepository(text(manifest.repository)); + return ( + (repository !== undefined && repository === comparableRepository(identity.repository)) || + (author !== undefined && author.toLowerCase() === identity.author?.toLowerCase()) || + (text(manifest.description) !== undefined && + text(manifest.description) === identity.description) + ); +}); + +/** + * The marketplace an installed copy came from: agy's own record first, then Scient's receipt for + * an archive Add, then, for a copy installed before agy recorded origins, its manifest. + */ +const installedMarketplace = Effect.fn("AntigravityProviderStore.installedMarketplace")(function* ( + plugin: { + readonly name: string; + readonly path: string; + readonly version?: string | undefined; + readonly source?: string | undefined; + }, + receipts: ReadonlyArray, + catalog: ReadonlyMap | undefined, +) { + if (plugin.source !== undefined && MARKETPLACE_NAMES.has(plugin.source)) + return { marketplace: plugin.source, receipt: undefined }; + const receipt = yield* receiptFor(receipts, plugin); + if (receipt) return { marketplace: receipt.marketplace, receipt }; + const entry = catalog?.get(plugin.name); + if (!entry || (plugin.source !== undefined && plugin.source !== "antigravity")) return undefined; + const matches = yield* manifestMatches(plugin.path, plugin.name, entry.identity).pipe( + Effect.orElseSucceed(() => false), + ); + return matches ? { marketplace: entry.marketplace, receipt: undefined } : undefined; +}); + /** `agy plugin list --json` as provider plugins; any malformed listing fails as a whole. */ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList")(function* ( output: string, receipts: ReadonlyArray, + catalog?: ReadonlyMap | undefined, ) { const path = yield* Path.Path; const listed = yield* decodeListed(output.trim()); @@ -171,23 +248,26 @@ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList names.add(item.name); const version = item.version?.trim() || undefined; const source = item.source?.trim() || undefined; - const receipt = yield* receiptFor(receipts, { - name: item.name, - path: item.path, - version, - source, - }); + const origin = yield* installedMarketplace( + { name: item.name, path: item.path, version, source }, + receipts, + catalog, + ); + const marketplace = origin?.marketplace; + const listedName = + (marketplace ? catalog?.get(item.name)?.displayName : undefined) ?? + origin?.receipt?.displayName?.trim(); plugins.push({ - id: receipt ? entryId(item.name, receipt.marketplace) : `antigravity:${item.name}`, + id: marketplace ? entryId(item.name, marketplace) : `antigravity:${item.name}`, name: item.name, - displayName: receipt?.displayName?.trim() || sharedPluginDisplayName(item.name), + displayName: listedName || sharedPluginDisplayName(item.name), ...(version ? { version } : {}), - ...(receipt ? { marketplace: receipt.marketplace } : {}), + ...(marketplace ? { marketplace } : {}), source: "local", enabled: item.enabled, canUninstall: true, canSetEnabled: true, - sourceLabel: receipt ? "Antigravity Marketplace" : "Antigravity's plugins", + sourceLabel: marketplace ? "Antigravity Marketplace" : "Antigravity's plugins", scope: "user", path: item.path, ...(source ? { nativeSource: source } : {}), @@ -284,7 +364,16 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi function* () { const sequence = yield* nextInventoryReadSequence; const output = yield* options.run(["plugin", "list", "--json"]); - const plugins = yield* parseAntigravityPluginList(output, yield* readReceipts); + // The cached catalog, when it reads, names plugins installed before agy recorded origins. + const known = yield* catalog.read(false).pipe( + Effect.map((read) => new Map(read.plugins.map((plugin) => [plugin.name, plugin]))), + Effect.option, + ); + const plugins = yield* parseAntigravityPluginList( + output, + yield* readReceipts, + Option.getOrUndefined(known), + ); return { plugins, sequence }; }, Effect.provideService(Path.Path, path), @@ -312,7 +401,7 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi : added ? undefined : native - ? `Antigravity already has a plugin named ${plugin.name} from another source. Remove it first to add this one.` + ? `Antigravity already has a different plugin named ${plugin.name}. Remove that one from Installed to add this one.` : plugin.archive === undefined ? "This plugin's download is not on Google's plugin host, so Scient can't add it." : undefined); @@ -432,6 +521,18 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const item = yield* find(id); if (item.entry.disabledReason) return yield* fail(item.entry.disabledReason); if (item.entry.installed) return; + // agy's own marketplace install records the origin and keeps the plugin updated. It needs + // agy's own sign-in; without one, Scient adds the catalog's checked archive instead. + const nativeAdd = yield* options.run(["plugin", "install", id]).pipe(Effect.option); + if (nativeAdd._tag === "Some") { + const listed = (yield* list()).plugins.find((plugin) => plugin.name === item.plugin.name); + if (listed?.id !== id) + return yield* fail("Antigravity did not list the plugin after adding it."); + yield* writeReceipts((receipts) => + receipts.filter((receipt) => receipt.name !== listed.name), + ).pipe(Effect.ignore); + return; + } const archive = item.plugin.archive; if (!archive) return yield* fail("This plugin cannot be added from Scient."); yield* Effect.scoped( diff --git a/apps/web/src/scient/extensions/Extensions.browser.test.tsx b/apps/web/src/scient/extensions/Extensions.browser.test.tsx index 735517c4e9..012b8c2839 100644 --- a/apps/web/src/scient/extensions/Extensions.browser.test.tsx +++ b/apps/web/src/scient/extensions/Extensions.browser.test.tsx @@ -2662,6 +2662,15 @@ describe("Antigravity Marketplace", () => { }), ); + // A different plugin of the same name: the reason and where to act, never a dead Add. + const clash = "Antigravity already has a different plugin named gmail."; + agents = await show({ plugins: [] }, { ...gmail, disabledReason: clash }); + await vi.waitFor(() => expect(agents.textContent).toContain(clash)); + expect(buttonIn(agents, "Add to Antigravity")).toBeNull(); + expect(linkIn(agents, "Open Installed")?.getAttribute("href")).toBe( + "/settings/extensions/installed", + ); + agents = await show({ plugins: [] }, { ...gmail, installationStateKnown: false }); await vi.waitFor(() => expect(agents.textContent).toContain("Checking…")); diff --git a/apps/web/src/scient/extensions/ServiceAgents.tsx b/apps/web/src/scient/extensions/ServiceAgents.tsx index 5dc84d0d4a..036c7122e9 100644 --- a/apps/web/src/scient/extensions/ServiceAgents.tsx +++ b/apps/web/src/scient/extensions/ServiceAgents.tsx @@ -211,7 +211,16 @@ function AntigravityServiceRow({ Off in Antigravity ) - ) : state === "added" ? null : ( + ) : state === "added" ? null : entry.data?.disabledReason ? ( + // The line above says why it can't be added; offer where to act, never a dead button. + + ) : ( Date: Sun, 22 Nov 2026 00:38:37 +0200 Subject: [PATCH 27/36] fix(web): say every agent reaches Google services through its own sign-in The Gmail, Calendar and Drive pages said agents reach them through a ChatGPT or Claude account; Antigravity reaches them through its own plugin and Google sign-in. Also translates "Open Installed". Co-Authored-By: Claude Opus 5.5 --- apps/web/src/i18n/translations/de.json | 9 +++++---- apps/web/src/i18n/translations/en.json | 9 +++++---- apps/web/src/i18n/translations/es.json | 9 +++++---- apps/web/src/i18n/translations/fr.json | 9 +++++---- apps/web/src/i18n/translations/ja.json | 9 +++++---- apps/web/src/i18n/translations/ko.json | 9 +++++---- apps/web/src/i18n/translations/pt-BR.json | 9 +++++---- apps/web/src/i18n/translations/ru.json | 9 +++++---- apps/web/src/i18n/translations/sv.json | 9 +++++---- apps/web/src/i18n/translations/zh.json | 9 +++++---- apps/web/src/scient/extensions/accountServices.ts | 13 ++++++------- 11 files changed, 56 insertions(+), 47 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 27122f39d4..92b5844fc2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -15315,6 +15315,7 @@ "1adafa7bf3950e49": "Über sein ChatGPT-Konto", "7d53eaac80454d20": "Über sein Claude-Konto", "a0a941e840d09146": "In Antigravity ausgeschaltet", + "0c984e449a44787a": "Installiert öffnen", "9bc27aecd2f69962": [ "Keiner deiner Agenten erreicht ", { @@ -15330,12 +15331,12 @@ "bc956fe5a8eb969d": "Keine Agenten gemeldet", "3a47c1420ef44a91": "Alle Agenten", "2c2f71bdc741589f": "E-Mails suchen, lesen und entwerfen", - "e208d5efd58ad5a5": "Jeder Agent erreicht Gmail über sein eigenes ChatGPT- oder Claude-Konto. Scient verwahrt deine Google-Anmeldung nie.", + "fd8732228de93a88": "Jeder Agent erreicht Gmail über seine eigene Anmeldung. Scient verwahrt deine Google-Anmeldung nie.", "8fb8b9918a38dc3d": "Verfügbarkeit prüfen und Termine verwalten", - "a81e3fea7da0b54b": "Jeder Agent erreicht Google Calendar über sein eigenes ChatGPT- oder Claude-Konto. Scient verwahrt deine Google-Anmeldung nie.", + "183dc5ff8568d278": "Jeder Agent erreicht Google Calendar über seine eigene Anmeldung. Scient verwahrt deine Google-Anmeldung nie.", "e7a7a6f8abb0a863": "Docs, Sheets und Dateien finden und lesen", - "af9c903a50bfafa0": "Jeder Agent erreicht Google Drive über sein eigenes ChatGPT- oder Claude-Konto. Scient verwahrt deine Google-Anmeldung nie.", - "995467efb83d481c": "Jeder Agent erreicht {name} über sein eigenes ChatGPT- oder Claude-Konto. Scient verwahrt diese Anmeldung nie.", + "25cbed76cf411a5f": "Jeder Agent erreicht Google Drive über seine eigene Anmeldung. Scient verwahrt deine Google-Anmeldung nie.", + "6aac5f20b8c69f42": "Jeder Agent erreicht {name} über seine eigene Anmeldung. Scient verwahrt diese Anmeldung nie.", "32c56b99e1f15a8f": "Codex und Scient Agent erreichen {name} über dein ChatGPT-Konto. Scient verwahrt diese Anmeldung nie.", "1d6f39fd50c58413": "Sein Konto wird geprüft…", "874d3705b30da727": "Nicht angemeldet", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c1d7ee7abb..f88ea4a916 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -15326,6 +15326,7 @@ "1adafa7bf3950e49": "Through its ChatGPT account", "7d53eaac80454d20": "Through its Claude account", "a0a941e840d09146": "Off in Antigravity", + "0c984e449a44787a": "Open Installed", "9bc27aecd2f69962": [ "None of your agents reaches ", { @@ -15341,12 +15342,12 @@ "bc956fe5a8eb969d": "No agents reported", "3a47c1420ef44a91": "All agents", "2c2f71bdc741589f": "Search, read and draft email", - "e208d5efd58ad5a5": "Each agent reaches Gmail through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", + "fd8732228de93a88": "Each agent reaches Gmail through its own sign-in. Scient never holds your Google sign-in.", "8fb8b9918a38dc3d": "Check availability and manage events", - "a81e3fea7da0b54b": "Each agent reaches Google Calendar through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", + "183dc5ff8568d278": "Each agent reaches Google Calendar through its own sign-in. Scient never holds your Google sign-in.", "e7a7a6f8abb0a863": "Find and read Docs, Sheets and files", - "af9c903a50bfafa0": "Each agent reaches Google Drive through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", - "995467efb83d481c": "Each agent reaches {name} through its own ChatGPT or Claude account. Scient never holds that sign-in.", + "25cbed76cf411a5f": "Each agent reaches Google Drive through its own sign-in. Scient never holds your Google sign-in.", + "6aac5f20b8c69f42": "Each agent reaches {name} through its own sign-in. Scient never holds that sign-in.", "32c56b99e1f15a8f": "Codex and Scient Agent reach {name} through your ChatGPT account. Scient never holds that sign-in.", "1d6f39fd50c58413": "Checking its account…", "874d3705b30da727": "Not signed in", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 8832828fb5..f522bd5726 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -15308,6 +15308,7 @@ "1adafa7bf3950e49": "A través de su cuenta de ChatGPT", "7d53eaac80454d20": "A través de su cuenta de Claude", "a0a941e840d09146": "Desactivado en Antigravity", + "0c984e449a44787a": "Abrir Instalados", "9bc27aecd2f69962": [ "Ninguno de tus agentes accede a ", { @@ -15323,12 +15324,12 @@ "bc956fe5a8eb969d": "No se informó de ningún agente", "3a47c1420ef44a91": "Todos los agentes", "2c2f71bdc741589f": "Buscar, leer y redactar correos", - "e208d5efd58ad5a5": "Cada agente accede a Gmail a través de su propia cuenta de ChatGPT o Claude. Scient nunca guarda tu inicio de sesión de Google.", + "fd8732228de93a88": "Cada agente accede a Gmail con su propio inicio de sesión. Scient nunca guarda tu inicio de sesión de Google.", "8fb8b9918a38dc3d": "Consultar la disponibilidad y gestionar eventos", - "a81e3fea7da0b54b": "Cada agente accede a Google Calendar a través de su propia cuenta de ChatGPT o Claude. Scient nunca guarda tu inicio de sesión de Google.", + "183dc5ff8568d278": "Cada agente accede a Google Calendar con su propio inicio de sesión. Scient nunca guarda tu inicio de sesión de Google.", "e7a7a6f8abb0a863": "Buscar y leer Docs, Sheets y archivos", - "af9c903a50bfafa0": "Cada agente accede a Google Drive a través de su propia cuenta de ChatGPT o Claude. Scient nunca guarda tu inicio de sesión de Google.", - "995467efb83d481c": "Cada agente accede a {name} a través de su propia cuenta de ChatGPT o Claude. Scient nunca guarda ese inicio de sesión.", + "25cbed76cf411a5f": "Cada agente accede a Google Drive con su propio inicio de sesión. Scient nunca guarda tu inicio de sesión de Google.", + "6aac5f20b8c69f42": "Cada agente accede a {name} con su propio inicio de sesión. Scient nunca guarda ese inicio de sesión.", "32c56b99e1f15a8f": "Codex y Scient Agent acceden a {name} a través de tu cuenta de ChatGPT. Scient nunca guarda ese inicio de sesión.", "1d6f39fd50c58413": "Comprobando su cuenta…", "874d3705b30da727": "Sin sesión iniciada", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index cb59143c22..295bea0e40 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -15313,6 +15313,7 @@ "1adafa7bf3950e49": "Via son compte ChatGPT", "7d53eaac80454d20": "Via son compte Claude", "a0a941e840d09146": "Désactivé dans Antigravity", + "0c984e449a44787a": "Ouvrir Installés", "9bc27aecd2f69962": [ "Aucun de vos agents n’accède à ", { @@ -15328,12 +15329,12 @@ "bc956fe5a8eb969d": "Aucun agent signalé", "3a47c1420ef44a91": "Tous les agents", "2c2f71bdc741589f": "Rechercher, lire et rédiger des e-mails", - "e208d5efd58ad5a5": "Chaque agent accède à Gmail via son propre compte ChatGPT ou Claude. Scient ne détient jamais votre connexion Google.", + "fd8732228de93a88": "Chaque agent accède à Gmail avec sa propre connexion. Scient ne conserve jamais votre connexion Google.", "8fb8b9918a38dc3d": "Vérifier les disponibilités et gérer les événements", - "a81e3fea7da0b54b": "Chaque agent accède à Google Agenda via son propre compte ChatGPT ou Claude. Scient ne détient jamais votre connexion Google.", + "183dc5ff8568d278": "Chaque agent accède à Google Calendar avec sa propre connexion. Scient ne conserve jamais votre connexion Google.", "e7a7a6f8abb0a863": "Trouver et lire des Docs, Sheets et fichiers", - "af9c903a50bfafa0": "Chaque agent accède à Google Drive via son propre compte ChatGPT ou Claude. Scient ne détient jamais votre connexion Google.", - "995467efb83d481c": "Chaque agent accède à {name} via son propre compte ChatGPT ou Claude. Scient ne détient jamais cette connexion.", + "25cbed76cf411a5f": "Chaque agent accède à Google Drive avec sa propre connexion. Scient ne conserve jamais votre connexion Google.", + "6aac5f20b8c69f42": "Chaque agent accède à {name} avec sa propre connexion. Scient ne conserve jamais cette connexion.", "32c56b99e1f15a8f": "Codex et Scient Agent accèdent à {name} via votre compte ChatGPT. Scient ne détient jamais cette connexion.", "1d6f39fd50c58413": "Vérification de son compte…", "874d3705b30da727": "Non connecté", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 138959080c..bc0872a32b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -15241,6 +15241,7 @@ "1adafa7bf3950e49": "ChatGPT アカウント経由", "7d53eaac80454d20": "Claude アカウント経由", "a0a941e840d09146": "Antigravity でオフ", + "0c984e449a44787a": "インストール済みを開く", "9bc27aecd2f69962": [ "アカウント経由で ", { @@ -15256,12 +15257,12 @@ "bc956fe5a8eb969d": "報告されたエージェントはありません", "3a47c1420ef44a91": "すべてのエージェント", "2c2f71bdc741589f": "メールの検索、閲覧、下書き", - "e208d5efd58ad5a5": "各エージェントは、それぞれの ChatGPT または Claude アカウントを通じて Gmail にアクセスします。Scient が Google のサインイン情報を保持することはありません。", + "fd8732228de93a88": "各エージェントは自身のサインインで Gmail にアクセスします。Scient が Google のサインイン情報を保持することはありません。", "8fb8b9918a38dc3d": "空き状況の確認と予定の管理", - "a81e3fea7da0b54b": "各エージェントは、それぞれの ChatGPT または Claude アカウントを通じて Google カレンダーにアクセスします。Scient が Google のサインイン情報を保持することはありません。", + "183dc5ff8568d278": "各エージェントは自身のサインインで Google Calendar にアクセスします。Scient が Google のサインイン情報を保持することはありません。", "e7a7a6f8abb0a863": "Docs、Sheets、ファイルの検索と閲覧", - "af9c903a50bfafa0": "各エージェントは、それぞれの ChatGPT または Claude アカウントを通じて Google ドライブにアクセスします。Scient が Google のサインイン情報を保持することはありません。", - "995467efb83d481c": "各エージェントは、それぞれの ChatGPT または Claude アカウントを通じて {name} にアクセスします。Scient がそのサインイン情報を保持することはありません。", + "25cbed76cf411a5f": "各エージェントは自身のサインインで Google Drive にアクセスします。Scient が Google のサインイン情報を保持することはありません。", + "6aac5f20b8c69f42": "各エージェントは自身のサインインで {name} にアクセスします。Scient がそのサインイン情報を保持することはありません。", "32c56b99e1f15a8f": "Codex と Scient Agent は、ChatGPT アカウントを通じて {name} にアクセスします。Scient がそのサインイン情報を保持することはありません。", "1d6f39fd50c58413": "アカウントを確認しています…", "874d3705b30da727": "サインインしていません", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 26328028e7..487e32362b 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -15246,6 +15246,7 @@ "1adafa7bf3950e49": "ChatGPT 계정을 통해", "7d53eaac80454d20": "Claude 계정을 통해", "a0a941e840d09146": "Antigravity에서 꺼짐", + "0c984e449a44787a": "설치됨 열기", "9bc27aecd2f69962": [ "어떤 에이전트도 자체 계정을 통해 ", { @@ -15261,12 +15262,12 @@ "bc956fe5a8eb969d": "보고된 에이전트 없음", "3a47c1420ef44a91": "모든 에이전트", "2c2f71bdc741589f": "이메일 검색, 읽기 및 초안 작성", - "e208d5efd58ad5a5": "각 에이전트는 자체 ChatGPT 또는 Claude 계정을 통해 Gmail에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", + "fd8732228de93a88": "각 에이전트는 자체 로그인으로 Gmail에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", "8fb8b9918a38dc3d": "일정 확인 및 이벤트 관리", - "a81e3fea7da0b54b": "각 에이전트는 자체 ChatGPT 또는 Claude 계정을 통해 Google Calendar에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", + "183dc5ff8568d278": "각 에이전트는 자체 로그인으로 Google Calendar에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", "e7a7a6f8abb0a863": "Docs, Sheets 및 파일 찾기와 읽기", - "af9c903a50bfafa0": "각 에이전트는 자체 ChatGPT 또는 Claude 계정을 통해 Google Drive에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", - "995467efb83d481c": "각 에이전트는 자체 ChatGPT 또는 Claude 계정을 통해 {name}에 접근합니다. Scient는 해당 로그인 정보를 보관하지 않습니다.", + "25cbed76cf411a5f": "각 에이전트는 자체 로그인으로 Google Drive에 접근합니다. Scient는 Google 로그인 정보를 보관하지 않습니다.", + "6aac5f20b8c69f42": "각 에이전트는 자체 로그인으로 {name}에 접근합니다. Scient는 그 로그인 정보를 보관하지 않습니다.", "32c56b99e1f15a8f": "Codex와 Scient Agent는 ChatGPT 계정을 통해 {name}에 접근합니다. Scient는 해당 로그인 정보를 보관하지 않습니다.", "1d6f39fd50c58413": "계정을 확인하는 중…", "874d3705b30da727": "로그인하지 않음", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 54bccf8fee..8ac63feb84 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -15312,6 +15312,7 @@ "1adafa7bf3950e49": "Pela conta do ChatGPT dele", "7d53eaac80454d20": "Pela conta do Claude dele", "a0a941e840d09146": "Desativado no Antigravity", + "0c984e449a44787a": "Abrir Instalados", "9bc27aecd2f69962": [ "Nenhum dos seus agentes alcança ", { @@ -15327,12 +15328,12 @@ "bc956fe5a8eb969d": "Nenhum agente informado", "3a47c1420ef44a91": "Todos os agentes", "2c2f71bdc741589f": "Pesquisar, ler e redigir e-mails", - "e208d5efd58ad5a5": "Cada agente acessa o Gmail pela própria conta do ChatGPT ou do Claude. O Scient nunca guarda seu login do Google.", + "fd8732228de93a88": "Cada agente acessa o Gmail com o próprio login. O Scient nunca guarda seu login do Google.", "8fb8b9918a38dc3d": "Verificar disponibilidade e gerenciar eventos", - "a81e3fea7da0b54b": "Cada agente acessa o Google Agenda pela própria conta do ChatGPT ou do Claude. O Scient nunca guarda seu login do Google.", + "183dc5ff8568d278": "Cada agente acessa o Google Calendar com o próprio login. O Scient nunca guarda seu login do Google.", "e7a7a6f8abb0a863": "Encontrar e ler Docs, Sheets e arquivos", - "af9c903a50bfafa0": "Cada agente acessa o Google Drive pela própria conta do ChatGPT ou do Claude. O Scient nunca guarda seu login do Google.", - "995467efb83d481c": "Cada agente acessa {name} pela própria conta do ChatGPT ou do Claude. O Scient nunca guarda esse login.", + "25cbed76cf411a5f": "Cada agente acessa o Google Drive com o próprio login. O Scient nunca guarda seu login do Google.", + "6aac5f20b8c69f42": "Cada agente acessa {name} com o próprio login. O Scient nunca guarda esse login.", "32c56b99e1f15a8f": "O Codex e o Scient Agent acessam {name} pela sua conta do ChatGPT. O Scient nunca guarda esse login.", "1d6f39fd50c58413": "Verificando a conta…", "874d3705b30da727": "Não conectado", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 26d472fc62..72caf60201 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -15313,6 +15313,7 @@ "1adafa7bf3950e49": "Через свой аккаунт ChatGPT", "7d53eaac80454d20": "Через свой аккаунт Claude", "a0a941e840d09146": "Выключено в Antigravity", + "0c984e449a44787a": "Открыть «Установленные»", "9bc27aecd2f69962": [ "Ни один из ваших агентов не имеет доступа к ", { @@ -15328,12 +15329,12 @@ "bc956fe5a8eb969d": "Агенты не сообщены", "3a47c1420ef44a91": "Все агенты", "2c2f71bdc741589f": "Поиск, чтение и черновики писем", - "e208d5efd58ad5a5": "Каждый агент получает доступ к Gmail через собственный аккаунт ChatGPT или Claude. Scient никогда не хранит ваш вход в Google.", + "fd8732228de93a88": "Каждый агент подключается к Gmail через собственный вход. Scient никогда не хранит ваш вход в Google.", "8fb8b9918a38dc3d": "Проверка занятости и управление событиями", - "a81e3fea7da0b54b": "Каждый агент получает доступ к Google Calendar через собственный аккаунт ChatGPT или Claude. Scient никогда не хранит ваш вход в Google.", + "183dc5ff8568d278": "Каждый агент подключается к Google Calendar через собственный вход. Scient никогда не хранит ваш вход в Google.", "e7a7a6f8abb0a863": "Поиск и чтение Docs, Sheets и файлов", - "af9c903a50bfafa0": "Каждый агент получает доступ к Google Drive через собственный аккаунт ChatGPT или Claude. Scient никогда не хранит ваш вход в Google.", - "995467efb83d481c": "Каждый агент получает доступ к {name} через собственный аккаунт ChatGPT или Claude. Scient никогда не хранит эти данные входа.", + "25cbed76cf411a5f": "Каждый агент подключается к Google Drive через собственный вход. Scient никогда не хранит ваш вход в Google.", + "6aac5f20b8c69f42": "Каждый агент подключается к {name} через собственный вход. Scient никогда не хранит этот вход.", "32c56b99e1f15a8f": "Codex и Scient Agent получают доступ к {name} через ваш аккаунт ChatGPT. Scient никогда не хранит эти данные входа.", "1d6f39fd50c58413": "Проверка аккаунта…", "874d3705b30da727": "Вход не выполнен", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 09c9df1cd2..df604df719 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -15322,6 +15322,7 @@ "1adafa7bf3950e49": "Via sitt ChatGPT-konto", "7d53eaac80454d20": "Via sitt Claude-konto", "a0a941e840d09146": "Avstängd i Antigravity", + "0c984e449a44787a": "Öppna Installerade", "9bc27aecd2f69962": [ "Ingen av dina agenter når ", { @@ -15337,12 +15338,12 @@ "bc956fe5a8eb969d": "Inga agenter rapporterades", "3a47c1420ef44a91": "Alla agenter", "2c2f71bdc741589f": "Sök, läs och skriv utkast till e-post", - "e208d5efd58ad5a5": "Varje agent når Gmail via sitt eget ChatGPT- eller Claude-konto. Scient har aldrig din Google-inloggning.", + "fd8732228de93a88": "Varje agent når Gmail med sin egen inloggning. Scient sparar aldrig din Google-inloggning.", "8fb8b9918a38dc3d": "Kontrollera tillgänglighet och hantera händelser", - "a81e3fea7da0b54b": "Varje agent når Google Kalender via sitt eget ChatGPT- eller Claude-konto. Scient har aldrig din Google-inloggning.", + "183dc5ff8568d278": "Varje agent når Google Calendar med sin egen inloggning. Scient sparar aldrig din Google-inloggning.", "e7a7a6f8abb0a863": "Hitta och läs Docs, Sheets och filer", - "af9c903a50bfafa0": "Varje agent når Google Drive via sitt eget ChatGPT- eller Claude-konto. Scient har aldrig din Google-inloggning.", - "995467efb83d481c": "Varje agent når {name} via sitt eget ChatGPT- eller Claude-konto. Scient har aldrig den inloggningen.", + "25cbed76cf411a5f": "Varje agent når Google Drive med sin egen inloggning. Scient sparar aldrig din Google-inloggning.", + "6aac5f20b8c69f42": "Varje agent når {name} med sin egen inloggning. Scient sparar aldrig den inloggningen.", "32c56b99e1f15a8f": "Codex och Scient Agent når {name} via ditt ChatGPT-konto. Scient har aldrig den inloggningen.", "1d6f39fd50c58413": "Kontrollerar kontot…", "874d3705b30da727": "Inte inloggad", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 67653d4398..e3903e9c83 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -15351,6 +15351,7 @@ "1adafa7bf3950e49": "通过其 ChatGPT 账户", "7d53eaac80454d20": "通过其 Claude 账户", "a0a941e840d09146": "已在 Antigravity 中关闭", + "0c984e449a44787a": "打开“已安装”", "9bc27aecd2f69962": [ "你的智能体都无法通过其账户访问 ", { @@ -15366,12 +15367,12 @@ "bc956fe5a8eb969d": "未报告智能体", "3a47c1420ef44a91": "所有智能体", "2c2f71bdc741589f": "搜索、阅读和起草邮件", - "e208d5efd58ad5a5": "每个智能体通过其自己的 ChatGPT 或 Claude 账户访问 Gmail。Scient 永远不会持有你的 Google 登录信息。", + "fd8732228de93a88": "每个智能体都通过自己的登录访问 Gmail。Scient 从不保存你的 Google 登录信息。", "8fb8b9918a38dc3d": "查看空闲时间并管理日程", - "a81e3fea7da0b54b": "每个智能体通过其自己的 ChatGPT 或 Claude 账户访问 Google Calendar。Scient 永远不会持有你的 Google 登录信息。", + "183dc5ff8568d278": "每个智能体都通过自己的登录访问 Google Calendar。Scient 从不保存你的 Google 登录信息。", "e7a7a6f8abb0a863": "查找和阅读 Docs、Sheets 及文件", - "af9c903a50bfafa0": "每个智能体通过其自己的 ChatGPT 或 Claude 账户访问 Google Drive。Scient 永远不会持有你的 Google 登录信息。", - "995467efb83d481c": "每个智能体通过其自己的 ChatGPT 或 Claude 账户访问 {name}。Scient 永远不会持有该登录信息。", + "25cbed76cf411a5f": "每个智能体都通过自己的登录访问 Google Drive。Scient 从不保存你的 Google 登录信息。", + "6aac5f20b8c69f42": "每个智能体都通过自己的登录访问 {name}。Scient 从不保存该登录信息。", "32c56b99e1f15a8f": "Codex 和 Scient Agent 通过你的 ChatGPT 账户访问 {name}。Scient 永远不会持有该登录信息。", "1d6f39fd50c58413": "正在检查其账户…", "874d3705b30da727": "未登录", diff --git a/apps/web/src/scient/extensions/accountServices.ts b/apps/web/src/scient/extensions/accountServices.ts index c495fea25a..5ecbb3c79a 100644 --- a/apps/web/src/scient/extensions/accountServices.ts +++ b/apps/web/src/scient/extensions/accountServices.ts @@ -86,7 +86,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ name: "Gmail", tagline: msg("Search, read and draft email"), description: msg( - "Each agent reaches Gmail through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", + "Each agent reaches Gmail through its own sign-in. Scient never holds your Google sign-in.", ), categories: ["most-used", "communication"], websiteUrl: "https://mail.google.com", @@ -99,7 +99,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ name: "Google Calendar", tagline: msg("Check availability and manage events"), description: msg( - "Each agent reaches Google Calendar through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", + "Each agent reaches Google Calendar through its own sign-in. Scient never holds your Google sign-in.", ), categories: ["most-used", "communication"], websiteUrl: "https://calendar.google.com", @@ -112,7 +112,7 @@ export const ACCOUNT_SERVICES: ReadonlyArray = [ name: "Google Drive", tagline: msg("Find and read Docs, Sheets and files"), description: msg( - "Each agent reaches Google Drive through its own ChatGPT or Claude account. Scient never holds your Google sign-in.", + "Each agent reaches Google Drive through its own sign-in. Scient never holds your Google sign-in.", ), categories: ["most-used", "files"], websiteUrl: "https://drive.google.com", @@ -193,10 +193,9 @@ export function accountServiceForApp(app: { name: app.name, tagline: app.description?.split("\n")[0]?.slice(0, 80) ?? "", description: claude - ? msg( - "Each agent reaches {name} through its own ChatGPT or Claude account. Scient never holds that sign-in.", - { name: app.name }, - ) + ? msg("Each agent reaches {name} through its own sign-in. Scient never holds that sign-in.", { + name: app.name, + }) : msg( "Codex and Scient Agent reach {name} through your ChatGPT account. Scient never holds that sign-in.", { name: app.name }, From 41390350d41759e6c3e0538822f63327b97cbe32 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 00:52:09 +0200 Subject: [PATCH 28/36] fix(antigravity): close the re-check's install and sign-in gaps - A tool update no longer flushes the reply or thought stream, so a status between two reply chunks can't release half a sign-in link. - Add reads agy's raw list after the named install whatever it reported, falls back only when the name is absent, and refuses another source's copy. The archive route's last read before installing is agy's raw list, and a receipt is written only for the copy whose plugin.json equals the staged one. - Writes to one plugin folder share one permit across instances. - A copy recognised only by its manifest shows as added but keeps its own id, so Marketplace Remove never acts on it; service rows follow the store's installed state. Co-Authored-By: Claude Opus 5.5 --- .../scient/antigravity/pluginSignIn.test.ts | 15 ++ .../src/scient/antigravity/pluginSignIn.ts | 6 +- .../AntigravityProviderStore.test.ts | 58 ++++++- .../extensions/AntigravityProviderStore.ts | 146 +++++++++++------- .../src/scient/extensions/ServiceAgents.tsx | 7 +- 5 files changed, 174 insertions(+), 58 deletions(-) diff --git a/apps/server/src/scient/antigravity/pluginSignIn.test.ts b/apps/server/src/scient/antigravity/pluginSignIn.test.ts index 7272078eef..ea83099004 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.test.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.test.ts @@ -364,6 +364,21 @@ describe("makeAntigravityPluginSignIns", () => { expect(textOf(projected)).toBe(`Open ${LINK_REMOVED} please`); }); + // regression: a tool status between two reply chunks used to flush the reply's held text. + it("holds a split page in the reply across another tool's updates", () => { + const { signIns, generation, observe } = setup(); + const reply = `Open ${URL_OK} please`; + const projected = [ + ...observe(textChunk(reply.slice(0, 120))).notifications, + ...observe(toolUpdate("call-9", { status: "in_progress", kind: "read" })).notifications, + ...observe(toolUpdate("call-9", { status: "completed", kind: "read" })).notifications, + ...observe(textChunk(reply.slice(120))).notifications, + ...signIns.flush(generation), + ]; + expect(JSON.stringify(projected)).not.toContain(STATE); + expect(textOf(projected)).toBe(`Open ${LINK_REMOVED} please`); + }); + it("reports the plugin's next successful call as signed in", () => { const { signIns, observe, admit } = setup(); admit(observe(challengeUpdate()).candidate); diff --git a/apps/server/src/scient/antigravity/pluginSignIn.ts b/apps/server/src/scient/antigravity/pluginSignIn.ts index e8b0a5cf73..41fab2c6e3 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.ts @@ -549,12 +549,12 @@ export function makeAntigravityPluginSignIns( if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { return { notifications: [notification], candidate: undefined }; } - // A tool call ends the reply streams; its own output stream ends with the call. + // A tool's output stream ends with its call. Reply and thought streams keep their held + // text across tool updates, so a status in between never releases half a sign-in link. const terminal = isTerminal(update.status); const flushed = flushStreams( sessionId, - (channel) => - !channel.startsWith("tool:") || (terminal && channel === `tool:${update.toolCallId}`), + (channel) => terminal && channel === `tool:${update.toolCallId}`, ); const { key, tool } = trackTool(sessionId, update.toolCallId); if (update.kind !== undefined) tool.kind = update.kind; diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index e571570583..75f3536837 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -52,6 +52,10 @@ interface Fixture { unavailable?: string; /** Whether agy itself is signed in, which its own marketplace install needs. */ nativeSignedIn?: boolean; + /** Runs right after a directory install, as another program might. */ + afterArchiveInstall?: () => Effect.Effect; + /** The named install times out even though agy installed the plugin. */ + namedTimesOut?: boolean; } const GMAIL_DESCRIPTION = "Search, read, draft, and send emails in Gmail."; @@ -153,6 +157,8 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff // agy's own marketplace install: it records the marketplace as the plugin's source. if (!fixture.nativeSignedIn) return yield* Effect.fail("unknown marketplace"); const [name, marketplace] = target!.split("@") as [string, string]; + // Like agy: a folder another source holds is refused, never replaced. + if (fixture.installed.has(name)) return yield* Effect.fail("another plugin is installed"); yield* fs.makeDirectory(pluginPath(name), { recursive: true }); yield* fs.writeFileString( path.join(pluginPath(name), "plugin.json"), @@ -164,6 +170,7 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff path: pluginPath(name), source: marketplace, }); + if (fixture.namedTimesOut) return yield* Effect.fail("timed out"); return ""; } if (command === "install") { @@ -181,6 +188,7 @@ const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buff version: parsed.version, path: pluginPath(parsed.name), }); + if (fixture.afterArchiveInstall) yield* fixture.afterArchiveInstall(); return ""; } if (command === "uninstall") { @@ -522,7 +530,7 @@ describe("AntigravityProviderStore", () => { it.effect("recognises a copy installed before agy recorded origins by its manifest", () => provide( Effect.gen(function* () { - const { store, fixture, pluginPath, fs, path } = yield* setup(); + const { store, actions, fixture, pluginPath, fs, path } = yield* setup(); const id = "gmail@antigravity-plugins-official"; const older = (description: string) => Effect.gen(function* () { @@ -540,6 +548,15 @@ describe("AntigravityProviderStore", () => { }); yield* older(GMAIL_DESCRIPTION); expect((yield* store.entry(id)).installed).toBe(true); + // Shown as added, but it keeps its own identity: Marketplace Remove never acts on it. + expect((yield* actions.listPlugins({})).plugins[0]).toMatchObject({ + id: "antigravity:gmail", + displayName: "Gmail", + }); + expect((yield* actions.uninstall({ pluginId: id }).pipe(Effect.flip)).message).toMatch( + /no longer installed/, + ); + expect(fixture.calls.some((call) => call[1] === "uninstall")).toBe(false); // Same name, nothing else in common: someone else's plugin, never claimed. yield* older("My own mail helper"); const entry = yield* store.entry(id); @@ -549,6 +566,45 @@ describe("AntigravityProviderStore", () => { ), ); + it.effect("trusts agy's list after a named install, whatever the command reported", () => + provide( + Effect.gen(function* () { + const { store, fixture } = yield* setup((fixture) => { + fixture.nativeSignedIn = true; + fixture.namedTimesOut = true; + }); + const id = "gmail@antigravity-plugins-official"; + // agy installed it before the command failed: that is an Add, not a reason to fall back. + yield* store.install(id); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); + expect((yield* store.entry(id)).installed).toBe(true); + }), + ), + ); + + it.effect("records no receipt for a copy swapped in right after the archive install", () => + provide( + Effect.gen(function* () { + const { store, actions, stateDir, pluginPath, fs, path } = yield* setup((fixture) => { + fixture.afterArchiveInstall = () => + fs + .writeFileString( + path.join(pluginPath("gmail"), "plugin.json"), + encode({ name: "gmail", version: "0.0.7", description: "someone else's" }), + ) + .pipe(Effect.orDie); + }); + const id = "gmail@antigravity-plugins-official"; + const error = yield* store.install(id).pipe(Effect.flip); + expect(error.message).toMatch(/changed while Scient added it/); + const receipts = path.join(stateDir, "antigravity-plugins", "receipts.json"); + if (yield* fs.exists(receipts)) + expect(yield* fs.readFileString(receipts)).not.toContain('"gmail"'); + expect((yield* actions.listPlugins({})).plugins[0]!.id).toBe("antigravity:gmail"); + }), + ), + ); + it.effect("treats a malformed installed list as unknown, never as empty", () => provide( Effect.gen(function* () { diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index 036ed847aa..af942cf3fe 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -95,6 +95,8 @@ const encodeReceipts = Schema.encodeEffect(ReceiptFile); export type AntigravityInstalledPlugin = ServerProviderPlugin & { readonly path: string; readonly nativeSource?: string | undefined; + /** The catalog this copy matches, recorded (agy, receipt) or only by its manifest. */ + readonly catalogMarketplace?: string | undefined; readonly skills: ReadonlyArray; readonly mcpServers: ReadonlyArray; }; @@ -208,7 +210,8 @@ const manifestMatches = Effect.fn("AntigravityProviderStore.manifestMatches")(fu /** * The marketplace an installed copy came from: agy's own record first, then Scient's receipt for - * an archive Add, then, for a copy installed before agy recorded origins, its manifest. + * an archive Add (both `recorded`), then, for a copy installed before agy recorded origins, its + * manifest. A manifest match only shows the copy as added; it never acts as the catalog entry. */ const installedMarketplace = Effect.fn("AntigravityProviderStore.installedMarketplace")(function* ( plugin: { @@ -221,15 +224,17 @@ const installedMarketplace = Effect.fn("AntigravityProviderStore.installedMarket catalog: ReadonlyMap | undefined, ) { if (plugin.source !== undefined && MARKETPLACE_NAMES.has(plugin.source)) - return { marketplace: plugin.source, receipt: undefined }; + return { marketplace: plugin.source, recorded: true, receipt: undefined }; const receipt = yield* receiptFor(receipts, plugin); - if (receipt) return { marketplace: receipt.marketplace, receipt }; + if (receipt) return { marketplace: receipt.marketplace, recorded: true, receipt }; const entry = catalog?.get(plugin.name); if (!entry || (plugin.source !== undefined && plugin.source !== "antigravity")) return undefined; const matches = yield* manifestMatches(plugin.path, plugin.name, entry.identity).pipe( Effect.orElseSucceed(() => false), ); - return matches ? { marketplace: entry.marketplace, receipt: undefined } : undefined; + return matches + ? { marketplace: entry.marketplace, recorded: false, receipt: undefined } + : undefined; }); /** `agy plugin list --json` as provider plugins; any malformed listing fails as a whole. */ @@ -253,9 +258,9 @@ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList receipts, catalog, ); - const marketplace = origin?.marketplace; + const marketplace = origin?.recorded ? origin.marketplace : undefined; const listedName = - (marketplace ? catalog?.get(item.name)?.displayName : undefined) ?? + (origin ? catalog?.get(item.name)?.displayName : undefined) ?? origin?.receipt?.displayName?.trim(); plugins.push({ id: marketplace ? entryId(item.name, marketplace) : `antigravity:${item.name}`, @@ -271,6 +276,7 @@ const parseAntigravityPluginList = Effect.fn("AntigravityProviderStore.parseList scope: "user", path: item.path, ...(source ? { nativeSource: source } : {}), + ...(origin ? { catalogMarketplace: origin.marketplace } : {}), skills: item.skills ?? [], mcpServers: item.mcpServers ?? [], }); @@ -301,6 +307,8 @@ function declaredContents(plugin: AntigravityCatalogPlugin): ExtensionPluginCont * user, so one instance's change is every same-home instance's change. */ const instancesByPluginHome = new Map>>(); +/** One write at a time per plugin folder, across every instance and its receipt file. */ +const writesByPluginHome = new Map(); const WORKSPACE_REFUSED = "Antigravity plugins belong to your user account, not a workspace. Change them from the agent's own list."; @@ -333,7 +341,15 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi ); const retired = yield* Deferred.make(); yield* Effect.addFinalizer(() => Deferred.succeed(retired, undefined)); - const writes = yield* Semaphore.make(1); + const writes = + options.pluginHome === undefined + ? yield* Semaphore.make(1) + : (writesByPluginHome.get(options.pluginHome) ?? + (yield* Semaphore.make(1).pipe( + Effect.tap((created) => + Effect.sync(() => writesByPluginHome.set(options.pluginHome!, created)), + ), + ))); const readReceipts = fs.exists(receiptsFile).pipe( Effect.flatMap((exists) => @@ -362,13 +378,14 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const readList = Effect.fn("AntigravityProviderStore.readList")( function* () { - const sequence = yield* nextInventoryReadSequence; - const output = yield* options.run(["plugin", "list", "--json"]); // The cached catalog, when it reads, names plugins installed before agy recorded origins. + // Read before agy's list, so a slow catalog never makes the listing stale. const known = yield* catalog.read(false).pipe( Effect.map((read) => new Map(read.plugins.map((plugin) => [plugin.name, plugin]))), Effect.option, ); + const sequence = yield* nextInventoryReadSequence; + const output = yield* options.run(["plugin", "list", "--json"]); const plugins = yield* parseAntigravityPluginList( output, yield* readReceipts, @@ -380,6 +397,13 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi Effect.provideService(FileSystem.FileSystem, fs), Effect.mapError(() => ({ message: "Could not read Antigravity's installed plugins." })), ); + /** agy's own list and nothing else: the last check before a change acts on it. */ + const nativeListed = Effect.fn("AntigravityProviderStore.nativeListed")( + function* () { + return yield* decodeListed((yield* options.run(["plugin", "list", "--json"])).trim()); + }, + Effect.mapError(() => ({ message: "Could not read Antigravity's installed plugins." })), + ); const list = Effect.fn("AntigravityProviderStore.list")(function* () { const reason = yield* options.unavailable; if (reason) return yield* fail(reason); @@ -393,7 +417,7 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi ): ProviderStoreEntry => { const id = entryId(plugin.name, plugin.marketplace); const native = installed?.find((item) => item.name === plugin.name); - const added = native?.id === id; + const added = native?.id === id || native?.catalogMarketplace === plugin.marketplace; const disabledReason = unavailable ?? (installed === undefined @@ -521,54 +545,63 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const item = yield* find(id); if (item.entry.disabledReason) return yield* fail(item.entry.disabledReason); if (item.entry.installed) return; - // agy's own marketplace install records the origin and keeps the plugin updated. It needs - // agy's own sign-in; without one, Scient adds the catalog's checked archive instead. - const nativeAdd = yield* options.run(["plugin", "install", id]).pipe(Effect.option); - if (nativeAdd._tag === "Some") { - const listed = (yield* list()).plugins.find((plugin) => plugin.name === item.plugin.name); - if (listed?.id !== id) - return yield* fail("Antigravity did not list the plugin after adding it."); - yield* writeReceipts((receipts) => - receipts.filter((receipt) => receipt.name !== listed.name), - ).pipe(Effect.ignore); + const name = item.plugin.name; + const marketplace = item.plugin.marketplace; + // agy's own marketplace install records the origin, keeps the plugin updated and refuses a + // folder another source holds. It needs agy's own sign-in; without one, Scient adds the + // catalog's checked archive instead. + const named = yield* options.run(["plugin", "install", id]).pipe(Effect.option); + const afterNamed = (yield* nativeListed()).find((plugin) => plugin.name === name); + if (afterNamed) { + if (afterNamed.source?.trim() !== marketplace) + return yield* fail( + `Antigravity has a different plugin named ${name} now, so Scient did not add this one.`, + ); + yield* writeReceipts((receipts) => receipts.filter((receipt) => receipt.name !== name)).pipe( + Effect.ignore, + ); return; } + if (named._tag === "Some") + return yield* fail("Antigravity did not list the plugin after adding it."); const archive = item.plugin.archive; if (!archive) return yield* fail("This plugin cannot be added from Scient."); - yield* Effect.scoped( - stageAntigravityPlugin({ - name: item.plugin.name, - version: item.plugin.version, - archive, - stagingRoot, - }).pipe( - Effect.mapError((cause) => - isAntigravityPluginArchiveError(cause) - ? { message: cause.message } - : { message: "Scient could not prepare this plugin to add." }, - ), - // agy has no no-replace install and overwrites a same-name folder, so the download - // window must not hide a plugin the Antigravity app installed meanwhile. - Effect.tap(() => - list().pipe( - Effect.flatMap((current) => - current.plugins.some((plugin) => plugin.name === item.plugin.name) - ? fail( - `Antigravity got a plugin named ${item.plugin.name} while Scient was preparing this one, so Scient did not replace it.`, - ) - : Effect.void, - ), + const added = yield* Effect.scoped( + Effect.gen(function* () { + const directory = yield* stageAntigravityPlugin({ + name, + version: item.plugin.version, + archive, + stagingRoot, + }).pipe( + Effect.mapError((cause) => + isAntigravityPluginArchiveError(cause) + ? { message: cause.message } + : { message: "Scient could not prepare this plugin to add." }, ), - ), - Effect.flatMap((directory) => options.run(["plugin", "install", directory])), - ), + ); + const staged = sha256Hex( + yield* fs + .readFile(path.join(directory, "plugin.json")) + .pipe( + Effect.mapError(() => ({ message: "Scient could not read the prepared plugin." })), + ), + ); + // A directory install replaces a same-name folder, so agy's own list is the last read + // before it: nothing else may run between them. + if ((yield* nativeListed()).some((plugin) => plugin.name === name)) + return yield* fail( + `Antigravity got a plugin named ${name} while Scient was preparing this one, so Scient did not replace it.`, + ); + yield* options.run(["plugin", "install", directory]); + return staged; + }), ).pipe( Effect.provideService(HttpClient.HttpClient, http), Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), ); - const after = yield* list(); - const listed = after.plugins.find((plugin) => plugin.name === item.plugin.name); + const listed = (yield* nativeListed()).find((plugin) => plugin.name === name); if (!listed) return yield* fail("Antigravity did not list the plugin after adding it."); const installation = yield* installationIdentity(listed.path).pipe( Effect.provideService(FileSystem.FileSystem, fs), @@ -577,13 +610,20 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi message: "The plugin was added, but Scient could not read its installed folder.", })), ); + // The receipt vouches only for the copy this Add installed, never one swapped in after. + if (!installation.endsWith(`:${added}`)) + return yield* fail( + `The plugin named ${name} changed while Scient added it, so Scient did not claim it.`, + ); + const version = listed.version?.trim() || undefined; + const source = listed.source?.trim() || undefined; yield* writeReceipts((receipts) => [ - ...receipts.filter((receipt) => receipt.name !== listed.name), + ...receipts.filter((receipt) => receipt.name !== name), { - name: listed.name, - marketplace: item.plugin.marketplace, - ...(listed.version ? { version: listed.version } : {}), - ...(listed.nativeSource ? { source: listed.nativeSource } : {}), + name, + marketplace, + ...(version ? { version } : {}), + ...(source ? { source } : {}), sha256: archive.sha256, path: listed.path, displayName: item.plugin.displayName, diff --git a/apps/web/src/scient/extensions/ServiceAgents.tsx b/apps/web/src/scient/extensions/ServiceAgents.tsx index 036c7122e9..8cee2a8588 100644 --- a/apps/web/src/scient/extensions/ServiceAgents.tsx +++ b/apps/web/src/scient/extensions/ServiceAgents.tsx @@ -178,8 +178,13 @@ function AntigravityServiceRow({ const entry = useEnvironmentQuery(atom); const plugin = provider.plugins?.find((item) => item.id === route.storeEntryId); if (entry.error || entry.data?.storeUnavailable) return null; + // The store also knows copies installed before agy recorded origins, by their manifest. const state = - entry.data === null || entry.data.installationStateKnown === false ? "checking" : route.state; + entry.data === null || entry.data.installationStateKnown === false + ? "checking" + : route.state === "add" && entry.data.installed + ? "added" + : route.state; return ( Date: Sun, 22 Nov 2026 00:52:22 +0200 Subject: [PATCH 29/36] docs(extensions): describe Antigravity Add and origin as built Pages for ChatGPT apps that also have an Antigravity plugin use the provider-neutral sentence. Records why the plugin's command name is enough evidence for the sign-in action: agy hands the token on that. Co-Authored-By: Claude Opus 5.5 --- .../src/scient/extensions/accountServices.ts | 21 +++++---- docs/internals/scient-extensions.md | 44 +++++++++++++------ 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/apps/web/src/scient/extensions/accountServices.ts b/apps/web/src/scient/extensions/accountServices.ts index 5ecbb3c79a..024b9593d1 100644 --- a/apps/web/src/scient/extensions/accountServices.ts +++ b/apps/web/src/scient/extensions/accountServices.ts @@ -192,14 +192,19 @@ export function accountServiceForApp(app: { id: slug(app.name), name: app.name, tagline: app.description?.split("\n")[0]?.slice(0, 80) ?? "", - description: claude - ? msg("Each agent reaches {name} through its own sign-in. Scient never holds that sign-in.", { - name: app.name, - }) - : msg( - "Codex and Scient Agent reach {name} through your ChatGPT account. Scient never holds that sign-in.", - { name: app.name }, - ), + // Another agent's own route besides ChatGPT's: every agent has its own sign-in. + description: + claude || antigravity + ? msg( + "Each agent reaches {name} through its own sign-in. Scient never holds that sign-in.", + { + name: app.name, + }, + ) + : msg( + "Codex and Scient Agent reach {name} through your ChatGPT account. Scient never holds that sign-in.", + { name: app.name }, + ), categories: [], chatgptAppId: id, claude, diff --git a/docs/internals/scient-extensions.md b/docs/internals/scient-extensions.md index ec509154b4..580606f72d 100644 --- a/docs/internals/scient-extensions.md +++ b/docs/internals/scient-extensions.md @@ -861,14 +861,17 @@ ServerProviderMcpServer { name; status: "connected" | "failed" | "needs-auth" | projects it, whether or not a notice follows, together with the `state` and `code_challenge` of any challenge seen. A stream holds a possible partial URL, secret or card (bounded) until that stream ends: a tool's output with its call, - a reply at the next tool call or the prompt's end. A challenge needs exactly one + a reply or thought at the prompt's end, never at another tool's update. A challenge needs exactly one well-formed card and one URL in the tool's result, never in its input; streamed output counts once its call ends. It earns a notice only from a plain shell run (no pipes, chaining, redirection or substitution) of a CLI that the installed plugin's `auth.json` lists under `providers.*.clis`, read bounded from `~/.gemini/config/plugins//`, whose `plugin.json` name equals the card's `catalog-id`, and whose `oauth2.authorizeUrl` and `oauth2.clientId` match the - page's origin, path and `client_id`. The page must also be HTTPS with no + page's origin, path and `client_id`. The command name is the same evidence + agy itself uses to hand the plugin its Google token (`delivery: env` for the + bare CLI), so a different program by that name already gets the token from + agy; the action adds no reach beyond it. The page must also be HTTPS with no userinfo or fragment, one `state`, and one `redirect_uri` that is HTTP loopback with a port of 1024 or above and path `/callback`. Partner plugins that sign in through MCP OAuth declare no CLI, so they get no button until their challenge @@ -956,19 +959,32 @@ other stays listed. Partner entries carry `publisherType: "third-party"` and show a developer notice before Add. Discover categories come from a reviewed per-plugin map, then the feed's own category and keywords. -Add does not use agy's named installs, which need the CLI's own sign-in. -Scient downloads the entry's gstatic archive (64 MiB cap), checks the feed's +Add first runs agy's own `agy plugin install @`, which records +the catalog as the plugin's `source`, keeps it updated and refuses a folder +another source holds (verified on agy 1.5.12). It needs agy's own sign-in, not +Scient's per-instance profile. Whatever the command reported, Scient then reads +agy's raw list: the name listed with that catalog as `source` is an Add, any +other copy of the name is refused, and only an absent name falls back. The +fallback downloads the entry's gstatic archive (64 MiB cap), checks the feed's SHA-256 before opening it, unpacks it without links, special files, escaping or -colliding names, keeps executable bits, checks `plugin.json`'s name and -version, then runs `agy plugin install ` with a minimal -environment. The plugin lands in the OS user's `~/.gemini/config/plugins`, -shared with the Antigravity app. agy's listing does not keep the catalog, so -`/antigravity-plugins/receipts.json` records name, catalog, version, -digest and folder; only a matching receipt makes a listed plugin the catalog -entry's installation. Installed state, enable/disable and Remove use -`agy plugin list --json`, `enable|disable` and `uninstall`. A catalog outage -keeps Installed and Remove; an unreadable listing pauses Add and Remove. A -paired-harness instance lists the catalogs with Add disabled and says why. +colliding names, keeps executable bits, checks `plugin.json`'s name and version, +re-reads agy's raw list as the last step before `agy plugin install +` (which replaces a same-name folder), and runs it with a minimal +environment. A receipt in `/antigravity-plugins/receipts.json` records +name, catalog, version, source, digest, folder and the installed copy's identity +(folder device, inode, birth time and `plugin.json` digest), written only when +that digest equals the staged one. Writes to one plugin folder, its receipts +included, take one permit shared by every instance using that folder. + +An installed copy is the catalog entry when agy's `source` names the catalog or +a receipt matches that exact copy; it then carries the entry's id and Marketplace +Remove acts on it. A copy with no recorded origin (`source` null or +`antigravity`) whose `plugin.json` has the same name and the catalog's +repository, author or description shows as added but keeps its own +`antigravity:` id, so only Installed removes it. Installed state, +enable/disable and Remove use `agy plugin list --json`, `enable|disable` and +`uninstall`. A catalog outage keeps Installed and Remove; an unreadable listing +pauses Add and Remove. A paired-harness instance lists the catalogs with Add disabled and says why. `providerPlugins.act` accepts `install` (entry id, with an optional source instance for shared stores), `add-official-store`, and the existing lifecycle From 118a73b6cd67483f07b6e8a55dc1967538890cb9 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 00:55:51 +0200 Subject: [PATCH 30/36] fix(antigravity): receipts need the folder agy created; Turn on finds older copies An archive receipt now also needs the installed folder to be born after the install began, besides the staged plugin.json. A service row for a copy recognised only by its manifest finds it by name, so a disabled one offers Turn on for its own id. Documents the archive route's remaining moment without a no-replace install. Co-Authored-By: Claude Opus 5.5 --- .../extensions/AntigravityProviderStore.ts | 14 +++++++++++--- .../extensions/Extensions.browser.test.tsx | 17 +++++++++++++++++ .../web/src/scient/extensions/ServiceAgents.tsx | 15 +++++++++++---- docs/internals/scient-extensions.md | 6 +++++- 4 files changed, 44 insertions(+), 8 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index af942cf3fe..a2179de242 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -11,6 +11,7 @@ import type { ProviderStoreSearchInput, ServerProviderPlugin, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -593,8 +594,9 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi return yield* fail( `Antigravity got a plugin named ${name} while Scient was preparing this one, so Scient did not replace it.`, ); + const startedAt = yield* Clock.currentTimeMillis; yield* options.run(["plugin", "install", directory]); - return staged; + return { staged, startedAt }; }), ).pipe( Effect.provideService(HttpClient.HttpClient, http), @@ -610,8 +612,14 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi message: "The plugin was added, but Scient could not read its installed folder.", })), ); - // The receipt vouches only for the copy this Add installed, never one swapped in after. - if (!installation.endsWith(`:${added}`)) + // The receipt vouches only for the copy this Add installed, never one swapped in after: the + // folder agy created (born after the install began, where the system records births) with + // the staged plugin.json. + const born = installation.split(":")[2]; + if ( + !installation.endsWith(`:${added.staged}`) || + (born !== undefined && born !== "" && Number(born) < added.startedAt - 2_000) + ) return yield* fail( `The plugin named ${name} changed while Scient added it, so Scient did not claim it.`, ); diff --git a/apps/web/src/scient/extensions/Extensions.browser.test.tsx b/apps/web/src/scient/extensions/Extensions.browser.test.tsx index 012b8c2839..ff4150ef22 100644 --- a/apps/web/src/scient/extensions/Extensions.browser.test.tsx +++ b/apps/web/src/scient/extensions/Extensions.browser.test.tsx @@ -2662,6 +2662,23 @@ describe("Antigravity Marketplace", () => { }), ); + // An older copy the store recognised by its manifest keeps its own id; Turn on acts on it. + agents = await show( + { plugins: [{ ...added(false), id: "antigravity:gmail" }] }, + { ...gmail, installed: true }, + ); + await vi.waitFor(() => expect(agents.textContent).toContain("Off in Antigravity")); + await userEvent.click(buttonIn(agents, "Turn on")!); + await vi.waitFor(() => + expect(state.commands.providerAct).toHaveBeenLastCalledWith({ + environmentId: "local", + input: { + instanceId: antigravity, + action: { type: "set-enabled", pluginId: "antigravity:gmail", enabled: true }, + }, + }), + ); + // A different plugin of the same name: the reason and where to act, never a dead Add. const clash = "Antigravity already has a different plugin named gmail."; agents = await show({ plugins: [] }, { ...gmail, disabledReason: clash }); diff --git a/apps/web/src/scient/extensions/ServiceAgents.tsx b/apps/web/src/scient/extensions/ServiceAgents.tsx index 8cee2a8588..b720aa242e 100644 --- a/apps/web/src/scient/extensions/ServiceAgents.tsx +++ b/apps/web/src/scient/extensions/ServiceAgents.tsx @@ -176,14 +176,21 @@ function AntigravityServiceRow({ input: { instanceId: route.instanceId, entryId: route.storeEntryId }, }); const entry = useEnvironmentQuery(atom); - const plugin = provider.plugins?.find((item) => item.id === route.storeEntryId); + // The store also knows copies installed before agy recorded origins, by their manifest; those + // keep their own id, so find them by name and act on that copy. + const plugin = + provider.plugins?.find((item) => item.id === route.storeEntryId) ?? + (entry.data?.installed + ? provider.plugins?.find((item) => item.name === entry.data?.name) + : undefined); if (entry.error || entry.data?.storeUnavailable) return null; - // The store also knows copies installed before agy recorded origins, by their manifest. const state = entry.data === null || entry.data.installationStateKnown === false ? "checking" - : route.state === "add" && entry.data.installed - ? "added" + : route.state === "add" && plugin !== undefined + ? plugin.enabled + ? "added" + : "off" : route.state; return ( diff --git a/docs/internals/scient-extensions.md b/docs/internals/scient-extensions.md index 580606f72d..39efa32dc2 100644 --- a/docs/internals/scient-extensions.md +++ b/docs/internals/scient-extensions.md @@ -973,7 +973,11 @@ re-reads agy's raw list as the last step before `agy plugin install environment. A receipt in `/antigravity-plugins/receipts.json` records name, catalog, version, source, digest, folder and the installed copy's identity (folder device, inode, birth time and `plugin.json` digest), written only when -that digest equals the staged one. Writes to one plugin folder, its receipts +that digest equals the staged one and the folder was born after the install +began (where the system records birth times). agy has no no-replace directory +install, so a same-name install by another program in the moment between that +last list and the install can still be replaced; the named route has no such +window. Writes to one plugin folder, its receipts included, take one permit shared by every instance using that folder. An installed copy is the catalog entry when agy's `source` names the catalog or From b082aee08be1708e5537c96c7794a24703415356 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 01:14:29 +0200 Subject: [PATCH 31/36] fix(antigravity): scrub every text update and key notices by session Whole agent messages and thoughts, compaction summaries and terminal output (base64, decoded across chunk boundaries) now pass through the same sign-in scrub as message chunks before projection. Plugin sign-in notices are keyed by ACP session and tool call, since tool call ids are unique only within one session. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.ts | 3 +- .../scient/antigravity/pluginSignIn.test.ts | 82 ++++++++++-- .../src/scient/antigravity/pluginSignIn.ts | 122 ++++++++++++++---- packages/provider-acp/src/server/adapter.ts | 10 +- 4 files changed, 182 insertions(+), 35 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 10b680649a..fcdbbd608f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -428,7 +428,8 @@ export function makeAntigravityAcpAdapterFlavor( }, normalizeToolCall: normalizeAntigravityToolCall, // SCIENT-FORK:START — plugin sign-in notices and the pages they open. - scientToolNotice: (toolCallId, owner) => pluginSignIns.takeToolNotice(toolCallId, owner), + scientToolNotice: (sessionId, toolCallId, owner) => + pluginSignIns.takeToolNotice(sessionId, toolCallId, owner), scientPluginSignIn: { open: Effect.fn("AntigravityAdapterV2.pluginSignIn.open")(function* (input) { const redeemed = pluginSignIns.redeem({ diff --git a/apps/server/src/scient/antigravity/pluginSignIn.test.ts b/apps/server/src/scient/antigravity/pluginSignIn.test.ts index ea83099004..580eb1fc10 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.test.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.test.ts @@ -258,12 +258,12 @@ describe("makeAntigravityPluginSignIns", () => { expect(JSON.stringify(notifications)).toContain(LINK_REMOVED); expect(candidate).toMatchObject({ program: "gmail", toolCallId: "call-1" }); admit(candidate); - expect(signIns.takeToolNotice("call-1", owner)?.pluginSignIn).toEqual({ + expect(signIns.takeToolNotice("session-1", "call-1", owner)?.pluginSignIn).toEqual({ attemptId: "attempt-1", plugin: "gmail", displayName: "Gmail", }); - expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + expect(signIns.takeToolNotice("session-1", "call-1", owner)).toBeUndefined(); expect( signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), ).toEqual({ url: URL_OK }); @@ -297,13 +297,13 @@ describe("makeAntigravityPluginSignIns", () => { expect(candidate).toBeUndefined(); expect(JSON.stringify(notifications)).not.toContain(STATE); } - expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + expect(signIns.takeToolNotice("session-1", "call-1", owner)).toBeUndefined(); }); it("never opens the page for another thread or session", () => { const { signIns, observe, admit } = setup(); admit(observe(challengeUpdate()).candidate); - signIns.takeToolNotice("call-1", owner); + signIns.takeToolNotice("session-1", "call-1", owner); const other = { ...owner, threadId: ThreadId.make("thread-2") }; expect( signIns.redeem({ @@ -321,7 +321,7 @@ describe("makeAntigravityPluginSignIns", () => { it("expires attempts and retires them with their agent process", () => { const { signIns, generation, observe, admit } = setup({ ttlMs: 1_000 }); admit(observe(challengeUpdate()).candidate); - signIns.takeToolNotice("call-1", owner); + signIns.takeToolNotice("session-1", "call-1", owner); const redeem = (now: number) => signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now }); expect(redeem(1_000)).toEqual({ failure: "expired" }); @@ -334,7 +334,7 @@ describe("makeAntigravityPluginSignIns", () => { const { signIns, observe } = setup(); const { candidate } = observe(textChunk(challengeText())); expect(candidate).toBeUndefined(); - expect(signIns.takeToolNotice("call-1", owner)).toBeUndefined(); + expect(signIns.takeToolNotice("session-1", "call-1", owner)).toBeUndefined(); }); it("scrubs a repeated page across chunks and hides the repeated card", () => { @@ -379,10 +379,72 @@ describe("makeAntigravityPluginSignIns", () => { expect(textOf(projected)).toBe(`Open ${LINK_REMOVED} please`); }); + // regression: whole messages, compaction summaries and terminal output skipped the scrub. + it("scrubs a page from every other update that shows text", () => { + const { signIns, generation, observe } = setup(); + const reply = `Open ${URL_OK} please`; + const whole = observe({ + sessionId: "session-1", + update: { + sessionUpdate: "agent_message", + messageId: "m-1", + content: [{ type: "text", text: reply }], + }, + } as EffectAcpSchema.SessionNotification).notifications; + const summary = [ + ...observe({ + sessionId: "session-1", + update: { + sessionUpdate: "compaction_summary_chunk", + compactionId: "c-1", + content: { type: "text", text: reply.slice(0, 120) }, + }, + } as EffectAcpSchema.SessionNotification).notifications, + ...observe({ + sessionId: "session-1", + update: { + sessionUpdate: "compaction_summary_chunk", + compactionId: "c-1", + content: { type: "text", text: reply.slice(120) }, + }, + } as EffectAcpSchema.SessionNotification).notifications, + ]; + const bytes = Buffer.from(reply, "utf8"); + const terminal = (data: Buffer) => + observe({ + sessionId: "session-1", + update: { + sessionUpdate: "terminal_output_chunk", + terminalId: "t-1", + data: data.toString("base64"), + }, + } as EffectAcpSchema.SessionNotification).notifications; + const output = [...terminal(bytes.subarray(0, 120)), ...terminal(bytes.subarray(120))]; + const rest = signIns.flush(generation); + const shown = JSON.stringify([...whole, ...summary, ...rest]); + expect(shown).not.toContain(STATE); + expect(shown).toContain(LINK_REMOVED); + const terminalText = [...output, ...rest] + .map((entry) => + entry.update.sessionUpdate === "terminal_output_chunk" + ? Buffer.from(entry.update.data, "base64").toString("utf8") + : "", + ) + .join(""); + expect(terminalText).toBe(`Open ${LINK_REMOVED} please`); + }); + + it("keeps two sessions' notices for the same tool call id apart", () => { + const { signIns, observe, admit } = setup(); + admit(observe(challengeUpdate()).candidate); + expect(signIns.takeToolNotice("session-2", "call-1", owner)).toBeUndefined(); + expect(signIns.takeToolNotice("session-1", "call-1", owner)).toBeDefined(); + }); + it("reports the plugin's next successful call as signed in", () => { const { signIns, observe, admit } = setup(); admit(observe(challengeUpdate()).candidate); - signIns.takeToolNotice("call-1", owner); + signIns.takeToolNotice("session-1", "call-1", owner); observe( toolUpdate("call-2", { status: "completed", @@ -391,7 +453,7 @@ describe("makeAntigravityPluginSignIns", () => { rawOutput: { output: "3 messages", exit_code: 0 }, }), ); - expect(signIns.takeToolNotice("call-2", owner)?.pluginSignIn).toEqual({ + expect(signIns.takeToolNotice("session-1", "call-2", owner)?.pluginSignIn).toEqual({ attemptId: "attempt-1", plugin: "gmail", displayName: "Gmail", @@ -405,7 +467,7 @@ describe("makeAntigravityPluginSignIns", () => { it("replaces an older attempt for the same plugin", () => { const { signIns, observe, admit } = setup(); admit(observe(challengeUpdate()).candidate); - signIns.takeToolNotice("call-1", owner); + signIns.takeToolNotice("session-1", "call-1", owner); const second = challengeText(signInUrl({ state: "second-state" })); admit( observe( @@ -417,7 +479,7 @@ describe("makeAntigravityPluginSignIns", () => { }), ).candidate, ); - signIns.takeToolNotice("call-3", owner); + signIns.takeToolNotice("session-1", "call-3", owner); expect( signIns.redeem({ attemptId: "attempt-1", owner, nativeSessionId: "session-1", now: 1 }), ).toEqual({ failure: "expired" }); diff --git a/apps/server/src/scient/antigravity/pluginSignIn.ts b/apps/server/src/scient/antigravity/pluginSignIn.ts index 41fab2c6e3..bf1c7b1d10 100644 --- a/apps/server/src/scient/antigravity/pluginSignIn.ts +++ b/apps/server/src/scient/antigravity/pluginSignIn.ts @@ -358,10 +358,15 @@ export interface PluginSignInToolNotice { } type Notification = EffectAcpSchema.SessionNotification; -type ChunkUpdate = Extract< - EffectAcpSchema.SessionUpdate, - { readonly sessionUpdate: "agent_message_chunk" | "agent_thought_chunk" } ->; +/** How many leading bytes end on a whole UTF-8 character; the rest waits for the next chunk. */ +const utf8Boundary = (bytes: Uint8Array) => { + let start = bytes.length - 1; + while (start >= 0 && bytes.length - start < 4 && (bytes[start]! & 0xc0) === 0x80) start -= 1; + if (start < 0) return bytes.length; + const lead = bytes[start]!; + const width = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1; + return bytes.length - start < width ? start : bytes.length; +}; const exitCodeOf = (rawOutput: unknown) => { if (!Predicate.isObject(rawOutput)) return undefined; @@ -399,8 +404,13 @@ export function makeAntigravityPluginSignIns( >(); const redactors = new Map< string, - { readonly redactor: ReturnType; template: Notification } + { + readonly redactor: ReturnType; + rebuild: (text: string) => Notification; + } >(); + // Terminal output arrives as base64 bytes; a character split across chunks waits here. + const terminalPending = new Map(); const tools = new Map(); // Secrets of every challenge a session printed, admitted or not. const secretsBySession = new Map>(); @@ -415,6 +425,9 @@ export function makeAntigravityPluginSignIns( .map((attempt) => ``), }); + // Tool call ids are unique only within one ACP session. + const noticeKey = (sessionId: string, toolCallId: string) => `${sessionId}\u0000${toolCallId}`; + const rememberSecrets = (sessionId: string, secrets: ReadonlyArray) => { const known = secretsBySession.get(sessionId) ?? []; for (const secret of secrets) if (!known.includes(secret)) known.push(secret); @@ -428,16 +441,10 @@ export function makeAntigravityPluginSignIns( for (const [key, entry] of redactors) { if (!key.startsWith(prefix) || !ends(key.slice(prefix.length))) continue; redactors.delete(key); + terminalPending.delete(key); const text = entry.redactor.flush(); if (text.length === 0) continue; - const update = entry.template.update; - flushed.push({ - ...entry.template, - update: - update.sessionUpdate === "tool_call_content_chunk" - ? { ...update, content: { type: "content", content: { type: "text", text } } } - : { ...(update as ChunkUpdate), content: { type: "text", text } }, - }); + flushed.push(entry.rebuild(text)); } return flushed; }; @@ -451,17 +458,29 @@ export function makeAntigravityPluginSignIns( const key = `${notification.sessionId}\u0000${channel}`; let entry = redactors.get(key); if (entry === undefined) { - entry = { - redactor: makeStreamRedactor(sessionPatterns(notification.sessionId)), - template: notification, - }; + entry = { redactor: makeStreamRedactor(sessionPatterns(notification.sessionId)), rebuild }; redactors.set(key, entry); } - entry.template = notification; + entry.rebuild = rebuild; const emitted = entry.redactor.push(text); return emitted.length === 0 ? [] : [rebuild(emitted)]; }; + /** A whole message, scrubbed at once: nothing of it can be released before its end. */ + const scrubWhole = (sessionId: string, text: string) => { + const redactor = makeStreamRedactor(sessionPatterns(sessionId)); + return redactor.push(text) + redactor.flush(); + }; + const scrubBlocks = ( + sessionId: string, + blocks: ReadonlyArray | null | undefined, + ) => + blocks?.map((block) => + block.type === "text" && "text" in block && Predicate.isString(block.text) + ? { ...block, text: scrubWhole(sessionId, block.text) } + : block, + ); + const trackTool = (sessionId: string, toolCallId: string) => { const key = `${sessionId}\u0000${toolCallId}`; let tool = tools.get(key); @@ -526,6 +545,57 @@ export function makeAntigravityPluginSignIns( candidate: undefined, }; } + // Every other update that shows text goes through the same scrub before projection. + if (update.sessionUpdate === "agent_message" || update.sessionUpdate === "agent_thought") { + const content = scrubBlocks(sessionId, update.content); + return { + notifications: [ + { ...notification, update: { ...update, ...(content ? { content } : {}) } }, + ], + candidate: undefined, + }; + } + if (update.sessionUpdate === "compaction_update") { + const summary = scrubBlocks(sessionId, update.summary); + return { + notifications: [ + { ...notification, update: { ...update, ...(summary ? { summary } : {}) } }, + ], + candidate: undefined, + }; + } + if (update.sessionUpdate === "compaction_summary_chunk" && update.content.type === "text") { + return { + notifications: streamChunk( + notification, + `compaction:${update.compactionId}`, + update.content.text, + (text) => ({ + ...notification, + update: { ...update, content: { ...update.content, text } }, + }), + ), + candidate: undefined, + }; + } + if (update.sessionUpdate === "terminal_output_chunk") { + const channel = `terminal:${update.terminalId}`; + const key = `${sessionId}\u0000${channel}`; + const bytes = Buffer.concat([ + terminalPending.get(key) ?? Buffer.alloc(0), + Buffer.from(update.data, "base64"), + ]); + const end = utf8Boundary(bytes); + terminalPending.set(key, bytes.subarray(end)); + const text = bytes.subarray(0, end).toString("utf8"); + return { + notifications: streamChunk(notification, channel, text, (shown) => ({ + ...notification, + update: { ...update, data: Buffer.from(shown, "utf8").toString("base64") }, + })), + candidate: undefined, + }; + } if (update.sessionUpdate === "tool_call_content_chunk") { const content = update.content; if (content.type !== "content" || content.content.type !== "text") { @@ -592,7 +662,10 @@ export function makeAntigravityPluginSignIns( if (waiting !== undefined) { waiting.signedIn = true; waiting.live = false; - pendingNotices.set(update.toolCallId, { attemptId: waiting.id, signedIn: true }); + pendingNotices.set(noticeKey(sessionId, update.toolCallId), { + attemptId: waiting.id, + signedIn: true, + }); } } if (terminal) tools.delete(key); @@ -639,7 +712,10 @@ export function makeAntigravityPluginSignIns( attempts.set(attempt.id, attempt); evict(); } - pendingNotices.set(candidate.toolCallId, { attemptId: attempt.id, signedIn: false }); + pendingNotices.set(noticeKey(candidate.sessionId, candidate.toolCallId), { + attemptId: attempt.id, + signedIn: false, + }); }, /** Ends every stream of an agent process's sessions when its prompt ends. */ flush: (generation: number) => @@ -648,12 +724,14 @@ export function makeAntigravityPluginSignIns( .flatMap(([sessionId]) => flushStreams(sessionId, () => true)), /** The notice a tool call raised, once; it binds the attempt to the thread that shows it. */ takeToolNotice: ( + sessionId: string, toolCallId: string, owner: PluginSignInOwner, ): PluginSignInToolNotice | undefined => { - const pending = pendingNotices.get(toolCallId); + const key = noticeKey(sessionId, toolCallId); + const pending = pendingNotices.get(key); if (pending === undefined) return undefined; - pendingNotices.delete(toolCallId); + pendingNotices.delete(key); const attempt = attempts.get(pending.attemptId); if (attempt === undefined) return undefined; attempt.owner ??= owner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 81d15aa9c1..a10355e828 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -793,6 +793,7 @@ export interface AcpAdapterV2Flavor { // SCIENT-FORK:START — typed notices about root tool calls, and the plugin sign-ins they offer. /** The notice a root tool call raised, taken once; `owner` is the thread that shows it. */ readonly scientToolNotice?: ( + sessionId: string, toolCallId: string, owner: { readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId }, ) => ProviderAdapter.ScientToolNotice | undefined; @@ -5455,9 +5456,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // SCIENT-FORK:START — see AcpAdapterV2Flavor.scientToolNotice. const emitScientToolNotice = Effect.fnUntraced(function* ( context: ActiveAcpTurn, + sessionId: string, toolCallId: string, ) { - const notice = flavor.scientToolNotice?.(toolCallId, { + const notice = flavor.scientToolNotice?.(sessionId, toolCallId, { threadId: context.input.threadId, providerThreadId: context.input.providerThread.id, }); @@ -6816,7 +6818,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (event._tag === "ToolCallUpdated") { yield* emitTool(context, event.toolCall, undefined, event.rawPayload); // SCIENT-FORK: see AcpAdapterV2Flavor.scientToolNotice. - yield* emitScientToolNotice(context, event.toolCall.toolCallId); + yield* emitScientToolNotice( + context, + notification.sessionId, + event.toolCall.toolCallId, + ); } else if (event._tag === "PlanUpdated") { yield* emitPlan(context, event.payload, update.sessionUpdate !== "plan"); } else if (event._tag === "NoticeReceived") { From e2b5449790804bb8baf1590ba5831c60cd1046be Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 01:14:46 +0200 Subject: [PATCH 32/36] fix(claude): finish a chat MCP sign-in from the browser without pasting Claude reports a sign-in finished on its own page only as the server's status, so without a pasted address its complete step now watches that status for up to five minutes instead of failing at once. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 57 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 20 ++++++- 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c20847a0ba..61912742e7 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -7447,6 +7447,63 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // SCIENT-FORK: a browser on this machine finishes Claude's sign-in on Claude's own page. + it.effect("finishes a chat MCP sign-in without an address once Claude reports it connected", () => + Effect.gen(function* () { + const checks = yield* Ref.make(0); + const harness = yield* makeWakeHarnessWithOptions({ + mcp: { + mcpServerStatus: Ref.updateAndGet(checks, (count) => count + 1).pipe( + Effect.map((count) => [ + { name: "linear", status: count >= 3 ? "connected" : "needs-auth" }, + ]), + ), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + }, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("mcp-sign-in-wait"), + text: "Plan the sprint", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "init", + uuid: "mcp-sign-in-wait-init", + session_id: WAKE_NATIVE_SESSION, + mcp_servers: [{ name: "linear", status: "needs-auth" }], + }), + ); + const finished = yield* harness.runtime + .mcpSignIn!.complete({ + providerThread: harness.providerThread, + server: "linear", + callbackUrl: undefined, + }) + .pipe(Effect.forkChild); + for (let step = 0; step < 4; step += 1) yield* TestClock.adjust("2 seconds"); + yield* Fiber.join(finished); + assert.isAtLeast(yield* Ref.get(checks), 3); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #38284 an MCP app's update-model-context note must reach Claude's next turn it.effect("sends MCP app model context with the next Claude turn", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 6ef1285955..ca81c4fdbd 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -313,6 +313,10 @@ export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent"); /** The query exited before the turn attached, so the prompt was never offered. */ export const CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL = "Claude provider query ended before the turn could start."; +// SCIENT-FORK: how long a chat MCP sign-in watches for the browser to finish on Claude's page. +const CLAUDE_MCP_SIGN_IN_BROWSER_WAIT_MS = 5 * 60_000; +const CLAUDE_MCP_SIGN_IN_POLL = "2 seconds"; + const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const; interface ClaudeCacheCreation { @@ -15915,8 +15919,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); // A browser on this machine may already have finished it on Claude's own page. if (statuses.find((status) => status.name === server)?.status === "connected") return; - // SCIENT-FORK:START — Claude reports no finished sign-in, so it needs the address. + // SCIENT-FORK:START — no address: a browser on this machine finishes it on Claude's + // own page, which Claude reports only as the server's status, so watch that for a while. if (callbackUrl === undefined) { + const connected = liveQuery.query.mcpServerStatus.pipe( + Effect.map( + (current) => + current.find((status) => status.name === server)?.status === "connected", + ), + Effect.orElseSucceed(() => false), + ); + const deadline = + (yield* Clock.currentTimeMillis) + CLAUDE_MCP_SIGN_IN_BROWSER_WAIT_MS; + while ((yield* Clock.currentTimeMillis) < deadline) { + yield* Effect.sleep(CLAUDE_MCP_SIGN_IN_POLL); + if (yield* connected) return; + } return yield* fail( "Paste the address your browser went to after you approved to finish the sign-in.", ); From 85edf788f08104ec2f3115e170cc1df0b1f1f0c4 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 01:14:59 +0200 Subject: [PATCH 33/36] fix(extensions): lock by agy's real plugin home; receipts per folder - The plugin-folder lock uses the same user home the runtime resolves (USERPROFILE, then HOMEDRIVE+HOMEPATH on Windows), compared case-insensitively on Windows. - Receipts are replaced per installed folder, so another plugin home's receipt for the same name survives. - Archives refuse Windows device names as path segments. - A catalog entry that names its MCP servers by a single path still shows that it includes MCP servers. Co-Authored-By: Claude Opus 5.5 --- .../AntigravityPluginArchive.test.ts | 7 ++++++ .../extensions/AntigravityPluginArchive.ts | 4 ++- .../extensions/AntigravityPluginCatalog.ts | 6 ++++- .../AntigravityProviderStore.test.ts | 3 ++- .../extensions/AntigravityProviderStore.ts | 25 +++++++++++++------ 5 files changed, 35 insertions(+), 10 deletions(-) diff --git a/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts index 618a18b047..42f85122aa 100644 --- a/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts @@ -80,6 +80,13 @@ describe("extractAntigravityArchive", () => { ).pipe(Effect.asVoid), ); + it.effect("refuses Windows device names, with or without an extension", () => + Effect.gen(function* () { + for (const name of ["skills/CON", "skills/nul.txt", "LPT1.md", "com9/x"]) + yield* refusal(makeZip([{ name, data: "x" }])); + }), + ); + it.effect("refuses two members that land on one name", () => refusal( makeZip([ diff --git a/apps/server/src/scient/extensions/AntigravityPluginArchive.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts index b4ca2de621..fb71a65b15 100644 --- a/apps/server/src/scient/extensions/AntigravityPluginArchive.ts +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts @@ -117,7 +117,9 @@ function memberSegments(fileName: string): ReadonlyArray | undefined { segment === ".." || segment.length > 255 || /[\u0000-\u001f\\:*?"<>|]/.test(segment) || - /[. ]$/.test(segment), + /[. ]$/.test(segment) || + // Windows device names, with or without an extension, never name a file there. + /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(\.|$)/i.test(segment), ) ) return undefined; diff --git a/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts index 662e5bed29..4784904ad0 100644 --- a/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts +++ b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts @@ -323,7 +323,11 @@ function catalogPlugin( scientCategories: antigravityCategories(plugin.name, categories, keywords), logoUrl: httpsUrl(plugin.logo), keywords, - includes: [...(skills.length ? ["Skills"] : []), ...(mcpServers.length ? ["MCP servers"] : [])], + // A single path (`"mcpServers": "./mcp_config.json"`) declares servers named only inside it. + includes: [ + ...(skills.length ? ["Skills"] : []), + ...(mcpServers.length || typeof plugin.mcpServers === "string" ? ["MCP servers"] : []), + ], skills, mcpServers, archive, diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts index 75f3536837..f1a4f72cda 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -98,6 +98,7 @@ const partnerFeed = (canva: Buffer) => ({ description: "Designs", author: { name: "Canva" }, skills: ["./skills/edit-design"], + mcpServers: "./mcp_config.json", source: { type: "archive", url: CANVA_ZIP, sha256: sha256(canva) }, }, ], @@ -236,7 +237,7 @@ describe("AntigravityProviderStore", () => { expect(page.entries[2]).toMatchObject({ publisherType: "third-party", publisher: "Canva", - includes: ["Skills"], + includes: ["Skills", "MCP servers"], }); expect((yield* store.search({ query: "science" })).entries.map((e) => e.name)).toEqual([ "chemistry", diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts index a2179de242..beb2021e85 100644 --- a/apps/server/src/scient/extensions/AntigravityProviderStore.ts +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -23,12 +23,14 @@ import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import { HttpClient } from "effect/http"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { ChildProcessSpawner } from "effect/process"; import type { ProviderNativeInventory, ProviderPluginActions, } from "../../provider/ScientProviderInstanceSeams.ts"; import { nextInventoryReadSequence } from "../../provider/ProviderNativeInventory.ts"; +import { resolveAntigravityUserHome } from "../../provider/Drivers/AntigravitySkills.ts"; import type { AntigravityExecutable, AntigravityInstallationError, @@ -558,9 +560,9 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi return yield* fail( `Antigravity has a different plugin named ${name} now, so Scient did not add this one.`, ); - yield* writeReceipts((receipts) => receipts.filter((receipt) => receipt.name !== name)).pipe( - Effect.ignore, - ); + yield* writeReceipts((receipts) => + receipts.filter((receipt) => receipt.path !== afterNamed.path), + ).pipe(Effect.ignore); return; } if (named._tag === "Some") @@ -626,7 +628,8 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const version = listed.version?.trim() || undefined; const source = listed.source?.trim() || undefined; yield* writeReceipts((receipts) => [ - ...receipts.filter((receipt) => receipt.name !== name), + // Receipts are per installed folder: another plugin home's receipt for the name stays. + ...receipts.filter((receipt) => receipt.path !== listed.path), { name, marketplace, @@ -742,7 +745,7 @@ export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActi const plugin = yield* nativePlugin(input.pluginId); yield* options.run(["plugin", "uninstall", plugin.name]); yield* writeReceipts((receipts) => - receipts.filter((receipt) => receipt.name !== plugin.name), + receipts.filter((receipt) => receipt.path !== plugin.path), ).pipe(Effect.ignore); }), ), @@ -830,12 +833,20 @@ export const makeAntigravityInstancePlugins = Effect.fn("makeAntigravityInstance ), Effect.orElseSucceed(() => "Install Antigravity to add its plugins."), ); - const home = input.environment.HOME ?? input.environment.USERPROFILE; + // The same home agy and the chat runtime resolve, so every instance writing one plugin + // folder shares its lock; Windows paths compare case-insensitively. + const platform = yield* HostProcess.Platform; + const home = resolveAntigravityUserHome( + platform, + input.environment, + yield* HostProcess.HomeDirectory, + ); + const pluginHome = path.resolve(home, ".gemini", "config", "plugins"); return yield* makeAntigravityPluginActions({ stateDir: input.stateDir, run, unavailable, - pluginHome: home ? path.resolve(home, ".gemini", "config", "plugins") : undefined, + pluginHome: platform === "win32" ? pluginHome.toLowerCase() : pluginHome, }); }, ); From 4f47844e0380059f3af087e141a308b53d052947 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 01:27:47 +0200 Subject: [PATCH 34/36] ci(runtime): void Antigravity publication when its runtime release choice changes antigravityRuntimeRelease.ts now decides which managed release the installer picks, so a change to it on main must void a qualification run. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/managed-provider-runtime-update-provider.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/managed-provider-runtime-update-provider.yml b/.github/workflows/managed-provider-runtime-update-provider.yml index 91166ac652..261f47b0d7 100644 --- a/.github/workflows/managed-provider-runtime-update-provider.yml +++ b/.github/workflows/managed-provider-runtime-update-provider.yml @@ -345,6 +345,7 @@ jobs: apps/server/src/scient/providerLifecycle/antigravityBrowserHelperPreflight.ts \ apps/server/scripts/qualify-antigravity-acp-catalog.ts \ apps/server/src/scient/providerLifecycle/antigravityAcpCatalog.ts \ + apps/server/src/scient/providerLifecycle/antigravityRuntimeRelease.ts \ apps/server/package.json \ ':(glob)apps/server/src/*.ts' \ apps/server/src/secrets/secretProviderDefinitions.ts \ From 62d4b0fd9d82e7975c241af88e3e3eb46c228a25 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 01:49:03 +0200 Subject: [PATCH 35/36] fix(antigravity): give the agy CLI's profile the user's plugins Scient runs `agy acp --gemini-dir `, and with that flag agy reads plugins, their sign-ins and their switches from the profile, not from ~/.gemini. The CLI branch only removed Scient's projection link, so chats saw plugin skills through other folders but agy never offered a plugin's sign-in (found in the live test: the Gmail CLI ran with no credentials). The profile's config/plugins now links to ~/.gemini/config/plugins, the folder Antigravity and the Extensions store install into, replacing only Scient's own link, and the user's plugin switches are copied into the profile's config.json beside Scient's keys. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/antigravityAuthSupport.ts | 6 +- .../antigravityPluginSkillProjection.test.ts | 56 ++++++-- .../antigravityPluginSkillProjection.ts | 135 +++++++++++++----- 3 files changed, 149 insertions(+), 48 deletions(-) diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index b16234abf8..100d4db020 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -25,7 +25,7 @@ import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStr // SCIENT-FORK:START — plugin skills are projected without their other components. import { projectAntigravityPluginSkills, - removeAntigravityPluginSkillProjection, + linkAntigravityUserPlugins, } from "../scient/skills/antigravityPluginSkillProjection.ts"; // SCIENT-FORK:END // SCIENT-FORK:START — safe skill links and a once-per-helper browser preflight. @@ -528,7 +528,7 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( readonly auth?: AntigravityAuthConfig; readonly userHome?: string; readonly tempDirectory?: string; - // SCIENT-FORK:START — the agy CLI loads plugins itself; only a paired runtime needs projection. + // SCIENT-FORK:START — the agy CLI reads the user's plugins through a link; paired runtimes get a projection. readonly nativePlugins?: boolean; // SCIENT-FORK:END }) { @@ -681,7 +681,7 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( } // SCIENT-FORK:START — see nativePlugins. yield* input.nativePlugins - ? removeAntigravityPluginSkillProjection({ profileDirectory: geminiHome }) + ? linkAntigravityUserPlugins({ profileDirectory: geminiHome, userHome, platform }) : projectAntigravityPluginSkills({ profileDirectory: geminiHome, userHome, platform }); // SCIENT-FORK:END return profile; diff --git a/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts b/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts index 68af9a43f0..bf24499d23 100644 --- a/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts +++ b/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts @@ -10,10 +10,11 @@ import * as Schema from "effect/Schema"; import { prepareAntigravityProfile } from "../../provider/antigravityAuthSupport.ts"; import { projectAntigravityPluginSkills, - removeAntigravityPluginSkillProjection, + linkAntigravityUserPlugins, } from "./antigravityPluginSkillProjection.ts"; const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown)); const makeHome = Effect.fn("test.makeAntigravityPluginHome")(function* () { const fs = yield* FileSystem.FileSystem; @@ -65,7 +66,7 @@ it.layer(NodeServices.layer)("Antigravity plugin skill projection", (it) => { ); it.effect.skipIf(!symlinksSupported)( - "removes only the projection link Scient made when the agy CLI loads plugins", + "links the agy CLI's profile to the user's own plugins, replacing only Scient's link", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -84,26 +85,63 @@ it.layer(NodeServices.layer)("Antigravity plugin skill projection", (it) => { expect(yield* isLink).toBe(true); const generation = yield* fs.readLink(pluginsLink); + // agy --gemini-dir reads plugins and their sign-ins from the profile. yield* prepareAntigravityProfile({ profileDirectory: home.profileDirectory, userHome: home.userHome, nativePlugins: true, }); - expect(yield* fs.exists(pluginsLink)).toBe(false); + expect(yield* fs.readLink(pluginsLink)).toBe(home.plugins); + expect(yield* fs.exists(path.join(pluginsLink, "gmail", "plugin.json"))).toBe(true); // A paired session that is still running keeps reading its generation. expect(yield* fs.exists(path.join(generation, "science", "skills"))).toBe(true); - const remove = removeAntigravityPluginSkillProjection({ + const link = linkAntigravityUserPlugins({ profileDirectory: home.profileDirectory, + userHome: home.userHome, + platform: yield* HostProcess.Platform, }); - yield* fs.symlink(home.plugins, pluginsLink); - yield* remove; - expect(yield* fs.readLink(pluginsLink)).toBe(home.plugins); - + // Someone else's link and a real folder stay as they are. + const elsewhere = path.join(home.root, "elsewhere"); + yield* fs.makeDirectory(elsewhere); + yield* fs.remove(pluginsLink); + yield* fs.symlink(elsewhere, pluginsLink); + yield* link; + expect(yield* fs.readLink(pluginsLink)).toBe(elsewhere); yield* fs.remove(pluginsLink); yield* fs.makeDirectory(path.join(pluginsLink, "own-plugin"), { recursive: true }); - yield* remove; + yield* link; expect(yield* fs.exists(path.join(pluginsLink, "own-plugin"))).toBe(true); }), ); + + it.effect.skipIf(!symlinksSupported)( + "copies the user's plugin switches into the profile beside Scient's own", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* makeHome(); + const profileConfig = path.join(home.profileDirectory, "config", "config.json"); + yield* fs.makeDirectory(path.dirname(profileConfig), { recursive: true }); + yield* fs.writeFileString( + profileConfig, + encodeJson({ plugins: { swarm: { enabled: false } } }), + ); + yield* fs.writeFileString( + path.join(home.userHome, ".gemini", "config", "config.json"), + encodeJson({ + plugins: { gmail: { enabled: false }, science: { installedFrom: { id: "x" } } }, + }), + ); + yield* linkAntigravityUserPlugins({ + profileDirectory: home.profileDirectory, + userHome: home.userHome, + platform: yield* HostProcess.Platform, + }); + expect(yield* decodeJson(yield* fs.readFileString(profileConfig))).toEqual({ + plugins: { swarm: { enabled: false }, gmail: { enabled: false } }, + }); + }), + ); }); diff --git a/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts b/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts index 581ce4b539..aff7a3037e 100644 --- a/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts +++ b/apps/server/src/scient/skills/antigravityPluginSkillProjection.ts @@ -28,6 +28,12 @@ const decodePluginSwitches = Schema.decodeUnknownOption( ), ); const projectionGeneration = /^[a-f0-9]{64}$/u; +const decodePluginConfig = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +); +const encodePluginConfig = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); /** Plugins `agy plugin disable` turned off, read as the skill picker reads them; null when * the user's config cannot be read. */ @@ -186,41 +192,98 @@ export const projectAntigravityPluginSkills = Effect.fn("projectAntigravityPlugi }, ); +const isProjectionLink = (profileDirectory: string, target: string) => + NodePath.dirname(target) === + NodePath.resolve(profileDirectory, "antigravity-acp", "skill-plugins") && + projectionGeneration.test(NodePath.basename(target)); + +/** Where a link at `link` points, resolved; Windows may prefix a junction with `\\?\`. */ +const linkTarget = async (link: string) => + NodePath.resolve( + NodePath.dirname(link), + (await NodeFSP.readlink(link)).replace(/^\\\\\?\\/u, ""), + ); + /** - * The agy CLI loads plugins itself from the user's ~/.gemini. Remove the profile's - * `config/plugins` link only when it is one Scient made to a projected generation; user - * directories and other links stay, and generations stay for any running paired session. + * `agy acp --gemini-dir ` reads plugins, sign-ins and switches from the profile: link its + * `config/plugins` to ~/.gemini/config/plugins (replacing only Scient's link, never a folder or + * another link) and copy the user's plugin switches beside Scient's keys. */ -export const removeAntigravityPluginSkillProjection = Effect.fn( - "removeAntigravityPluginSkillProjection", -)(function* (input: { readonly profileDirectory: string }) { - yield* Effect.tryPromise({ - try: async () => { - const pluginsLink = NodePath.join(input.profileDirectory, "config", "plugins"); - const existing = await NodeFSP.lstat(pluginsLink).catch((error: NodeJS.ErrnoException) => - error.code === "ENOENT" ? undefined : Promise.reject(error), - ); - if (!existing?.isSymbolicLink()) return; - // Windows may report a junction's target with the \\?\ long-path prefix. - const written = (await NodeFSP.readlink(pluginsLink)).replace(/^\\\\\?\\/u, ""); - const target = NodePath.resolve(NodePath.dirname(pluginsLink), written); - const projectionRoot = NodePath.resolve( - input.profileDirectory, - "antigravity-acp", - "skill-plugins", - ); - if ( - NodePath.dirname(target) !== projectionRoot || - !projectionGeneration.test(NodePath.basename(target)) - ) { - return; - } - await NodeFSP.rm(pluginsLink); - }, - catch: (cause) => (cause instanceof Error ? cause.message : String(cause)), - }).pipe( - Effect.catch((error) => - Effect.logWarning("Antigravity's projected plugin skills link was not removed.", { error }), - ), - ); -}); +export const linkAntigravityUserPlugins = Effect.fn("linkAntigravityUserPlugins")( + function* (input: { + readonly profileDirectory: string; + readonly userHome: string; + readonly platform: NodeJS.Platform; + }) { + yield* Effect.tryPromise({ + try: async () => { + const userPlugins = NodePath.resolve(input.userHome, ".gemini", "config", "plugins"); + await NodeFSP.mkdir(userPlugins, { recursive: true }); + const pluginsLink = NodePath.join(input.profileDirectory, "config", "plugins"); + const existing = await NodeFSP.lstat(pluginsLink).catch((error: NodeJS.ErrnoException) => + error.code === "ENOENT" ? undefined : Promise.reject(error), + ); + if (existing && !existing.isSymbolicLink()) return; + if (existing) { + const target = await linkTarget(pluginsLink); + if (target === userPlugins) return; + if (!isProjectionLink(input.profileDirectory, target)) return; + await NodeFSP.rm(pluginsLink); + } + await NodeFSP.mkdir(NodePath.dirname(pluginsLink), { recursive: true, mode: 0o700 }); + await NodeFSP.symlink( + userPlugins, + pluginsLink, + input.platform === "win32" ? "junction" : "dir", + ); + }, + catch: (cause) => (cause instanceof Error ? cause.message : String(cause)), + }).pipe( + Effect.catch((error) => + Effect.logWarning("Antigravity's plugins are not linked into the profile.", { error }), + ), + ); + yield* Effect.tryPromise({ + try: async () => { + const read = async (file: string) => { + const info = await NodeFSP.stat(file).catch(() => undefined); + if (!info?.isFile() || info.size > maxPluginManifestBytes) return undefined; + const text = await NodeFSP.readFile(file, "utf8"); + return { text, parsed: Option.getOrUndefined(decodePluginConfig(text)) }; + }; + const user = await read(NodePath.join(input.userHome, ".gemini", "config", "config.json")); + const switches = Object.entries(user?.parsed?.plugins ?? {}).flatMap(([name, value]) => + isRecord(value) && typeof value.enabled === "boolean" + ? [[name, value.enabled] as const] + : [], + ); + if (switches.length === 0) return; + const profileFile = NodePath.join(input.profileDirectory, "config", "config.json"); + const profile = await read(profileFile); + if (profile !== undefined && profile.parsed === undefined) return; + const next: Record = { ...profile?.parsed }; + const plugins: Record = isRecord(next.plugins) ? { ...next.plugins } : {}; + let changed = false; + for (const [name, enabled] of switches) { + const current = isRecord(plugins[name]) ? plugins[name] : {}; + if (current.enabled === enabled) continue; + plugins[name] = { ...current, enabled }; + changed = true; + } + if (!changed) return; + next.plugins = plugins; + const temporary = `${profileFile}.${NodeCrypto.randomUUID()}.tmp`; + await NodeFSP.mkdir(NodePath.dirname(profileFile), { recursive: true, mode: 0o700 }); + await NodeFSP.writeFile(temporary, encodePluginConfig(next), { mode: 0o600 }); + await NodeFSP.rename(temporary, profileFile); + }, + catch: (cause) => (cause instanceof Error ? cause.message : String(cause)), + }).pipe( + Effect.catch((error) => + Effect.logWarning("Antigravity's plugin switches are not copied into the profile.", { + error, + }), + ), + ); + }, +); From 49306ed4e10be59558b7bdba8f9b7186853ade00 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 02:05:07 +0200 Subject: [PATCH 36/36] fix(extensions): say where an Antigravity plugin's MCP connection signs in The live test showed agy loads a plugin MCP server that needs a sign-in (Canva's) only after its interactive /plugin manager signs it in, which neither `agy acp` nor `agy -p` does. An installed Antigravity plugin that lists MCP servers now says so on its page and its service row, instead of implying the connection works in Scient chats; its skills still do. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/i18n/translations/de.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/en.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/es.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/fr.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/ja.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/ko.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/pt-BR.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/ru.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/sv.json | 22 ++++++++++++++++++ apps/web/src/i18n/translations/zh.json | 22 ++++++++++++++++++ .../extensions/Extensions.browser.test.tsx | 11 +++++++++ .../scient/extensions/ProviderStorePages.tsx | 23 +++++++++++++++++++ .../src/scient/extensions/ServiceAgents.tsx | 6 +++-- docs/internals/scient-extensions.md | 8 +++++++ 14 files changed, 266 insertions(+), 2 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 92b5844fc2..36f07638db 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -15253,6 +15253,27 @@ "8f9c5620edf0a5dd": "Prüfen", "9dc4d06a2faa74dc": "Von Anthropic geprüft", "baae13041db7565a": "Von einem Partner geprüft", + "69bbad6aa5aa9457": [ + "Seine Verbindung zu ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " meldet sich nur im eigenen Plugin-Manager von Antigravity an (", + { + "t": "code", + "i": 2, + "c": "agy" + }, + " ausführen, ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + " öffnen), den Scient noch nicht öffnen kann; Scient-Chats nutzen daher seine Skills." + ], "533719cc42a36c38": "Entferne dieses Plugin im Plugin-Manager des Agenten.", "011876a86e46cc56": [ "Entferne dieses Plugin im Plugin-Manager von ", @@ -15310,6 +15331,7 @@ "c7b2fa0c1eb4415f": "Mit ChatGPT anmelden", "ab533b1faa64155e": "ChatGPT hinzufügen", "44b26795fc644218": "Wird eingeschaltet…", + "b2a91f20f10e5115": "Hinzugefügt · seine Verbindung meldet sich nur im Plugin-Manager von Antigravity an", "e077c767f4195050": "Hinzugefügt · meldet sich an, wenn ein Chat es zum ersten Mal nutzt", "b15c63066ebf4e6c": "Über sein Plugin aus dem Antigravity Marketplace", "1adafa7bf3950e49": "Über sein ChatGPT-Konto", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f88ea4a916..163e5cdad1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -15263,6 +15263,27 @@ "8f9c5620edf0a5dd": "Review", "9dc4d06a2faa74dc": "Reviewed by Anthropic", "baae13041db7565a": "Reviewed by a partner", + "69bbad6aa5aa9457": [ + "Its connection to ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " signs in only in Antigravity’s own plugin manager (run ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", open ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), which Scient can’t open yet, so Scient chats use its skills." + ], "533719cc42a36c38": "Remove this plugin in the agent’s plugin manager.", "011876a86e46cc56": [ "Remove this plugin in ", @@ -15321,6 +15342,7 @@ "c7b2fa0c1eb4415f": "Sign in with ChatGPT", "ab533b1faa64155e": "Add ChatGPT", "44b26795fc644218": "Turning on…", + "b2a91f20f10e5115": "Added · its connection signs in only in Antigravity’s own plugin manager", "e077c767f4195050": "Added · signs in the first time a chat uses it", "b15c63066ebf4e6c": "Through its Antigravity Marketplace plugin", "1adafa7bf3950e49": "Through its ChatGPT account", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index f522bd5726..e4ea8809ba 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -15245,6 +15245,27 @@ "8f9c5620edf0a5dd": "Revisar", "9dc4d06a2faa74dc": "Revisado por Anthropic", "baae13041db7565a": "Revisado por un socio", + "69bbad6aa5aa9457": [ + "Su conexión con ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " solo inicia sesión en el gestor de plugins de Antigravity (ejecuta ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", abre ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), que Scient aún no puede abrir, así que los chats de Scient usan sus skills." + ], "533719cc42a36c38": "Quita este plugin en el gestor de plugins del agente.", "011876a86e46cc56": [ "Quita este plugin en el gestor de plugins de ", @@ -15303,6 +15324,7 @@ "c7b2fa0c1eb4415f": "Iniciar sesión con ChatGPT", "ab533b1faa64155e": "Añadir ChatGPT", "44b26795fc644218": "Activando…", + "b2a91f20f10e5115": "Añadido · su conexión solo inicia sesión en el gestor de plugins de Antigravity", "e077c767f4195050": "Añadido · inicia sesión la primera vez que un chat lo usa", "b15c63066ebf4e6c": "Mediante su plugin de Antigravity Marketplace", "1adafa7bf3950e49": "A través de su cuenta de ChatGPT", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 295bea0e40..d667be49bd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -15250,6 +15250,27 @@ "8f9c5620edf0a5dd": "Vérification", "9dc4d06a2faa74dc": "Examiné par Anthropic", "baae13041db7565a": "Examiné par un partenaire", + "69bbad6aa5aa9457": [ + "Sa connexion à ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ne se connecte que dans le gestionnaire de plugins d’Antigravity (lancez ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", ouvrez ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), que Scient ne peut pas encore ouvrir ; les chats Scient utilisent donc ses skills." + ], "533719cc42a36c38": "Supprimez ce plugin dans le gestionnaire de plugins de l’agent.", "011876a86e46cc56": [ "Supprimez ce plugin dans le gestionnaire de plugins de ", @@ -15308,6 +15329,7 @@ "c7b2fa0c1eb4415f": "Se connecter avec ChatGPT", "ab533b1faa64155e": "Ajouter ChatGPT", "44b26795fc644218": "Activation…", + "b2a91f20f10e5115": "Ajouté · sa connexion ne se connecte que dans le gestionnaire de plugins d’Antigravity", "e077c767f4195050": "Ajouté · se connecte la première fois qu’un chat l’utilise", "b15c63066ebf4e6c": "Via son plugin de l’Antigravity Marketplace", "1adafa7bf3950e49": "Via son compte ChatGPT", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index bc0872a32b..8f6c2e3dc4 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -15180,6 +15180,27 @@ "8f9c5620edf0a5dd": "レビュー", "9dc4d06a2faa74dc": "Anthropic によるレビュー済み", "baae13041db7565a": "パートナーによるレビュー済み", + "69bbad6aa5aa9457": [ + "", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " への接続は Antigravity 自身のプラグインマネージャー(", + { + "t": "code", + "i": 2, + "c": "agy" + }, + " を実行し ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + " を開く)でのみサインインします。Scient はまだこれを開けないため、Scient のチャットではスキルのみを使います。" + ], "533719cc42a36c38": "エージェントのプラグインマネージャーでこのプラグインを削除してください。", "011876a86e46cc56": [ { @@ -15236,6 +15257,7 @@ "c7b2fa0c1eb4415f": "ChatGPT でサインイン", "ab533b1faa64155e": "ChatGPT を追加", "44b26795fc644218": "オンにしています…", + "b2a91f20f10e5115": "追加済み · 接続は Antigravity のプラグインマネージャーでのみサインインします", "e077c767f4195050": "追加済み · チャットで初めて使うときにサインインします", "b15c63066ebf4e6c": "Antigravity Marketplace のプラグイン経由", "1adafa7bf3950e49": "ChatGPT アカウント経由", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 487e32362b..83349e2cfb 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -15185,6 +15185,27 @@ "8f9c5620edf0a5dd": "검토", "9dc4d06a2faa74dc": "Anthropic이 검토함", "baae13041db7565a": "파트너가 검토함", + "69bbad6aa5aa9457": [ + "", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 연결은 Antigravity 자체 플러그인 관리자(", + { + "t": "code", + "i": 2, + "c": "agy" + }, + " 실행 후 ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + " 열기)에서만 로그인합니다. Scient는 아직 이를 열 수 없어 Scient 채팅은 스킬만 사용합니다." + ], "533719cc42a36c38": "에이전트의 플러그인 관리자에서 이 플러그인을 제거하세요.", "011876a86e46cc56": [ { @@ -15241,6 +15262,7 @@ "c7b2fa0c1eb4415f": "ChatGPT로 로그인", "ab533b1faa64155e": "ChatGPT 추가", "44b26795fc644218": "켜는 중…", + "b2a91f20f10e5115": "추가됨 · 연결은 Antigravity 플러그인 관리자에서만 로그인합니다", "e077c767f4195050": "추가됨 · 채팅에서 처음 사용할 때 로그인합니다", "b15c63066ebf4e6c": "Antigravity Marketplace 플러그인을 통해", "1adafa7bf3950e49": "ChatGPT 계정을 통해", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 8ac63feb84..b291032968 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -15249,6 +15249,27 @@ "8f9c5620edf0a5dd": "Revisar", "9dc4d06a2faa74dc": "Revisado pela Anthropic", "baae13041db7565a": "Revisado por um parceiro", + "69bbad6aa5aa9457": [ + "A conexão com ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " só faz login no gerenciador de plugins do Antigravity (execute ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", abra ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), que o Scient ainda não consegue abrir; por isso os chats do Scient usam as skills dele." + ], "533719cc42a36c38": "Remova este plugin no gerenciador de plugins do agente.", "011876a86e46cc56": [ "Remova este plugin no gerenciador de plugins de ", @@ -15307,6 +15328,7 @@ "c7b2fa0c1eb4415f": "Entrar com o ChatGPT", "ab533b1faa64155e": "Adicionar o ChatGPT", "44b26795fc644218": "Ativando…", + "b2a91f20f10e5115": "Adicionado · a conexão só faz login no gerenciador de plugins do Antigravity", "e077c767f4195050": "Adicionado · entra na primeira vez que um chat o usa", "b15c63066ebf4e6c": "Pelo plugin do Antigravity Marketplace", "1adafa7bf3950e49": "Pela conta do ChatGPT dele", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 72caf60201..39ffe7f5c5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -15250,6 +15250,27 @@ "8f9c5620edf0a5dd": "Проверка", "9dc4d06a2faa74dc": "Проверено Anthropic", "baae13041db7565a": "Проверено партнёром", + "69bbad6aa5aa9457": [ + "Подключение к ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " входит только через собственный менеджер плагинов Antigravity (запустите ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", откройте ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), который Scient пока не может открыть, поэтому чаты Scient используют только его навыки." + ], "533719cc42a36c38": "Удалите этот плагин в менеджере плагинов агента.", "011876a86e46cc56": [ "Удалите этот плагин в менеджере плагинов ", @@ -15308,6 +15329,7 @@ "c7b2fa0c1eb4415f": "Войти через ChatGPT", "ab533b1faa64155e": "Добавить ChatGPT", "44b26795fc644218": "Включение…", + "b2a91f20f10e5115": "Добавлен · подключение входит только через менеджер плагинов Antigravity", "e077c767f4195050": "Добавлено · вход выполняется при первом использовании в чате", "b15c63066ebf4e6c": "Через плагин из Antigravity Marketplace", "1adafa7bf3950e49": "Через свой аккаунт ChatGPT", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index df604df719..0d35619e6d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -15259,6 +15259,27 @@ "8f9c5620edf0a5dd": "Granska", "9dc4d06a2faa74dc": "Granskat av Anthropic", "baae13041db7565a": "Granskat av en partner", + "69bbad6aa5aa9457": [ + "Dess anslutning till ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " loggar bara in i Antigravitys egen pluginhanterare (kör ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ", öppna ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "), som Scient inte kan öppna än, så Scient-chattar använder dess skills." + ], "533719cc42a36c38": "Ta bort det här tillägget i agentens tilläggshanterare.", "011876a86e46cc56": [ "Ta bort det här tillägget i tilläggshanteraren för ", @@ -15317,6 +15338,7 @@ "c7b2fa0c1eb4415f": "Logga in med ChatGPT", "ab533b1faa64155e": "Lägg till ChatGPT", "44b26795fc644218": "Slår på…", + "b2a91f20f10e5115": "Tillagd · anslutningen loggar bara in i Antigravitys pluginhanterare", "e077c767f4195050": "Tillagd · loggar in första gången en chatt använder den", "b15c63066ebf4e6c": "Via sitt plugin från Antigravity Marketplace", "1adafa7bf3950e49": "Via sitt ChatGPT-konto", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index e3903e9c83..04eb1c57ef 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -15288,6 +15288,27 @@ "8f9c5620edf0a5dd": "查看", "9dc4d06a2faa74dc": "经 Anthropic 审核", "baae13041db7565a": "经合作伙伴审核", + "69bbad6aa5aa9457": [ + "它与 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 的连接只能在 Antigravity 自己的插件管理器中登录(运行 ", + { + "t": "code", + "i": 2, + "c": "agy" + }, + ",打开 ", + { + "t": "code", + "i": 3, + "c": "/plugin" + }, + "),Scient 暂时无法打开它,因此 Scient 聊天只使用它的技能。" + ], "533719cc42a36c38": "请在智能体的插件管理器中移除此插件。", "011876a86e46cc56": [ "请在 ", @@ -15346,6 +15367,7 @@ "c7b2fa0c1eb4415f": "使用 ChatGPT 登录", "ab533b1faa64155e": "添加 ChatGPT", "44b26795fc644218": "正在开启…", + "b2a91f20f10e5115": "已添加 · 其连接只能在 Antigravity 的插件管理器中登录", "e077c767f4195050": "已添加 · 聊天首次使用时登录", "b15c63066ebf4e6c": "通过其 Antigravity Marketplace 插件", "1adafa7bf3950e49": "通过其 ChatGPT 账户", diff --git a/apps/web/src/scient/extensions/Extensions.browser.test.tsx b/apps/web/src/scient/extensions/Extensions.browser.test.tsx index ff4150ef22..4eb7c2b05b 100644 --- a/apps/web/src/scient/extensions/Extensions.browser.test.tsx +++ b/apps/web/src/scient/extensions/Extensions.browser.test.tsx @@ -2649,6 +2649,17 @@ describe("Antigravity Marketplace", () => { ); expect(agents.textContent).not.toContain("Connected"); + // A plugin whose MCP server agy signs in only in its own plugin manager says so. + agents = await show( + { plugins: [added(true)] }, + { ...gmail, installed: true, includes: ["Skills", "MCP servers"] }, + ); + await vi.waitFor(() => + expect(agents.textContent).toContain( + "Added · its connection signs in only in Antigravity’s own plugin manager", + ), + ); + agents = await show({ plugins: [added(false)] }); await vi.waitFor(() => expect(agents.textContent).toContain("Off in Antigravity")); await userEvent.click(buttonIn(agents, "Turn on")!); diff --git a/apps/web/src/scient/extensions/ProviderStorePages.tsx b/apps/web/src/scient/extensions/ProviderStorePages.tsx index 1ab89d3c88..7025f43122 100644 --- a/apps/web/src/scient/extensions/ProviderStorePages.tsx +++ b/apps/web/src/scient/extensions/ProviderStorePages.tsx @@ -61,6 +61,26 @@ function ThirdPartyNotice({ entry }: { readonly entry: ProviderStoreEntry }) { return {useThirdPartyNoticeText(entry)}; } +/** + * agy loads a plugin's MCP servers only once they are signed in through its own plugin manager, + * which Scient can't drive; its chats here get the skills until then. + */ +export function needsAntigravityConnectionSignIn(entry: ProviderStoreEntry) { + return entry.kind === "antigravity" && entry.installed && entry.includes.includes("MCP servers"); +} + +function AntigravityConnectionSignIn({ entry }: { readonly entry: ProviderStoreEntry }) { + return ( + + + Its connection to {entry.displayName} signs in only in Antigravity’s own plugin + manager (run agy, open /plugin), which Scient can’t open yet, so + Scient chats use its skills. + + + ); +} + export function StoreInstall({ provider, entry, @@ -578,6 +598,9 @@ function StoreDetail({ > {entry.disabledReason ? {entry.disabledReason} : null} {isThirdPartyPlugin(entry) && !entry.installed ? : null} + {needsAntigravityConnectionSignIn(entry) ? ( + + ) : null} {route.label} {state === "added" - ? gt("Added · signs in the first time a chat uses it") + ? entry.data && needsAntigravityConnectionSignIn(entry.data) + ? gt("Added · its connection signs in only in Antigravity’s own plugin manager") + : gt("Added · signs in the first time a chat uses it") : state === "add" && entry.data?.disabledReason ? entry.data.disabledReason : gt("Through its Antigravity Marketplace plugin")} diff --git a/docs/internals/scient-extensions.md b/docs/internals/scient-extensions.md index 39efa32dc2..595aa41ed3 100644 --- a/docs/internals/scient-extensions.md +++ b/docs/internals/scient-extensions.md @@ -990,6 +990,14 @@ enable/disable and Remove use `agy plugin list --json`, `enable|disable` and `uninstall`. A catalog outage keeps Installed and Remove; an unreadable listing pauses Add and Remove. A paired-harness instance lists the catalogs with Add disabled and says why. +Live check (agy 1.5.12, 2026-11-22): a plugin MCP server that needs a sign-in +(Canva's) does not load in `agy acp` or `agy -p`, which log "Not reloading plugin +MCP servers: cannot get the signed-in user"; agy signs those in only in its +interactive `/plugin` manager, which Scient cannot drive. Skills and CLI plugins +that sign in through `auth.json` (Google's) work in Scient chats. An installed +plugin listing MCP servers therefore says where its connection signs in, and its +service row does not claim the connection works. + `providerPlugins.act` accepts `install` (entry id, with an optional source instance for shared stores), `add-official-store`, and the existing lifecycle operations. Codex installation calls `plugin/install { pluginName,