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 \ diff --git a/UPSTREAM.md b/UPSTREAM.md index ccbe698846..36c1ab63a9 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 @@ -2607,6 +2609,23 @@ predicate. Tested in `ThreadLaunchService.scient.test.ts` and `EmptyRepositoryWo T3 main has the same launch, save and wait code, so this is offered upstream; when T3 takes an equal change, use its version and delete the blocks, modules and tests. +## MCP sign-in from a chat notice + +T3's #39921 signs an agent's MCP server in from its notice and finishes only with a pasted callback +address. Scient makes `ProviderMcpSignInCompleteInput.callbackUrl` optional: without it, Codex's +`complete` waits up to five minutes for `mcpServer/oauthLogin/completed`, Claude's succeeds only +when the server is already connected, and `McpSignInAction` starts that wait when it opens the +page. `McpSignIn` refreshes the provider instance after a sign-in so Extensions updates. All edits +carry SCIENT-FORK markers; tests are `CodexAdapterV2.mcpSignIn.scient.test.ts`, +`McpSignIn.scient.test.ts` and `McpSignInAction.scient.browser.test.tsx`. The same change suits T3 +and can be offered upstream; when T3 finishes local sign-ins itself, take its version and delete +the blocks and tests. + +Antigravity plugin sign-in reuses that notice slot with a Scient `pluginSignIn` field on +`system_notice`, Scient's `scient.pluginSignIn.open` RPC, the ACP flavor hooks `scientToolNotice` +and `scientPluginSignIn`, and `ProviderAdapterV2SessionRuntime.scientPluginSignIn`; see the Antigravity +section of `docs/internals/scient-extensions.md`. + ## Security policy `.github/SECURITY.md` is Scient's: reports go to Scient's address or a private advisory on 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/mcpApps/McpSignIn.scient.test.ts b/apps/server/src/mcpApps/McpSignIn.scient.test.ts new file mode 100644 index 0000000000..6dcfac8718 --- /dev/null +++ b/apps/server/src/mcpApps/McpSignIn.scient.test.ts @@ -0,0 +1,67 @@ +import { assert, it } from "@effect/vitest"; +import { + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ThreadId, +} from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as McpSignIn from "./McpSignIn.ts"; + +const instanceId = ProviderInstanceId.make("codex-chat-sign-in"); +const providerThread = { + id: ProviderThreadId.make("provider-thread-chat-sign-in"), + providerInstanceId: instanceId, + providerSessionId: ProviderSessionId.make("provider-session-chat-sign-in"), +}; +const input = { + threadId: ThreadId.make("thread-chat-sign-in"), + providerThreadId: providerThread.id, + server: "linear", +}; + +it.effect("refreshes the instance's inventory after a chat sign-in finishes", () => + Effect.gen(function* () { + const refreshed = yield* Deferred.make(); + const completed: Array = []; + const layer = McpSignIn.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed({ providerThreads: [providerThread] }) as never, + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + get: () => + Effect.succeed( + Option.some({ + mcpSignIn: { + start: () => Effect.succeed({ authorizationUrl: "https://linear.example/a" }), + complete: ({ callbackUrl }: { readonly callbackUrl: string | undefined }) => + Effect.sync(() => { + completed.push(callbackUrl); + }), + }, + }) as never, + ), + }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + refreshInstance: (id) => Deferred.succeed(refreshed, id).pipe(Effect.as([])), + }), + ), + ), + ); + yield* Effect.gen(function* () { + const signIn = yield* McpSignIn.McpSignIn; + yield* signIn.complete(input); + assert.deepEqual(completed, [undefined]); + assert.strictEqual(yield* Deferred.await(refreshed), instanceId); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/mcpApps/McpSignIn.ts b/apps/server/src/mcpApps/McpSignIn.ts index 56072d1c71..db47ce0cb8 100644 --- a/apps/server/src/mcpApps/McpSignIn.ts +++ b/apps/server/src/mcpApps/McpSignIn.ts @@ -1,4 +1,5 @@ import { + type ProviderInstanceId, ProviderMcpSignInError, type ProviderMcpSignInCompleteInput, type ProviderMcpSignInCompleteResult, @@ -15,6 +16,9 @@ import * as Schema from "effect/Schema"; import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +// SCIENT-FORK:START — a chat sign-in refreshes the instance's Extensions inventory. +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +// SCIENT-FORK:END /** * Signs an agent's MCP server in through the session that reported it needs @@ -37,6 +41,14 @@ const isSignInError = Schema.is(ProviderMcpSignInError); const make = Effect.gen(function* () { const threadManagement = yield* ThreadManagementService.ThreadManagementService; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + // SCIENT-FORK:START — the agent keeps the new credential; re-read the servers it lists. + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + const serviceScope = yield* Effect.scope; + const refreshInventory = (providerThread: { readonly providerInstanceId: ProviderInstanceId }) => + providerRegistry + .refreshInstance(providerThread.providerInstanceId) + .pipe(Effect.ignore, Effect.forkIn(serviceScope), Effect.asVoid); + // SCIENT-FORK:END const fail = (server: string, detail: string) => new ProviderMcpSignInError({ server, detail }); const stopped = (server: string) => @@ -80,6 +92,8 @@ const make = Effect.gen(function* () { providerThread, server: input.server, }); + // SCIENT-FORK: see refreshInventory. + if (authorizationUrl === null) yield* refreshInventory(providerThread); return { authorizationUrl, signedInAt: authorizationUrl === null ? DateTime.formatIso(yield* DateTime.now) : null, @@ -99,6 +113,8 @@ const make = Effect.gen(function* () { server: input.server, callbackUrl: input.callbackUrl, }); + // SCIENT-FORK: see refreshInventory. + yield* refreshInventory(providerThread); return { signedInAt: DateTime.formatIso(yield* DateTime.now) }; }, (effect, input) => 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..985c0fe4ee --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.scient.test.ts @@ -0,0 +1,302 @@ +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 FileSystem from "effect/FileSystem"; +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"); + +/** 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 { events, notices, session, providerThread, threadId } = yield* runChallengeTurn({ + command: "gmail readonly search --max 3", + manifestClientId: "synthetic-client.example", + }); + const serialized = JSON.stringify(events); + assert.notInclude(serialized, STATE); + assert.notInclude(serialized, "synthetic-challenge"); + 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.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 899afbf3f9..fcdbbd608f 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,10 @@ 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"; +import { verifyPluginSignIn } from "../../scient/antigravity/pluginAuthManifest.ts"; +// SCIENT-FORK:END import { AcpProviderCapabilitiesV2, makeAcpAdapterV2, @@ -110,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 } /** @@ -152,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(); @@ -165,11 +176,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 +224,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 +257,41 @@ 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 { notifications, candidate } = pluginSignIns.observe({ + generation, + notification: reads.repair(notification), + }); + // 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 + ), ); }, start: () => @@ -367,6 +427,25 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, + // SCIENT-FORK:START — plugin sign-in notices and the pages they open. + scientToolNotice: (sessionId, toolCallId, owner) => + pluginSignIns.takeToolNotice(sessionId, 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, @@ -406,9 +485,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/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 9e1b870c65..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,6 +15919,27 @@ 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 — 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.", + ); + } + // 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/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/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 6edf2071ab..1b46f1a80c 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -88,6 +88,9 @@ import { } from "./ScientAntigravityDriver.ts"; export { usesLegacyAntigravityBackend } from "./ScientAntigravityDriver.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — Antigravity Marketplace plugins through the instance's agy CLI. +import { makeAntigravityInstancePlugins } from "../../scient/extensions/AntigravityProviderStore.ts"; +// SCIENT-FORK:END import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts"; import { LegacyAntigravityDriver, @@ -284,6 +287,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), @@ -707,6 +711,20 @@ export const AntigravityDriver: ScientProviderDriver< }); // SCIENT-FORK:END + // SCIENT-FORK:START — Antigravity Marketplace plugins through the instance's agy CLI. + const plugins = yield* makeAntigravityInstancePlugins({ + installation, + binaryPath: settings.binaryPath, + environment: processEnvironment, + stateDir: host.paths.stateDir, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + // SCIENT-FORK:END + // SCIENT-FORK:START — a read started before a runtime install must not publish its older // list after the post-install read, so catalog reads take turns. const refreshGate = yield* Semaphore.make(1); @@ -795,6 +813,10 @@ export const AntigravityDriver: ScientProviderDriver< auth: authFlow.controller, connectionActions, managedRuntimeActions, + // SCIENT-FORK:START — Antigravity Marketplace plugins through the instance's agy CLI. + pluginActions: plugins.actions, + nativeInventoryChanges: plugins.reports, + // SCIENT-FORK:END // SCIENT-FORK: catalog reads take turns (see refreshGate). refreshModels: () => refreshGate.withPermits(1)(refreshModels()), } satisfies ScientProviderInstance; 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")); } diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index d069daf88b..100d4db020 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, + linkAntigravityUserPlugins, +} 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 reads the user's plugins through a link; paired runtimes get a 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 + ? linkAntigravityUserPlugins({ profileDirectory: geminiHome, userHome, platform }) + : projectAntigravityPluginSkills({ profileDirectory: geminiHome, userHome, platform }); + // SCIENT-FORK:END return profile; }); 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/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 new file mode 100644 index 0000000000..580eb1fc10 --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginSignIn.test.ts @@ -0,0 +1,490 @@ +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, + plainCommandProgram, + type PluginSignInCandidate, +} 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, the loopback sign-in page and its OAuth client", () => { + const challenge = extractPluginSignInChallenge(challengeText()); + 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([ + ["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://"))], + [ + "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}`, ""))], + ["no client", challengeText(URL_OK.replace("client_id=synthetic-client.example&", ""))], + ["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(); + }); +}); + +describe("extractToolCallChallenge", () => { + const output = challengeText(); + it("reads a tool result whose fields repeat the same text", () => { + expect( + extractToolCallChallenge({ + inputs: ["gmail readonly search", { CommandLine: "gmail readonly search" }], + outputs: [ + { output, exit_code: 1 }, + [{ type: "content", content: { type: "text", text: output } }], + ], + })?.plugin, + ).toBe("gmail"); + }); + + it("refuses a challenge the call's own input wrote", () => { + expect( + extractToolCallChallenge({ + inputs: ["echo", { CommandLine: `echo '${output}'` }], + outputs: [{ output }], + }), + ).toBeUndefined(); + }); + + it("refuses fields that disagree on the page", () => { + expect( + extractToolCallChallenge({ + 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", () => { + 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 = () => ({ secrets: [], cards: [card()] }); + 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"), +}; +type ToolUpdate = Extract; +const toolUpdate = ( + toolCallId: string, + 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 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: 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(""); + +describe("makeAntigravityPluginSignIns", () => { + const setup = (options?: { ttlMs?: number }) => { + const signIns = makeAntigravityPluginSignIns(options); + const generation = signIns.openGeneration(); + let ids = 0; + 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 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("session-1", "call-1", owner)?.pluginSignIn).toEqual({ + attemptId: "attempt-1", + plugin: "gmail", + displayName: "Gmail", + }); + 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 }); + }); + + // 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(); + 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("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("session-1", "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, admit } = setup({ ttlMs: 1_000 }); + admit(observe(challengeUpdate()).candidate); + 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" }); + 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 { candidate } = observe(textChunk(challengeText())); + expect(candidate).toBeUndefined(); + expect(signIns.takeToolNotice("session-1", "call-1", owner)).toBeUndefined(); + }); + + it("scrubs a repeated page across chunks and hides the repeated card", () => { + 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))).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`); + }); + + // 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`); + }); + + // 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`); + }); + + // 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("session-1", "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("session-1", "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, admit } = setup(); + admit(observe(challengeUpdate()).candidate); + signIns.takeToolNotice("session-1", "call-1", owner); + const second = challengeText(signInUrl({ state: "second-state" })); + admit( + observe( + toolUpdate("call-3", { + status: "completed", + kind: "execute", + rawInput: gmailRun, + rawOutput: { output: second }, + }), + ).candidate, + ); + signIns.takeToolNotice("session-1", "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..bf1c7b1d10 --- /dev/null +++ b/apps/server/src/scient/antigravity/pluginSignIn.ts @@ -0,0 +1,782 @@ +/** + * 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 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]"]); +// 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", + 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; + /** 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; +} + +const single = (params: URLSearchParams, name: string) => { + const values = params.getAll(name); + return values.length === 1 ? values[0] : undefined; +}; + +const parseUrl = (value: string) => { + try { + 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 !== "" + ) { + 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; + } + 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) || + 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 plugin = CARD_PATTERN.exec(text)?.[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, + endpoint: `${url.origin}${url.pathname}`, + clientId: url.searchParams.get("client_id")!, + secrets: secrets.filter((value): value is string => Predicate.isString(value) && value !== ""), + }; +} + +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)) { + 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); + } +} + +/** 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 scrubSignInText(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 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 inputs: ReadonlyArray; + readonly outputs: ReadonlyArray; +}): PluginSignInChallenge | undefined { + const inputs: Array = []; + collectStrings(update.inputs, inputs); + if (inputs.some((text) => text.includes("plugin-card"))) return undefined; + const outputs: Array = []; + collectStrings(update.outputs, 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; +} + +/** 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 text without completing it. */ +function partialStart(buffer: string, texts: ReadonlyArray): number { + let earliest = -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 (text.startsWith(text === text.toLowerCase() ? lower.slice(index) : buffer.slice(index))) { + earliest = index; + break; + } + } + } + return earliest; +} + +/** + * 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: () => { + readonly secrets: ReadonlyArray; + readonly cards: ReadonlyArray; + }, +) { + let carry = ""; + let previous = "\n"; + 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); + } + } + 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; + } + } + } + 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), + flush: () => { + const held = carry; + carry = ""; + return held.length === 0 ? "" : process(held, true); + }, + }; +} + +export interface PluginSignInOwner { + readonly threadId: ThreadId; + 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 sessionId: string; + readonly generation: number; + readonly expiresAt: number; + owner: PluginSignInOwner | undefined; + live: boolean; + 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 { + readonly title: string; + readonly message: string; + readonly level: "warning" | "info"; + readonly pluginSignIn: OrchestrationV2PluginSignIn; +} + +type Notification = EffectAcpSchema.SessionNotification; +/** 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; + 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; +}; + +const isTerminal = (status: string | null | undefined) => + status === "completed" || status === "failed"; + +/** + * 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: { + 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; + 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>(); + // 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) => () => ({ + secrets: secretsBySession.get(sessionId) ?? [], + cards: [...attempts.values()] + .filter((attempt) => attempt.sessionId === sessionId && attempt.live) + .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); + secretsBySession.set(sessionId, known.slice(-32)); + }; + + /** 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.startsWith(prefix) || !ends(key.slice(prefix.length))) continue; + redactors.delete(key); + terminalPending.delete(key); + const text = entry.redactor.flush(); + if (text.length === 0) continue; + flushed.push(entry.rebuild(text)); + } + return flushed; + }; + + 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)), rebuild }; + redactors.set(key, entry); + } + 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); + 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 { + 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`, 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 notifications: ReadonlyArray; + readonly candidate: PluginSignInCandidate | undefined; + } => { + 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" + ) { + return { + notifications: streamChunk( + notification, + update.sessionUpdate, + update.content.text, + (text) => ({ + ...notification, + update: { ...update, content: { ...update.content, text } }, + }), + ), + 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") { + 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, + (text) => ({ + ...notification, + update: { ...update, content: { ...content, content: { ...content.content, text } } }, + }), + ), + candidate: undefined, + }; + } + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { + return { notifications: [notification], candidate: undefined }; + } + // 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) => 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) { + 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, + program, + challenge, + }; + } + } else if (update.status === "completed" && exitCodeOf(update.rawOutput) === 0) { + const program = command === undefined ? undefined : plainCommandProgram(command); + const waiting = [...attempts.values()] + .toReversed() + .find( + (attempt) => + attempt.sessionId === sessionId && + !attempt.signedIn && + program !== undefined && + attempt.programs.includes(program), + ); + if (waiting !== undefined) { + waiting.signedIn = true; + waiting.live = false; + pendingNotices.set(noticeKey(sessionId, update.toolCallId), { + attemptId: waiting.id, + signedIn: true, + }); + } + } + 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(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) => + [...sessionGenerations] + .filter(([, owner]) => owner === generation) + .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 key = noticeKey(sessionId, toolCallId); + const pending = pendingNotices.get(key); + if (pending === undefined) return undefined; + pendingNotices.delete(key); + const attempt = attempts.get(pending.attemptId); + if (attempt === undefined) return undefined; + attempt.owner ??= owner; + const name = attempt.displayName ?? attempt.plugin; + const pluginSignIn = { + attemptId: attempt.id, + plugin: attempt.plugin, + ...(attempt.displayName === undefined ? {} : { displayName: attempt.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/scient/extensions/AntigravityPluginArchive.test.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts new file mode 100644 index 0000000000..42f85122aa --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.test.ts @@ -0,0 +1,150 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { + checkStagedManifest, + extractAntigravityArchive, + isAntigravityPluginArchiveError, +} from "./AntigravityPluginArchive.ts"; +import { makeZip, renameInZip } from "./AntigravityPluginArchive.testkit.ts"; + +const extract = (zip: Buffer) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const archive = path.join(root, "plugin.zip"); + const target = path.join(root, "plugin"); + yield* fs.writeFile(archive, zip); + yield* fs.makeDirectory(target); + const result = yield* extractAntigravityArchive(archive, target).pipe(Effect.result); + return { result, target, fs, path }; + }); + +const refusal = (zip: Effect.Effect) => + Effect.scoped( + Effect.gen(function* () { + const { result, target, fs } = yield* extract(yield* zip); + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") { + expect(isAntigravityPluginArchiveError(result.failure)).toBe(true); + expect(result.failure.reason).toBe("unsafe-archive"); + } + return yield* fs.readDirectory(target, { recursive: true }); + }), + ).pipe(Effect.provide(NodeServices.layer)); + +describe("extractAntigravityArchive", () => { + it.effect("unpacks plain files and keeps executable bits", () => + Effect.scoped( + Effect.gen(function* () { + const { result, target, fs, path } = yield* extract( + yield* makeZip([ + { name: "plugin.json", data: '{"name":"gmail"}' }, + { name: "skills/", directory: true }, + { name: "skills/gmail/scripts/gmail", data: "#!/bin/sh", mode: 0o100755 }, + ]), + ); + expect(result._tag).toBe("Success"); + const script = yield* fs.stat(path.join(target, "skills", "gmail", "scripts", "gmail")); + expect(Number(script.mode) & 0o111).not.toBe(0); + const manifest = yield* fs.stat(path.join(target, "plugin.json")); + expect(Number(manifest.mode) & 0o111).toBe(0); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("refuses links", () => + Effect.gen(function* () { + const written = yield* refusal( + makeZip([ + { name: "a.txt", data: "a" }, + { name: "link", data: "/etc/passwd", mode: 0o120777 }, + ]), + ); + expect(written).not.toContain("link"); + }), + ); + + it.effect("refuses special files", () => + refusal(makeZip([{ name: "pipe", mode: 0o010644 }])).pipe(Effect.asVoid), + ); + + it.effect("refuses names that leave the folder", () => + refusal( + makeZip([{ name: "zz/evil.txt", data: "x" }]).pipe( + Effect.map((zip) => renameInZip(zip, "zz/evil.txt", "../evil.txt")), + ), + ).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([ + { name: "Skill.md", data: "one" }, + { name: "skill.md", data: "two" }, + ]), + ).pipe(Effect.asVoid), + ); + + it.effect("refuses an archive larger than its unpacked limit", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const archive = path.join(root, "plugin.zip"); + yield* fs.writeFile( + archive, + yield* makeZip([ + { name: "a", data: "x".repeat(600) }, + { name: "b", data: "x".repeat(600) }, + ]), + ); + yield* fs.makeDirectory(path.join(root, "plugin")); + const result = yield* extractAntigravityArchive(archive, path.join(root, "plugin"), { + unpackedBytes: 1_000, + }).pipe(Effect.flip); + expect(result.reason).toBe("unsafe-archive"); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); + +describe("checkStagedManifest", () => { + it.effect("requires the catalog's name and version", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString( + path.join(root, "plugin.json"), + '{"name":"gmail","version":"0.0.7"}', + ); + yield* checkStagedManifest(root, { name: "gmail", version: "0.0.7" }); + yield* checkStagedManifest(root, { name: "gmail" }); + const wrongName = yield* checkStagedManifest(root, { name: "gdrive" }).pipe(Effect.flip); + expect(wrongName.reason).toBe("manifest"); + const wrongVersion = yield* checkStagedManifest(root, { + name: "gmail", + version: "0.0.8", + }).pipe(Effect.flip); + expect(wrongVersion.reason).toBe("manifest"); + yield* fs.remove(path.join(root, "plugin.json")); + expect((yield* checkStagedManifest(root, { name: "gmail" }).pipe(Effect.flip)).reason).toBe( + "manifest", + ); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/scient/extensions/AntigravityPluginArchive.testkit.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.testkit.ts new file mode 100644 index 0000000000..8fbad6f3be --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.testkit.ts @@ -0,0 +1,29 @@ +// @effect-diagnostics nodeBuiltinImport:off -- test archives are built in memory. +import * as NodeStreamConsumers from "node:stream/consumers"; +import * as Effect from "effect/Effect"; +import * as yazl from "yazl"; + +export interface ZipMember { + readonly name: string; + readonly data?: string; + readonly mode?: number; + readonly directory?: boolean; +} + +export const makeZip = (members: ReadonlyArray) => + Effect.promise(() => { + const zip = new yazl.ZipFile(); + for (const member of members) { + if (member.directory) zip.addEmptyDirectory(member.name, { mode: member.mode ?? 0o40755 }); + else + zip.addBuffer(Buffer.from(member.data ?? ""), member.name, { + mode: member.mode ?? 0o100644, + }); + } + zip.end(); + return NodeStreamConsumers.buffer(zip.outputStream); + }); + +/** yazl refuses unsafe names, so a same-length safe name is rewritten in the finished bytes. */ +export const renameInZip = (zip: Buffer, from: string, to: string) => + Buffer.from(zip.toString("latin1").split(from).join(to), "latin1"); diff --git a/apps/server/src/scient/extensions/AntigravityPluginArchive.ts b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts new file mode 100644 index 0000000000..fb71a65b15 --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityPluginArchive.ts @@ -0,0 +1,280 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the archive is hashed as it streams in. +/** + * Stages one catalog plugin for `agy plugin install `: the archive the catalog names is + * downloaded from gstatic, checked against the catalog's SHA-256 before it is opened, unpacked + * without links, special files or paths outside the folder, and its manifest must name the plugin. + */ +import * as NodeCrypto from "node:crypto"; + +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 * as Stream from "effect/Stream"; +import { HttpClient } from "effect/http"; +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, + entries: 20_000, + manifestBytes: 256 * 1024, + depth: 32, +}; + +export class AntigravityPluginArchiveError extends Schema.TaggedError()( + "AntigravityPluginArchiveError", + { + reason: Schema.Literals(["download", "checksum", "unsafe-archive", "manifest"]), + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail; + } +} +export const isAntigravityPluginArchiveError = Schema.is(AntigravityPluginArchiveError); +const archiveError = + (reason: AntigravityPluginArchiveError["reason"], detail: string) => (cause?: unknown) => + new AntigravityPluginArchiveError({ reason, detail, cause }); +const unsafe = (detail: string) => archiveError("unsafe-archive", detail)(); + +const Manifest = Schema.Struct({ + name: Schema.String, + version: Schema.optional(Schema.NullOr(Schema.String)), +}); +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest)); + +/** Downloads and checks the archive in memory; nothing reaches disk unless the digest matches. */ +const downloadAntigravityArchive = Effect.fn("AntigravityPluginArchive.download")( + function* (archive: { readonly url: string; readonly sha256: string }) { + if (!isAntigravityGstaticUrl(archive.url)) + return yield* archiveError("download", "This plugin's download is not on Google's host.")(); + const http = yield* HttpClient.HttpClient; + const failed = archiveError("download", "Scient could not download this plugin."); + const response = yield* getGstatic(http, archive.url, "application/zip").pipe( + Effect.mapError(failed), + ); + if (response.status !== 200) return yield* failed(); + const declared = Number(response.headers["content-length"]); + if (Number.isFinite(declared) && declared > ARCHIVE_LIMITS.archiveBytes) + return yield* archiveError("download", "This plugin's download is larger than 64 MB.")(); + const hash = NodeCrypto.createHash("sha256"); + const chunks: Uint8Array[] = []; + let bytes = 0; + yield* response.stream.pipe( + Stream.mapError(failed), + Stream.runForEach((chunk) => { + bytes += chunk.length; + if (bytes > ARCHIVE_LIMITS.archiveBytes) + return archiveError("download", "This plugin's download is larger than 64 MB.")(); + hash.update(chunk); + chunks.push(chunk); + return Effect.void; + }), + ); + if (hash.digest("hex") !== archive.sha256.toLowerCase()) + return yield* archiveError( + "checksum", + "The downloaded plugin doesn't match the checksum its catalog lists, so Scient didn't add it.", + )(); + return Buffer.concat(chunks); + }, + (effect) => + Effect.timeoutOrElse(effect, { + duration: "3 minutes", + orElse: () => + Effect.fail( + new AntigravityPluginArchiveError({ + reason: "download", + detail: "The plugin took too long to download.", + }), + ), + }), +); + +const UNIX_FILE_TYPE = 0o170000; +const UNIX_REGULAR = 0o100000; +const UNIX_DIRECTORY = 0o040000; + +/** Relative, forward-slash names only; every segment a plain name on every platform. */ +function memberSegments(fileName: string): ReadonlyArray | undefined { + const directory = fileName.endsWith("/"); + const segments = (directory ? fileName.slice(0, -1) : fileName).split("/"); + if ( + fileName.length > 1024 || + segments.length > ARCHIVE_LIMITS.depth || + segments.some( + (segment) => + segment === "" || + segment === "." || + segment === ".." || + segment.length > 255 || + /[\u0000-\u001f\\:*?"<>|]/.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; + return segments; +} + +/** + * Unpacks `archivePath` into the empty folder `target`. Executable bits are kept; anything that + * is not a plain file or folder, or that would land outside `target` or on another member, fails. + */ +export const extractAntigravityArchive = Effect.fn("AntigravityPluginArchive.extract")(function* ( + archivePath: string, + target: string, + limits: Partial = {}, +) { + const { entries, unpackedBytes } = { ...ARCHIVE_LIMITS, ...limits }; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = path.resolve(target); + yield* Effect.scoped( + Effect.gen(function* () { + const archive = yield* openZipArchive(archivePath, (detail, cause) => + archiveError("unsafe-archive", `The plugin archive could not be read: ${detail}`)(cause), + ); + if (archive.entryCount > entries) + return yield* unsafe("The plugin archive has too many files."); + const claimed = new Set(); + let total = 0; + for (;;) { + const entry: Yauzl.Entry | null = yield* archive.next; + if (entry === null) break; + const segments = memberSegments(entry.fileName); + if (!segments) return yield* unsafe("The plugin archive has a file outside its folder."); + if (entry.isEncrypted()) return yield* unsafe("The plugin archive is encrypted."); + const madeOnUnix = entry.versionMadeBy >> 8 === 3; + const mode = madeOnUnix ? entry.externalFileAttributes >>> 16 : 0; + const type = mode & UNIX_FILE_TYPE; + const isDirectory = entry.fileName.endsWith("/"); + if ( + (type !== 0 && type !== UNIX_REGULAR && type !== UNIX_DIRECTORY) || + (type === UNIX_DIRECTORY && !isDirectory) || + (type === UNIX_REGULAR && isDirectory) + ) + return yield* unsafe("The plugin archive has links or special files."); + // Case- and form-insensitive, as macOS and Windows folders compare names. + const key = segments.join("/").normalize("NFC").toLowerCase(); + const destination = path.join(root, ...segments); + if (!destination.startsWith(`${root}${path.sep}`)) + return yield* unsafe("The plugin archive has a file outside its folder."); + if (isDirectory) { + if (claimed.has(`file:${key}`)) + return yield* unsafe("The plugin archive has two members with one name."); + claimed.add(`dir:${key}`); + yield* fs.makeDirectory(destination, { recursive: true }); + continue; + } + if (claimed.has(`file:${key}`) || claimed.has(`dir:${key}`)) + return yield* unsafe("The plugin archive has two members with one name."); + claimed.add(`file:${key}`); + total += entry.uncompressedSize; + if (total > unpackedBytes) + return yield* unsafe("The plugin is larger than 256 MB unpacked."); + const readable = yield* archive.streamEntry(entry); + const contents = yield* Effect.tryPromise({ + try: async () => { + const parts: Buffer[] = []; + let size = 0; + for await (const chunk of readable) { + size += (chunk as Buffer).length; + if (size > entry.uncompressedSize) throw new Error("member larger than declared"); + parts.push(chunk as Buffer); + } + return Buffer.concat(parts); + }, + catch: archiveError("unsafe-archive", "A file in the plugin archive could not be read."), + }); + yield* fs.makeDirectory(path.dirname(destination), { recursive: true }); + yield* fs.writeFile(destination, contents, { + flag: "wx", + mode: (mode & 0o111) !== 0 ? 0o755 : 0o644, + }); + } + }), + ).pipe( + Effect.mapError((cause) => + isAntigravityPluginArchiveError(cause) + ? cause + : archiveError("unsafe-archive", "The plugin archive could not be unpacked.")(cause), + ), + ); +}); + +/** The unpacked plugin's own manifest must be the catalog's plugin, at the catalog's version. */ +export const checkStagedManifest = Effect.fn("AntigravityPluginArchive.checkManifest")(function* ( + directory: string, + expected: { readonly name: string; readonly version?: string | undefined }, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const file = path.join(directory, "plugin.json"); + const missing = archiveError("manifest", "The plugin archive has no readable plugin.json."); + const info = yield* fs.stat(file).pipe(Effect.mapError(missing)); + if (info.type !== "File" || Number(info.size) > ARCHIVE_LIMITS.manifestBytes) + return yield* missing(); + const manifest = yield* fs + .readFileString(file) + .pipe(Effect.flatMap(decodeManifest), Effect.mapError(missing)); + if (manifest.name !== expected.name) + return yield* archiveError( + "manifest", + "The downloaded plugin names a different plugin than its catalog entry.", + )(); + if ( + expected.version !== undefined && + typeof manifest.version === "string" && + manifest.version.trim() !== expected.version + ) + return yield* archiveError( + "manifest", + "The downloaded plugin is a different version than its catalog lists. Refresh and try again.", + )(); +}); + +/** + * A checked, unpacked copy of the plugin in a private folder under `stagingRoot`, removed when the + * scope closes whatever happened. + */ +export const stageAntigravityPlugin = Effect.fn("AntigravityPluginArchive.stage")( + function* (input: { + readonly name: string; + readonly version?: string | undefined; + readonly archive: { readonly url: string; readonly sha256: string }; + readonly stagingRoot: string; + }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bytes = yield* downloadAntigravityArchive(input.archive); + yield* fs.makeDirectory(input.stagingRoot, { recursive: true, mode: 0o700 }); + const staging = yield* Effect.acquireRelease( + fs.makeTempDirectory({ directory: input.stagingRoot, prefix: "add-" }), + (directory) => + fs + .remove(directory, { recursive: true, force: true }) + .pipe( + Effect.catch(() => + Effect.logWarning("Could not remove an Antigravity plugin staging folder."), + ), + ), + ); + const archivePath = path.join(staging, "plugin.zip"); + const pluginDirectory = path.join(staging, input.name); + yield* fs.writeFile(archivePath, bytes, { flag: "wx", mode: 0o600 }); + yield* fs.makeDirectory(pluginDirectory); + yield* extractAntigravityArchive(archivePath, pluginDirectory); + yield* checkStagedManifest(pluginDirectory, input); + return pluginDirectory; + }, +); diff --git a/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts new file mode 100644 index 0000000000..4784904ad0 --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityPluginCatalog.ts @@ -0,0 +1,479 @@ +/** + * Google's two public Antigravity plugin catalogs, read the way the agy CLI reads them: fixed + * gstatic addresses, no sign-in. Each catalog is fetched, bounded and decoded on its own, so one + * outage leaves the other listed. + */ +import { + storeCategories, + type ExtensionCategory, + type ExtensionIconDataUri, +} from "@t3tools/contracts"; +import * as Cache from "effect/Cache"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; +import { extensionIconData } from "./ExtensionIconData.ts"; + +export const ANTIGRAVITY_MARKETPLACES = [ + { + name: "antigravity-plugins-official", + url: "https://www.gstatic.com/antigravity/plugins/marketplace.json", + publisherType: "google", + }, + { + name: "antigravity-plugins-partners", + url: "https://www.gstatic.com/antigravity/plugins-partners/marketplace.json", + publisherType: "third-party", + }, +] as const; +export type AntigravityMarketplace = (typeof ANTIGRAVITY_MARKETPLACES)[number]; +export type AntigravityMarketplaceName = AntigravityMarketplace["name"]; + +const GSTATIC_HOST = "www.gstatic.com"; +const MAX_FEED_BYTES = 4 * 1024 * 1024; +const MAX_FEED_PLUGINS = 2_000; +const MAX_ICON_BYTES = 64 * 1024; + +export const AntigravityPluginName = Schema.String.check( + Schema.isPattern(/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]{0,62}[a-zA-Z0-9])?$/), +); +const Feed = Schema.Struct({ + name: Schema.String, + plugins: Schema.Array(Schema.Unknown).check(Schema.isMaxLength(MAX_FEED_PLUGINS)), +}); +// Only the identity and the download are required; display fields are read leniently. +const FeedPlugin = Schema.Struct({ + name: AntigravityPluginName, + displayName: Schema.optional(Schema.Unknown), + version: Schema.optional(Schema.Unknown), + description: Schema.optional(Schema.Unknown), + 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), + mcpServers: Schema.optional(Schema.Unknown), + source: Schema.Struct({ + type: Schema.String, + url: Schema.optional(Schema.String), + sha256: Schema.optional(Schema.String), + }), +}); +const decodeFeed = Schema.decodeUnknownEffect(Schema.fromJsonString(Feed)); +const decodeFeedPlugin = Schema.decodeUnknownOption(FeedPlugin); + +export interface AntigravityCatalogPlugin { + readonly name: string; + readonly marketplace: AntigravityMarketplaceName; + readonly publisherType: AntigravityMarketplace["publisherType"]; + readonly displayName: string; + readonly description: string; + readonly version?: string | undefined; + readonly publisher?: string | undefined; + readonly website?: string | undefined; + readonly categories: ReadonlyArray; + /** Scient's Discover categories, from the reviewed map or the catalog's own labels. */ + readonly scientCategories: ReadonlyArray; + readonly logoUrl?: string | undefined; + readonly keywords: ReadonlyArray; + readonly includes: ReadonlyArray; + readonly skills: ReadonlyArray; + 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 { + readonly plugins: ReadonlyArray; + readonly sourceFailures: ReadonlyArray; +} + +export class AntigravityCatalogError extends Schema.TaggedError()( + "AntigravityCatalogError", + { marketplace: Schema.String, detail: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return `Could not read ${this.marketplace}: ${this.detail}`; + } +} + +/** `https://www.gstatic.com/…` with nothing that could point elsewhere. */ +function isGstaticUrl(value: string): boolean { + if (!URL.canParse(value)) return false; + const url = new URL(value); + return ( + url.protocol === "https:" && + url.hostname === GSTATIC_HOST && + url.port === "" && + url.username === "" && + url.password === "" && + url.hash === "" + ); +} + +/** Where both catalogs keep their plugin archives. */ +export function isAntigravityGstaticUrl(value: string): boolean { + return isGstaticUrl(value) && new URL(value).pathname.startsWith("/antigravity/"); +} + +const nonBlank = (value: unknown) => { + const trimmed = typeof value === "string" ? value.trim() : undefined; + return trimmed ? trimmed : undefined; +}; + +const strings = (value: unknown): ReadonlyArray => + (Array.isArray(value) ? value : [value]).flatMap((item) => { + const text = nonBlank(item); + return text ? [text] : []; + }); + +const httpsUrl = (value: unknown) => { + const trimmed = nonBlank(value); + return trimmed && URL.canParse(trimmed) && new URL(trimmed).protocol === "https:" + ? trimmed + : undefined; +}; + +/** Names a component list gives, whether as paths (`./skills/x`), objects or a record's keys. */ +function componentNames(value: unknown): ReadonlyArray { + const names = Array.isArray(value) + ? value.flatMap((item) => + typeof item === "string" + ? [item.split(/[\\/]/).filter(Boolean).at(-1) ?? ""] + : typeof item === "object" && item !== null && "name" in item + ? [String(item.name)] + : [], + ) + : typeof value === "object" && value !== null + ? Object.keys(value) + : []; + return [...new Set(names.map((name) => name.trim()).filter(Boolean))].slice(0, 200); +} + +/** Reviewed Discover categories per catalog plugin (2026-11-21 catalogs); others fall back. */ +const ANTIGRAVITY_CATEGORIES: Readonly>> = { + // Google: Workspace, science, developer. + gmail: ["communication"], + gcalendar: ["communication", "projects"], + gdocs: ["files"], + gdrive: ["files"], + gsheets: ["files", "data"], + gslides: ["files", "figures"], + "scientific-literature": ["papers"], + "science-overview": ["papers", "biology", "chemistry"], + chemistry: ["chemistry"], + genomics: ["biology"], + "structural-biology": ["biology", "chemistry"], + robotics: ["physics-math", "code"], + "data-agent-kit-plugin": ["data", "code"], + looker: ["data"], + google_maps_platform: ["earth", "code"], + egm: ["files"], + "android-cli-plugin": ["code"], + "chrome-devtools-plugin": ["code"], + firebase: ["code"], + flutter: ["code"], + "gemini-api": ["code"], + "google-antigravity-sdk": ["code"], + "google-cloud-developer": ["code"], + "google-developer-knowledge": ["code"], + "google-health-developer": ["code"], + "google-home-developer": ["code"], + "modern-web-guidance-plugin": ["code"], + // Partners. + canva: ["figures"], + figma: ["figures"], + mobbin: ["figures"], + invideo: ["figures"], + notion: ["files", "projects"], + dropbox: ["files"], + docusign: ["files"], + pandadoc: ["files"], + linear: ["projects", "code"], + monday: ["projects"], + clickup: ["projects"], + trello: ["projects"], + "atlassian-twg-cli": ["projects", "files"], + "zoho-projects": ["projects"], + "zoho-bigin": ["projects"], + zapier: ["projects"], + "n8n-skills": ["projects", "code"], + granola: ["communication"], + "wispr-flow": ["communication"], + intercom: ["communication"], + "zoho-desk-antigravity": ["communication"], + keenable: ["papers"], + "keenable-select": ["papers", "data"], + parallel: ["papers"], + tavily: ["papers"], + midpage: ["papers", "social-science"], + "levels-fyi": ["social-science"], + semrush: ["data"], + databricks: ["data", "code"], + "mongodb-atlas": ["data", "code"], + neo4j: ["data", "code"], + supabase: ["data", "code"], + "arize-skills": ["data", "code"], + "grafana-cloud-mcp": ["data", "code"], + "zohobooks-antigravity": ["data"], + // Developer, security and operations tooling. + stripe: ["code"], + auth0: ["code"], + base44: ["code"], + betterstack: ["code"], + browse: ["code"], + clerk: ["code"], + cloudflare: ["code"], + coderabbit: ["code"], + context7: ["code"], + crowdstrike: ["code"], + datadog: ["code"], + dynatrace: ["code"], + "endor-labs-agent-kit": ["code"], + "harness-antigravity": ["code"], + "incident-io": ["code"], + "leapwork-play": ["code"], + netlify: ["code"], + "ping-identity-pingone": ["code"], + postman: ["code"], + qodo: ["code"], + railway: ["code"], + "scandit-sdk": ["code"], + "sentinelone-purple-mcp": ["code"], + sentry: ["code"], + soc: ["code"], + sonarqube: ["code"], + spacefast: ["code"], + superpowers: ["code"], + "testmu-ai": ["code"], + unity: ["code"], + "vercel-plugin": ["code"], + virustotal: ["code"], + wix: ["code"], + wordpress: ["code"], + "zoho-crm-plugin": ["code"], +}; +/** + * Discover categories for a catalog plugin: the reviewed list, else the catalog's own categories, + * else its keywords. Most used stays Scient's picks. + */ +export function antigravityCategories( + name: string, + categories: ReadonlyArray, + keywords: ReadonlyArray, +): ReadonlyArray { + const reviewed = ANTIGRAVITY_CATEGORIES[name]; + if (reviewed) return reviewed; + for (const labels of [categories, keywords]) { + const found = [ + ...new Set(labels.flatMap((label) => storeCategories("", label.replace(/-/g, " ")))), + ].filter((category) => category !== "most-used"); + if (found.length) return found; + } + return []; +} + +function catalogPlugin( + marketplace: AntigravityMarketplace, + raw: unknown, +): AntigravityCatalogPlugin | undefined { + const decoded = decodeFeedPlugin(raw); + if (decoded._tag === "None") return undefined; + const plugin = decoded.value; + const skills = componentNames(plugin.skills); + const mcpServers = componentNames(plugin.mcpServers); + const sha256 = plugin.source.sha256?.toLowerCase(); + const archive = + plugin.source.type === "archive" && + plugin.source.url !== undefined && + isAntigravityGstaticUrl(plugin.source.url) && + sha256 !== undefined && + /^[0-9a-f]{64}$/.test(sha256) + ? { url: plugin.source.url, sha256 } + : undefined; + const author = + typeof plugin.author === "object" && plugin.author !== null && "name" in plugin.author + ? nonBlank(plugin.author.name) + : nonBlank(plugin.author); + const publisher = author ?? (marketplace.publisherType === "google" ? "Google" : undefined); + const categories = strings(plugin.category).slice(0, 10); + const keywords = (Array.isArray(plugin.keywords) ? strings(plugin.keywords) : []).slice(0, 50); + return { + name: plugin.name, + marketplace: marketplace.name, + publisherType: marketplace.publisherType, + displayName: nonBlank(plugin.displayName) ?? plugin.name, + description: nonBlank(plugin.description) ?? "", + version: nonBlank(plugin.version), + publisher, + website: httpsUrl(plugin.homepage), + categories, + scientCategories: antigravityCategories(plugin.name, categories, keywords), + logoUrl: httpsUrl(plugin.logo), + keywords, + // 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, + identity: { + repository: nonBlank(plugin.repository), + author, + description: nonBlank(plugin.description), + }, + }; +} + +/** Reads at most `limit` bytes of a body; a longer body fails rather than truncating. */ +const readBoundedBody = (stream: Stream.Stream, limit: number) => + stream.pipe( + Stream.runFoldEffect( + () => ({ chunks: [] as Uint8Array[], bytes: 0 }), + (state, chunk) => { + if (state.bytes + chunk.length > limit) return Effect.fail("too-large" as const); + state.chunks.push(chunk); + state.bytes += chunk.length; + return Effect.succeed(state); + }, + ), + Effect.map((state) => Buffer.concat(state.chunks)), + ); + +/** One GET of a fixed gstatic address: no redirects followed, no credentials sent. */ +export const getGstatic = (http: HttpClient.HttpClient, url: string, accept: string) => + http + .execute(HttpClientRequest.get(url, { headers: { accept } })) + .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" })); + +const readFeed = Effect.fn("AntigravityPluginCatalog.readFeed")( + function* (http: HttpClient.HttpClient, marketplace: AntigravityMarketplace) { + const failed = (detail: string) => (cause?: unknown) => + new AntigravityCatalogError({ marketplace: marketplace.name, detail, cause }); + const response = yield* getGstatic(http, marketplace.url, "application/json").pipe( + Effect.mapError(failed("the catalog could not be reached")), + ); + if (response.status !== 200) + return yield* failed(`the catalog answered with HTTP ${response.status}`)(); + const body = yield* readBoundedBody(response.stream, MAX_FEED_BYTES).pipe( + Effect.mapError(failed("the catalog was too large or could not be read")), + ); + const feed = yield* decodeFeed(body.toString("utf8")).pipe( + Effect.mapError(failed("the catalog is not in the expected format")), + ); + if (feed.name !== marketplace.name) + return yield* failed("the catalog names a different marketplace")(); + const seen = new Set(); + const plugins: AntigravityCatalogPlugin[] = []; + for (const raw of feed.plugins) { + const plugin = catalogPlugin(marketplace, raw); + if (!plugin || seen.has(plugin.name)) continue; + seen.add(plugin.name); + plugins.push(plugin); + } + return plugins; + }, + (effect, _http, marketplace) => + Effect.timeoutOrElse(effect, { + duration: "20 seconds", + orElse: () => + Effect.fail( + new AntigravityCatalogError({ + marketplace: marketplace.name, + detail: "the catalog took too long to answer", + }), + ), + }), +); + +/** + * Both catalogs, cached for ten minutes per catalog (a failure for fifteen seconds). Concurrent + * readers share one fetch; `refresh` fetches both again. + */ +export const makeAntigravityPluginCatalog = Effect.fn("makeAntigravityPluginCatalog")(function* ( + marketplaces: ReadonlyArray = ANTIGRAVITY_MARKETPLACES, +) { + const http = yield* HttpClient.HttpClient; + const cache = yield* Cache.makeWith( + (name: AntigravityMarketplaceName) => { + const marketplace = marketplaces.find((item) => item.name === name)!; + return readFeed(http, marketplace); + }, + { + capacity: marketplaces.length, + timeToLive: (exit) => (Exit.isSuccess(exit) ? "10 minutes" : "15 seconds"), + }, + ); + const icons = new Map(); + const readIcon = Effect.fn("AntigravityPluginCatalog.icon")(function* (url: string | undefined) { + if (!url || !isGstaticUrl(url)) return undefined; + if (icons.has(url)) return icons.get(url); + const icon = yield* Effect.gen(function* () { + const response = yield* getGstatic( + http, + url, + "image/svg+xml,image/png,image/webp,image/jpeg", + ); + if (response.status !== 200) return undefined; + return extensionIconData(yield* readBoundedBody(response.stream, MAX_ICON_BYTES)); + }).pipe( + Effect.timeout("5 seconds"), + Effect.orElseSucceed(() => undefined), + ); + icons.set(url, icon); + while (icons.size > 512) icons.delete(icons.keys().next().value!); + return icon; + }); + const read = Effect.fn("AntigravityPluginCatalog.read")(function* (refresh = false) { + const results = yield* Effect.forEach( + marketplaces, + (marketplace) => + (refresh + ? Cache.refresh(cache, marketplace.name) + : Cache.get(cache, marketplace.name) + ).pipe( + Effect.tapError((cause) => Effect.logWarning(cause.message)), + Effect.result, + ), + { concurrency: "unbounded" }, + ); + const plugins: AntigravityCatalogPlugin[] = []; + const sourceFailures: AntigravityMarketplaceName[] = []; + const seen = new Set(); + for (const [index, result] of results.entries()) { + if (result._tag === "Failure") { + sourceFailures.push(marketplaces[index]!.name); + continue; + } + // A slug both catalogs list installs to one folder; the first catalog keeps it. + for (const plugin of result.success) { + if (seen.has(plugin.name)) continue; + seen.add(plugin.name); + plugins.push(plugin); + } + } + return { plugins, sourceFailures } satisfies AntigravityCatalogRead; + }); + return { + read, + invalidate: Cache.invalidateAll(cache), + icon: readIcon, + }; +}); +export type AntigravityPluginCatalog = Effect.Success< + ReturnType +>; diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts new file mode 100644 index 0000000000..f1a4f72cda --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.test.ts @@ -0,0 +1,768 @@ +// @effect-diagnostics nodeBuiltinImport:off -- fixtures hash their archives. +import * as NodeCrypto from "node:crypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +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"; +import * as TestClock from "effect/testing/TestClock"; +import { ANTIGRAVITY_MARKETPLACES, antigravityCategories } from "./AntigravityPluginCatalog.ts"; +import { + ANTIGRAVITY_NOT_CLI, + antigravityPluginCommandEnvironment, + makeAntigravityPluginActions, +} from "./AntigravityProviderStore.ts"; +import { makeZip, renameInZip } from "./AntigravityPluginArchive.testkit.ts"; + +const encode = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeManifest = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ name: Schema.String, version: Schema.String })), +); +const [OFFICIAL, PARTNERS] = ANTIGRAVITY_MARKETPLACES; +const GMAIL_ZIP = "https://www.gstatic.com/antigravity/plugins/gmail/gmail.zip?v=1"; +const CANVA_ZIP = "https://www.gstatic.com/antigravity/plugins-partners/canva/canva.zip?v=1"; +const sha256 = (bytes: Uint8Array) => NodeCrypto.createHash("sha256").update(bytes).digest("hex"); + +const gmailZip = makeZip([ + { name: "plugin.json", data: encode({ name: "gmail", version: "0.0.7" }) }, + { name: "skills/gmail/SKILL.md", data: "---\nname: gmail\n---\n" }, + { name: "skills/gmail/scripts/gmail", data: "#!/bin/sh\n", mode: 0o100755 }, +]); + +/** A fresh response per request: a cloned body stays open until every clone is read. */ +type Route = (() => Response) | "hang" | "fail"; + +interface Fixture { + readonly routes: Map; + readonly fetched: string[]; + readonly calls: string[][]; + readonly installed: Map< + string, + { enabled: boolean; version?: string; path: string; source?: string | null } + >; + readonly stagedScriptModes: number[]; + listOutput?: string; + 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."; +const isArchiveInstall = (call: ReadonlyArray) => + call[1] === "install" && !call[2]!.includes("@"); + +const officialFeed = (gmail: Buffer, overrides: Record = {}) => ({ + name: OFFICIAL.name, + plugins: [ + { + name: "gmail", + displayName: "Gmail", + version: "0.0.7", + description: GMAIL_DESCRIPTION, + logo: "https://www.gstatic.com/images/gmail.svg", + source: { type: "archive", url: GMAIL_ZIP, sha256: sha256(gmail) }, + ...overrides, + }, + { name: "broken entry", source: { type: "archive" } }, + { + name: "chemistry", + displayName: "Chemistry", + description: "Molecules", + keywords: ["science"], + source: { + type: "archive", + url: "https://example.com/chemistry.zip", + sha256: "0".repeat(64), + }, + }, + ], +}); +const partnerFeed = (canva: Buffer) => ({ + name: PARTNERS.name, + plugins: [ + { + name: "canva", + displayName: "Canva", + version: "1.0.0", + description: "Designs", + author: { name: "Canva" }, + skills: ["./skills/edit-design"], + mcpServers: "./mcp_config.json", + source: { type: "archive", url: CANVA_ZIP, sha256: sha256(canva) }, + }, + ], +}); + +const setup = (configure?: (fixture: Fixture, zips: { gmail: Buffer; canva: Buffer }) => void) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const home = yield* fs.makeTempDirectoryScoped(); + const gmail = yield* gmailZip; + const canva = yield* makeZip([ + { name: "plugin.json", data: encode({ name: "canva", version: "1.0.0" }) }, + ]); + const fixture: Fixture = { + routes: new Map([ + [OFFICIAL.url, () => Response.json(officialFeed(gmail))], + [PARTNERS.url, () => Response.json(partnerFeed(canva))], + [GMAIL_ZIP, () => new Response(gmail)], + [CANVA_ZIP, () => new Response(canva)], + ]), + fetched: [], + calls: [], + installed: new Map(), + stagedScriptModes: [], + }; + configure?.(fixture, { gmail, canva }); + const http = HttpClient.make((request) => { + fixture.fetched.push(request.url); + const route = fixture.routes.get(request.url); + if (route === "hang") return Effect.never; + if (route === "fail" || route === undefined) + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("missing", { status: 404 })), + ); + return Effect.succeed(HttpClientResponse.fromWeb(request, route())); + }); + const pluginPath = (name: string) => path.join(home, ".gemini", "config", "plugins", name); + const run = (args: ReadonlyArray) => + Effect.gen(function* () { + fixture.calls.push([...args]); + const [, command, target] = args; + if (command === "list") { + if (fixture.listOutput !== undefined) return fixture.listOutput; + return encode( + [...fixture.installed].map(([name, plugin]) => ({ + name, + enabled: plugin.enabled, + ...(plugin.version ? { version: plugin.version } : {}), + ...(plugin.source === null ? {} : { source: plugin.source ?? "antigravity" }), + path: plugin.path, + })), + ); + } + 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]; + // 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"), + encode({ name, version: "0.0.7", description: GMAIL_DESCRIPTION }), + ); + fixture.installed.set(name, { + enabled: true, + version: "0.0.7", + path: pluginPath(name), + source: marketplace, + }); + if (fixture.namedTimesOut) return yield* Effect.fail("timed out"); + return ""; + } + if (command === "install") { + const manifest = yield* fs.readFileString(path.join(target!, "plugin.json")); + const script = path.join(target!, "skills", "gmail", "scripts", "gmail"); + 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, + path: pluginPath(parsed.name), + }); + if (fixture.afterArchiveInstall) yield* fixture.afterArchiveInstall(); + return ""; + } + 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"; + } + return ""; + }).pipe(Effect.mapError(() => ({ message: "agy failed" }))); + const plugins = yield* makeAntigravityPluginActions({ + stateDir, + run, + unavailable: Effect.sync(() => fixture.unavailable), + }).pipe(Effect.provideService(HttpClient.HttpClient, http)); + const store = plugins.actions.store!; + return { ...plugins, store, fixture, stateDir, pluginPath, fs, path }; + }); + +const provide = ( + effect: Effect.Effect, +) => Effect.scoped(effect).pipe(Effect.provide(NodeServices.layer)); + +describe("AntigravityProviderStore", () => { + it.effect("lists both catalogs in order with their publishers, skipping malformed entries", () => + provide( + Effect.gen(function* () { + const { store } = yield* setup(); + const page = yield* store.search({}); + expect(page.entries.map((entry) => entry.id)).toEqual([ + "gmail@antigravity-plugins-official", + "chemistry@antigravity-plugins-official", + "canva@antigravity-plugins-partners", + ]); + expect(page.entries[0]).toMatchObject({ + kind: "antigravity", + publisherType: "google", + publisher: "Google", + installed: false, + }); + expect(page.entries[0]!.disabledReason).toBeUndefined(); + expect(page.entries[1]!.disabledReason).toMatch(/Google's plugin host/); + expect(page.entries[2]).toMatchObject({ + publisherType: "third-party", + publisher: "Canva", + includes: ["Skills", "MCP servers"], + }); + expect((yield* store.search({ query: "science" })).entries.map((e) => e.name)).toEqual([ + "chemistry", + ]); + const detail = yield* store.contents!("canva@antigravity-plugins-partners"); + expect(detail.deferred).toBe(true); + expect(detail.skills.map((skill) => skill.name)).toEqual(["edit-design"]); + }), + ), + ); + + it.effect("keeps one catalog when the other fails, is too large or malformed", () => + provide( + Effect.gen(function* () { + for (const partner of [ + "fail" as const, + () => new Response("x".repeat(4 * 1024 * 1024 + 1)), + () => Response.json({ name: "someone-else", plugins: [] }), + () => new Response("{not json"), + ]) { + const { store } = yield* setup((fixture) => fixture.routes.set(PARTNERS.url, partner)); + const page = yield* store.search({}); + expect(page.sourceFailures).toEqual([PARTNERS.name]); + expect(page.entries.map((entry) => entry.name)).toEqual(["gmail", "chemistry"]); + } + }), + ), + ); + + it.effect("times out a catalog that never answers", () => + provide( + Effect.gen(function* () { + const { store } = yield* setup((fixture) => fixture.routes.set(OFFICIAL.url, "hang")); + const searching = yield* store + .search({}) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("21 seconds"); + const page = yield* Fiber.join(searching); + expect(page.sourceFailures).toEqual([OFFICIAL.name]); + expect(page.entries.map((entry) => entry.name)).toEqual(["canva"]); + }), + ), + ); + + it.effect("fetches each catalog once for concurrent and repeated reads until refreshed", () => + provide( + Effect.gen(function* () { + const { store, fixture } = yield* setup(); + yield* Effect.all([store.search({}), store.search({ preview: true })], { + concurrency: "unbounded", + }); + yield* store.search({ query: "gmail" }); + const feedReads = () => fixture.fetched.filter((url) => url.endsWith("marketplace.json")); + expect(feedReads()).toHaveLength(2); + yield* store.search({ refresh: true }); + expect(feedReads()).toHaveLength(4); + }), + ), + ); + + it.effect("adds a checked archive through agy and records where it came from", () => + provide( + 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(isArchiveInstall)!; + expect(install.slice(0, 2)).toEqual(["plugin", "install"]); + expect(path.basename(install[2]!)).toBe("gmail"); + expect(yield* fs.exists(install[2]!)).toBe(false); + expect(fixture.stagedScriptModes[0]! & 0o111).not.toBe(0); + expect((yield* store.entry("gmail@antigravity-plugins-official")).installed).toBe(true); + const listing = yield* actions.listPlugins({}); + expect(listing.plugins).toEqual([ + expect.objectContaining({ + id: "gmail@antigravity-plugins-official", + marketplace: "antigravity-plugins-official", + displayName: "Gmail", + canUninstall: true, + canSetEnabled: true, + path: pluginPath("gmail"), + }), + ]); + expect( + yield* fs.readFileString(path.join(stateDir, "antigravity-plugins", "receipts.json")), + ).toContain('"sha256"'); + expect( + yield* fs.readDirectory(path.join(stateDir, "antigravity-plugins", "staging")), + ).toEqual([]); + + yield* actions.setEnabled!({ + pluginId: "gmail@antigravity-plugins-official", + enabled: false, + }); + expect(fixture.calls).toContainEqual(["plugin", "disable", "gmail"]); + yield* actions.uninstall({ pluginId: "gmail@antigravity-plugins-official" }); + expect(fixture.calls).toContainEqual(["plugin", "uninstall", "gmail"]); + expect((yield* store.entry("gmail@antigravity-plugins-official")).installed).toBe(false); + }), + ), + ); + + it.effect("refuses an archive whose checksum differs and never installs it", () => + provide( + Effect.gen(function* () { + const { store, fixture, stateDir, fs, path } = yield* setup((fixture) => + fixture.routes.set(GMAIL_ZIP, () => new Response("tampered")), + ); + const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); + expect(error.message).toMatch(/checksum/); + 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([]); + }), + ), + ); + + it.effect("refuses an unsafe archive even when its checksum matches", () => + provide( + Effect.gen(function* () { + const unsafe = renameInZip( + yield* makeZip([ + { name: "plugin.json", data: encode({ name: "gmail", version: "0.0.7" }) }, + { name: "zz/evil", data: "x" }, + ]), + "zz/evil", + "../evil", + ); + const { store, fixture, stateDir, fs, path } = yield* setup((fixture) => { + fixture.routes.set(OFFICIAL.url, () => Response.json(officialFeed(unsafe))); + fixture.routes.set(GMAIL_ZIP, () => new Response(unsafe)); + }); + const error = yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip); + expect(error.message).toMatch(/archive/); + expect(fixture.calls.some(isArchiveInstall)).toBe(false); + expect( + yield* fs.readDirectory(path.join(stateDir, "antigravity-plugins", "staging")), + ).toEqual([]); + expect(yield* fs.exists(path.join(stateDir, "antigravity-plugins", "evil"))).toBe(false); + }), + ), + ); + + it.effect("never claims or removes a same-name plugin from another source", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture, pluginPath } = yield* setup(); + fixture.installed.set("gmail", { + enabled: true, + version: "9.9.9", + path: pluginPath("gmail"), + }); + const entry = yield* store.entry("gmail@antigravity-plugins-official"); + expect(entry.installed).toBe(false); + expect(entry.disabledReason).toMatch(/different plugin named gmail/); + expect( + (yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip)).message, + ).toMatch(/different plugin named gmail/); + expect(fixture.calls.some((call) => call[1] === "install")).toBe(false); + expect( + (yield* actions + .uninstall({ pluginId: "gmail@antigravity-plugins-official" }) + .pipe(Effect.flip)).message, + ).toMatch(/no longer installed/); + expect(fixture.calls.some((call) => call[1] === "uninstall")).toBe(false); + const [native] = (yield* actions.listPlugins({})).plugins; + expect(native).toMatchObject({ + id: "antigravity:gmail", + sourceLabel: "Antigravity's plugins", + }); + expect(native!.marketplace).toBeUndefined(); + }), + ), + ); + + 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(isArchiveInstall)).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 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("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, actions, 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); + // 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); + expect(entry.installed).toBe(false); + expect(entry.disabledReason).toMatch(/different plugin named gmail/); + }), + ), + ); + + 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* () { + for (const output of ["not json", encode([{ name: "gmail", enabled: true }])]) { + const { store, actions } = yield* setup((fixture) => { + fixture.listOutput = output; + }); + expect((yield* actions.listPlugins({}).pipe(Effect.flip)).message).toMatch( + /installed plugins/, + ); + const page = yield* store.search({}); + expect(page.message).toMatch(/paused/); + expect(page.entries[0]).toMatchObject({ + installationStateKnown: false, + installed: false, + }); + expect(page.entries[0]!.disabledReason).toMatch(/paused/); + expect( + (yield* store.install("gmail@antigravity-plugins-official").pipe(Effect.flip)).message, + ).toMatch(/paused/); + } + }), + ), + ); + + it.effect("keeps installed plugins and Remove working while both catalogs are down", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture, pluginPath } = yield* setup((fixture) => { + fixture.routes.set(OFFICIAL.url, "fail"); + fixture.routes.set(PARTNERS.url, "fail"); + }); + fixture.installed.set("canva", { enabled: true, path: pluginPath("canva") }); + const page = yield* store.search({}); + expect(page.entries).toEqual([]); + expect(page.sourceFailures).toEqual([OFFICIAL.name, PARTNERS.name]); + yield* actions.uninstall({ pluginId: "antigravity:canva" }); + expect(fixture.installed.size).toBe(0); + }), + ), + ); + + it.effect("explains why an instance that is not the agy CLI cannot add plugins", () => + provide( + Effect.gen(function* () { + const { store, actions, fixture } = yield* setup((fixture) => { + fixture.unavailable = ANTIGRAVITY_NOT_CLI; + }); + const page = yield* store.search({}); + expect(page.message).toBe(ANTIGRAVITY_NOT_CLI); + expect( + page.entries.every( + (entry) => entry.disabledReason === ANTIGRAVITY_NOT_CLI && entry.storeUnavailable, + ), + ).toBe(true); + expect((yield* actions.listPlugins({}).pipe(Effect.flip)).message).toBe( + ANTIGRAVITY_NOT_CLI, + ); + expect(fixture.calls).toEqual([]); + }), + ), + ); +}); + +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"]); + expect(antigravityCategories("new-tool", ["Developer Tools", "Cloud"], [])).toEqual(["code"]); + expect(antigravityCategories("new-db", [], ["graph", "database"])).toEqual(["data"]); + expect(antigravityCategories("new-thing", [], ["misc"])).toEqual([]); +}); + +it.effect("filters a category page by those categories", () => + provide( + Effect.gen(function* () { + const { store } = yield* setup(); + const names = (category: string) => + store.search({ category }).pipe(Effect.map((page) => page.entries.map((e) => e.name))); + expect(yield* names("communication")).toEqual(["gmail"]); + expect(yield* names("chemistry")).toEqual(["chemistry"]); + expect(yield* names("figures")).toEqual(["canva"]); + expect(yield* names("most-used")).toEqual([]); + }), + ), +); + +it("passes agy only what it needs to find the user's home", () => { + expect( + antigravityPluginCommandEnvironment({ + HOME: "/home/a", + PATH: "/usr/bin", + GEMINI_API_KEY: "secret", + GEMINI_HOME: "/profile", + T3CODE_HOME: "/live", + }), + ).toEqual({ HOME: "/home/a", PATH: "/usr/bin" }); +}); diff --git a/apps/server/src/scient/extensions/AntigravityProviderStore.ts b/apps/server/src/scient/extensions/AntigravityProviderStore.ts new file mode 100644 index 0000000000..beb2021e85 --- /dev/null +++ b/apps/server/src/scient/extensions/AntigravityProviderStore.ts @@ -0,0 +1,852 @@ +/** + * 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, + ProviderStoreEntry, + ProviderStorePage, + 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"; +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"; +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, +} from "../../provider/AntigravityInstallation.ts"; +import { + ANTIGRAVITY_MARKETPLACES, + AntigravityPluginName, + makeAntigravityPluginCatalog, + type AntigravityCatalogPlugin, + type AntigravityMarketplace, + type AntigravityPluginIdentity, +} from "./AntigravityPluginCatalog.ts"; +import { + ARCHIVE_LIMITS, + isAntigravityPluginArchiveError, + sha256Hex, + stageAntigravityPlugin, +} from "./AntigravityPluginArchive.ts"; +import { resolveBrandIcon } from "./BrandIcons.ts"; +import { readLocalPluginContents, readLocalPluginSkill } from "./LocalPluginContents.ts"; +import { tryLocalPluginRead } from "./LocalPluginFiles.ts"; +import { runProviderPluginCommand } from "./ProviderPluginCommand.ts"; +import { sharedPluginDisplayName } from "./SharedPluginStore.ts"; + +type Failure = { readonly message: string }; +const fail = (message: string) => Effect.fail({ message } satisfies Failure); + +const MAX_LISTED = 2_000; +const Listed = Schema.Array( + Schema.Struct({ + name: AntigravityPluginName, + enabled: Schema.Boolean, + version: Schema.optional(Schema.NullOr(Schema.String)), + source: Schema.optional(Schema.NullOr(Schema.String)), + path: Schema.String, + skills: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + mcpServers: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + }), +).check(Schema.isMaxLength(MAX_LISTED)); +const decodeListed = Schema.decodeUnknownEffect(Schema.fromJsonString(Listed)); + +const Receipt = Schema.Struct({ + name: AntigravityPluginName, + marketplace: Schema.Literals(ANTIGRAVITY_MARKETPLACES.map((item) => item.name)), + version: Schema.optional(Schema.String), + 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( + Schema.Struct({ + version: Schema.Literal(1), + receipts: Schema.Array(Receipt).check(Schema.isMaxLength(MAX_LISTED)), + }), +); +const decodeReceipts = Schema.decodeUnknownEffect(ReceiptFile); +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; + /** The catalog this copy matches, recorded (agy, receipt) or only by its manifest. */ + readonly catalogMarketplace?: string | undefined; + readonly skills: ReadonlyArray; + readonly mcpServers: ReadonlyArray; +}; + +const entryId = (name: string, marketplace: string) => `${name}@${marketplace}`; + +export const ANTIGRAVITY_NOT_CLI = + "Adding plugins needs Antigravity's agy command-line runtime. Choose it in this agent's settings."; +const INVENTORY_UNAVAILABLE = + "Scient could not read Antigravity's installed plugins, so Add and Remove are paused. Refresh to try again."; + +/** + * 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; + readonly source?: string | undefined; + }, +) { + const candidate = receipts.find( + (receipt) => + receipt.name === plugin.name && + receipt.path === plugin.path && + 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; +}); + +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 (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: { + 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, recorded: true, receipt: undefined }; + const receipt = yield* receiptFor(receipts, plugin); + 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, recorded: false, 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()); + const names = new Set(); + const plugins: AntigravityInstalledPlugin[] = []; + for (const item of listed) { + if (names.has(item.name) || !path.isAbsolute(item.path)) + return yield* fail("Antigravity listed its plugins in an unexpected form."); + names.add(item.name); + const version = item.version?.trim() || undefined; + const source = item.source?.trim() || undefined; + const origin = yield* installedMarketplace( + { name: item.name, path: item.path, version, source }, + receipts, + catalog, + ); + const marketplace = origin?.recorded ? origin.marketplace : undefined; + const listedName = + (origin ? catalog?.get(item.name)?.displayName : undefined) ?? + origin?.receipt?.displayName?.trim(); + plugins.push({ + id: marketplace ? entryId(item.name, marketplace) : `antigravity:${item.name}`, + name: item.name, + displayName: listedName || sharedPluginDisplayName(item.name), + ...(version ? { version } : {}), + ...(marketplace ? { marketplace } : {}), + source: "local", + enabled: item.enabled, + canUninstall: true, + canSetEnabled: true, + sourceLabel: marketplace ? "Antigravity Marketplace" : "Antigravity's plugins", + scope: "user", + path: item.path, + ...(source ? { nativeSource: source } : {}), + ...(origin ? { catalogMarketplace: origin.marketplace } : {}), + skills: item.skills ?? [], + mcpServers: item.mcpServers ?? [], + }); + } + return plugins; +}); + +/** Contents a catalog entry declares, before it is added; folders are read once it is. */ +function declaredContents(plugin: AntigravityCatalogPlugin): ExtensionPluginContents { + return { + deferred: true, + apps: [], + agents: [], + commands: [], + mcpServers: plugin.mcpServers.map((name) => ({ name })), + skills: plugin.skills.map((name) => ({ + id: name, + name, + description: "", + enabled: false, + documentAvailable: false, + })), + }; +} + +/** + * 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>>(); +/** 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."; + +export interface AntigravityPluginStoreOptions { + /** Scient's state folder: receipts and the private staging folder live under it. */ + readonly stateDir: string; + /** Runs this instance's `agy` with fixed arguments, or fails with why it cannot. */ + 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; +} + +export const makeAntigravityPluginActions = Effect.fn("makeAntigravityPluginActions")(function* ( + options: AntigravityPluginStoreOptions, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const http = yield* HttpClient.HttpClient; + const catalog = yield* makeAntigravityPluginCatalog(options.marketplaces); + const root = path.join(options.stateDir, "antigravity-plugins"); + const receiptsFile = path.join(root, "receipts.json"); + const stagingRoot = path.join(root, "staging"); + const reports = yield* Effect.acquireRelease( + PubSub.unbounded({ replay: 1 }), + PubSub.shutdown, + ); + const retired = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(retired, undefined)); + 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) => + exists + ? fs.readFileString(receiptsFile).pipe( + Effect.flatMap(decodeReceipts), + Effect.map((file) => file.receipts), + ) + : Effect.succeed([]), + ), + Effect.tapError(() => + Effect.logWarning("Ignoring an unreadable Antigravity plugin receipt file."), + ), + Effect.orElseSucceed((): ReadonlyArray => []), + ); + const writeReceipts = Effect.fn("AntigravityProviderStore.writeReceipts")(function* ( + update: (receipts: ReadonlyArray) => ReadonlyArray, + ) { + const next = update(yield* readReceipts).slice(-MAX_LISTED); + const text = yield* encodeReceipts({ version: 1, receipts: [...next] }); + yield* fs.makeDirectory(root, { recursive: true }); + const temporary = `${receiptsFile}.tmp`; + yield* fs.writeFileString(temporary, text); + yield* fs.rename(temporary, receiptsFile); + }); + + const readList = Effect.fn("AntigravityProviderStore.readList")( + function* () { + // 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, + Option.getOrUndefined(known), + ); + return { plugins, sequence }; + }, + Effect.provideService(Path.Path, path), + 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); + return yield* readList(); + }); + + const toEntry = ( + plugin: AntigravityCatalogPlugin, + installed: ReadonlyArray | undefined, + unavailable: string | undefined, + ): ProviderStoreEntry => { + const id = entryId(plugin.name, plugin.marketplace); + const native = installed?.find((item) => item.name === plugin.name); + const added = native?.id === id || native?.catalogMarketplace === plugin.marketplace; + const disabledReason = + unavailable ?? + (installed === undefined + ? INVENTORY_UNAVAILABLE + : added + ? undefined + : native + ? `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); + return { + id, + name: plugin.name, + marketplace: plugin.marketplace, + displayName: plugin.displayName, + description: plugin.description, + kind: "antigravity", + installed: added, + ...(installed === undefined ? { installationStateKnown: false } : {}), + ...(unavailable ? { storeUnavailable: true } : {}), + ...(plugin.categories[0] ? { category: plugin.categories[0] } : {}), + ...(plugin.version ? { version: plugin.version } : {}), + ...(plugin.publisher ? { publisher: plugin.publisher } : {}), + ...(plugin.website ? { website: plugin.website } : {}), + includes: added && native ? nativeIncludes(native) : [...plugin.includes], + publisherType: plugin.publisherType, + ...(disabledReason ? { disabledReason } : {}), + apps: [], + }; + }; + const nativeIncludes = (plugin: AntigravityInstalledPlugin) => [ + ...(plugin.skills.length ? ["Skills"] : []), + ...(plugin.mcpServers.length ? ["MCP servers"] : []), + ]; + const withIcon = Effect.fn("AntigravityProviderStore.withIcon")(function* ( + entry: ProviderStoreEntry, + plugin: AntigravityCatalogPlugin, + ) { + const iconUrl = + (yield* catalog.icon(plugin.logoUrl)) ?? + resolveBrandIcon(plugin.displayName) ?? + resolveBrandIcon(plugin.name); + return iconUrl ? { ...entry, iconUrl } : entry; + }); + + const listing = Effect.fn("AntigravityProviderStore.listing")(function* (refresh: boolean) { + const [read, inventory, unavailable] = yield* Effect.all( + [catalog.read(refresh), list().pipe(Effect.option), options.unavailable], + { concurrency: "unbounded" }, + ); + const installed = inventory._tag === "Some" ? inventory.value.plugins : undefined; + return { + read, + installed, + unavailable, + entries: read.plugins.map((plugin) => ({ + plugin, + entry: toEntry(plugin, installed, unavailable), + })), + }; + }); + const find = Effect.fn("AntigravityProviderStore.find")(function* (id: string) { + const current = yield* listing(false); + const item = current.entries.find((candidate) => candidate.entry.id === id); + if (!item) return yield* fail("This plugin is no longer in the Antigravity Marketplace."); + return { ...current, ...item }; + }); + + const search = Effect.fn("AntigravityProviderStore.search")(function* ( + input: Omit, + ) { + const current = yield* listing(input.refresh === true); + const terms = (input.query ?? "").toLowerCase().split(/\s+/).filter(Boolean); + const matching = current.entries.filter( + ({ plugin }) => + (!input.category || + plugin.scientCategories.some((category) => category === input.category)) && + terms.every((term) => + [ + plugin.name, + plugin.displayName, + plugin.description, + plugin.publisher ?? "", + ...plugin.keywords, + ] + .join(" ") + .toLowerCase() + .includes(term), + ), + ); + const offset = input.cursor ? Number(input.cursor) : 0; + if (!Number.isSafeInteger(offset) || offset < 0) return yield* fail("Invalid store cursor."); + const limit = Math.min(input.limit ?? (input.preview ? 6 : 30), 50); + const entries = yield* Effect.forEach( + matching.slice(offset, offset + limit), + ({ entry, plugin }) => withIcon(entry, plugin), + { concurrency: 8 }, + ); + const message = + current.unavailable ?? (current.installed === undefined ? INVENTORY_UNAVAILABLE : undefined); + return { + entries, + total: matching.length, + ...(current.read.sourceFailures.length + ? { sourceFailures: [...current.read.sourceFailures] } + : {}), + ...(offset + limit < matching.length ? { nextCursor: String(offset + limit) } : {}), + ...(message ? { message } : {}), + } satisfies ProviderStorePage; + }); + + const installedFolder = Effect.fn("AntigravityProviderStore.installedFolder")(function* ( + id: string, + ) { + const item = yield* find(id); + const native = item.installed?.find((plugin) => plugin.id === id); + if (!native) return yield* fail("Add this plugin to read its files."); + return native.path; + }); + + const install = Effect.fn("AntigravityProviderStore.install")(function* (id: string) { + // Read under the write permit: agy replaces a same-name folder silently, so the entry's + // other-source check must see the listing this Add acts on. + const item = yield* find(id); + if (item.entry.disabledReason) return yield* fail(item.entry.disabledReason); + if (item.entry.installed) return; + 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.path !== afterNamed.path), + ).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."); + 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." }, + ), + ); + 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.`, + ); + const startedAt = yield* Clock.currentTimeMillis; + yield* options.run(["plugin", "install", directory]); + return { staged, startedAt }; + }), + ).pipe( + Effect.provideService(HttpClient.HttpClient, http), + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + 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), + Effect.provideService(Path.Path, path), + Effect.mapError(() => ({ + 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: 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.`, + ); + const version = listed.version?.trim() || undefined; + const source = listed.source?.trim() || undefined; + yield* writeReceipts((receipts) => [ + // Receipts are per installed folder: another plugin home's receipt for the name stays. + ...receipts.filter((receipt) => receipt.path !== listed.path), + { + name, + marketplace, + ...(version ? { version } : {}), + ...(source ? { source } : {}), + sha256: archive.sha256, + path: listed.path, + displayName: item.plugin.displayName, + installation, + }, + ]).pipe( + Effect.mapError(() => ({ + message: "The plugin was added, but Scient could not record where it came from.", + })), + ); + }); + + const nativePlugin = Effect.fn("AntigravityProviderStore.nativePlugin")(function* ( + pluginId: string, + ) { + const plugin = (yield* list()).plugins.find((item) => item.id === pluginId); + if (!plugin?.canUninstall) return yield* fail("This plugin is no longer installed."); + return plugin; + }); + + const publish = Effect.fn("AntigravityProviderStore.publish")(function* () { + 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) => changeAll(install(id)), + contents: (id) => + find(id).pipe( + Effect.flatMap(({ entry, plugin, installed }) => { + const native = entry.installed + ? installed?.find((item) => item.id === entry.id) + : undefined; + return native + ? tryLocalPluginRead(() => readLocalPluginContents(native.path)).pipe( + Effect.mapError(() => ({ message: "Could not read this plugin's contents." })), + ) + : Effect.succeed(declaredContents(plugin)); + }), + ), + skillDocument: (id, skillId) => + installedFolder(id).pipe( + Effect.flatMap((folder) => + tryLocalPluginRead(() => readLocalPluginSkill(folder, skillId)).pipe( + Effect.mapError(() => ({ message: "Could not read this skill document." })), + ), + ), + ), + }, + refreshInventory: ({ force }) => + (force ? catalog.invalidate : Effect.void).pipe(Effect.andThen(publish())), + listPlugins: () => list(), + listPluginRoots: () => + list().pipe( + Effect.map((listing) => + listing.plugins.map((plugin) => ({ + id: plugin.id, + name: plugin.name, + enabled: plugin.enabled, + root: plugin.path, + })), + ), + ), + readMcpServer: () => Effect.undefined, + setEnabled: (input) => + 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, + ), + ), + uninstall: (input) => + 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.path !== plugin.path), + ).pipe(Effect.ignore); + }), + ), + startMcpSignIn: () => + fail("Sign in to this plugin's service from an Antigravity chat when it asks."), + isRetired: Deferred.isDone(retired), + whenRetired: Deferred.await(retired), + }; + return { actions, reports: Stream.fromPubSub(reports) }; +}); + +/** What `agy plugin` needs to find the OS user's home, and nothing of the chat or its secrets. */ +const COMMAND_ENVIRONMENT_KEYS = [ + "HOME", + "USERPROFILE", + "HOMEDRIVE", + "HOMEPATH", + "APPDATA", + "LOCALAPPDATA", + "PATH", + "Path", + "SystemRoot", + "SYSTEMROOT", + "windir", + "TMPDIR", + "TEMP", + "TMP", + "LANG", + "LC_ALL", + "XDG_CONFIG_HOME", + "XDG_DATA_HOME", + "XDG_CACHE_HOME", +] as const; + +export function antigravityPluginCommandEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const picked: NodeJS.ProcessEnv = {}; + for (const key of COMMAND_ENVIRONMENT_KEYS) if (env[key] !== undefined) picked[key] = env[key]; + return picked; +} + +/** The plugin seam for one Antigravity instance, run through the same `agy` its chats use. */ +export const makeAntigravityInstancePlugins = Effect.fn("makeAntigravityInstancePlugins")( + function* (input: { + readonly installation: { + readonly resolve: ( + binaryPath?: string, + environment?: NodeJS.ProcessEnv, + ) => Effect.Effect; + readonly acquire: ( + binaryPath?: string, + environment?: NodeJS.ProcessEnv, + ) => Effect.Effect; + }; + readonly binaryPath: string; + readonly environment: NodeJS.ProcessEnv; + readonly stateDir: string; + }) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const environment = antigravityPluginCommandEnvironment(input.environment); + yield* fs.makeDirectory(input.stateDir, { recursive: true }).pipe(Effect.ignore); + const run = (args: ReadonlyArray) => + Effect.scoped( + Effect.gen(function* () { + const executable = yield* input.installation + .acquire(input.binaryPath, input.environment) + .pipe(Effect.mapError(() => ({ message: "Antigravity is not installed." }))); + if (executable.harnessPath !== null) return yield* fail(ANTIGRAVITY_NOT_CLI); + return yield* runProviderPluginCommand( + executable.executablePath, + environment, + input.stateDir, + args, + ); + }), + ).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + const unavailable = input.installation.resolve(input.binaryPath, input.environment).pipe( + Effect.map((executable) => + executable.harnessPath === null ? undefined : ANTIGRAVITY_NOT_CLI, + ), + Effect.orElseSucceed(() => "Install Antigravity to add its plugins."), + ); + // 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: platform === "win32" ? pluginHome.toLowerCase() : pluginHome, + }); + }, +); 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 ( diff --git a/apps/server/src/scient/extensions/discover/curatedCatalog.ts b/apps/server/src/scient/extensions/discover/curatedCatalog.ts index 325a44f83b..b3fd11e52e 100644 --- a/apps/server/src/scient/extensions/discover/curatedCatalog.ts +++ b/apps/server/src/scient/extensions/discover/curatedCatalog.ts @@ -415,6 +415,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "supabase", + agentStores: { antigravity: "supabase@antigravity-plugins-partners" }, accountRequired: true, displayName: "Supabase", tagline: "Postgres projects, tables and SQL", @@ -501,6 +502,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // open: 200 "Context7" 4.4.3 id: "context7", + agentStores: { antigravity: "context7@antigravity-plugins-partners" }, accountRequired: false, displayName: "Context7", tagline: "Up-to-date library documentation", @@ -515,6 +517,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "sentry", + agentStores: { antigravity: "sentry@antigravity-plugins-partners" }, accountRequired: true, displayName: "Sentry", tagline: "Errors, issues and performance data", @@ -529,6 +532,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "vercel", + agentStores: { antigravity: "vercel-plugin@antigravity-plugins-partners" }, accountRequired: true, displayName: "Vercel", tagline: "Projects, deployments and logs", @@ -543,6 +547,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth, dynamic client registration (verified 2026-11-14) id: "cloudflare", + agentStores: { antigravity: "cloudflare@antigravity-plugins-partners" }, accountRequired: true, displayName: "Cloudflare", tagline: "Workers, DNS, storage and the rest of your account", @@ -634,7 +639,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ // sign-in: 401 OAuth id: "notion", accountRequired: true, - agentStores: { codex: "notion" }, + agentStores: { codex: "notion", antigravity: "notion@antigravity-plugins-partners" }, displayName: "Notion", tagline: "Pages, databases and lab notes", description: @@ -648,6 +653,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "atlassian", + agentStores: { antigravity: "atlassian-twg-cli@antigravity-plugins-partners" }, accountRequired: true, displayName: "Atlassian", tagline: "Confluence pages and Jira issues", @@ -677,7 +683,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ // sign-in: 401 OAuth id: "linear", accountRequired: true, - agentStores: { codex: "linear" }, + agentStores: { codex: "linear", antigravity: "linear@antigravity-plugins-partners" }, displayName: "Linear", tagline: "Issues, projects and cycles", description: @@ -691,6 +697,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "monday", + agentStores: { antigravity: "monday@antigravity-plugins-partners" }, accountRequired: true, displayName: "monday.com", tagline: "Boards, items and updates", @@ -705,6 +712,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "clickup", + agentStores: { antigravity: "clickup@antigravity-plugins-partners" }, accountRequired: true, displayName: "ClickUp", tagline: "Tasks, docs and workspaces", @@ -732,6 +740,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "granola", + agentStores: { antigravity: "granola@antigravity-plugins-partners" }, accountRequired: true, displayName: "Granola", tagline: "Your meeting notes", @@ -774,6 +783,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // sign-in: 401 OAuth id: "canva", + agentStores: { antigravity: "canva@antigravity-plugins-partners" }, accountRequired: true, displayName: "Canva", tagline: "Create and edit Canva designs", @@ -1245,6 +1255,7 @@ export const CURATED_SERVERS: ReadonlyArray = [ { // Verified 2026-10-28: vendor setup: https://help.dropbox.com/integrations/connect-dropbox-mcp-server. id: "dropbox", + agentStores: { antigravity: "dropbox@antigravity-plugins-partners" }, displayName: "Dropbox", tagline: "Search, read and organise Dropbox files", description: 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/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; +} 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, + }) + ); +} 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..bf24499d23 --- /dev/null +++ b/apps/server/src/scient/skills/antigravityPluginSkillProjection.test.ts @@ -0,0 +1,147 @@ +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, + 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; + 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)( + "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; + 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); + + // 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.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 link = linkAntigravityUserPlugins({ + profileDirectory: home.profileDirectory, + userHome: home.userHome, + platform: yield* HostProcess.Platform, + }); + // 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* 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 3738f486ad..aff7a3037e 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,41 @@ 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; +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. */ +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 +75,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 +108,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 +191,99 @@ 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, ""), + ); + +/** + * `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 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, + }), + ), + ); + }, +); 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/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..737d8f4a9d --- /dev/null +++ b/apps/web/src/components/chat/McpSignInAction.scient.browser.test.tsx @@ -0,0 +1,113 @@ +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 { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; +import { sameHostEnvironmentIdsAtom } from "../../scient/sameHost"; +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("../../scient/sameHost", () => ({ + sameHostEnvironmentIdsAtom: Atom.make>(new Set(["synthetic"])), +})); +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]: () => { + appAtomRegistry.set(sameHost, new Set(["synthetic"])); + fixture.start.mockReset(); + fixture.complete.mockReset(); + fixture.openExternal.mockReset(); + }, + }; +} + +const sameHost = sameHostEnvironmentIdsAtom as Atom.Writable>; + +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(); +}); + +// 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 63c5d9e49d..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 }), ); @@ -61,6 +65,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 +107,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 (!sameHost || 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 +173,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); + // 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; + const state = + entry.data === null || entry.data.installationStateKnown === false + ? "checking" + : route.state === "add" && plugin !== undefined + ? plugin.enabled + ? "added" + : "off" + : route.state; + return ( + + + + {route.label} + + {state === "added" + ? 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")} + + + {state === "checking" ? ( + + Checking… + + ) : state === "off" ? ( + plugin?.canSetEnabled ? ( + + ) : ( + + Off in Antigravity + + ) + ) : state === "added" ? null : entry.data?.disabledReason ? ( + // The line above says why it can't be added; offer where to act, never a dead button. + + ) : ( + + 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 +274,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..024b9593d1 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, ""); @@ -82,36 +86,39 @@ 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", chatgptAppId: "connector_2128aebfecb84f64a069897515042a44", claude: claudeConnectorFor("Gmail"), + stores: { antigravity: "gmail@antigravity-plugins-official" }, }, { id: "google-calendar", 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", chatgptAppId: "connector_947e0d954944416db111db556030eea6", claude: claudeConnectorFor("Google Calendar"), + stores: { antigravity: "gcalendar@antigravity-plugins-official" }, }, { id: "google-drive", 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", 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,22 +187,28 @@ 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, 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( - "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, + ...(antigravity ? { stores: { antigravity } } : {}), }; } @@ -239,13 +275,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 +294,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 +304,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 +500,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 +557,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; diff --git a/apps/web/src/scient/extensions/extensionActions.ts b/apps/web/src/scient/extensions/extensionActions.ts index 2fd062962d..ff70351ad2 100644 --- a/apps/web/src/scient/extensions/extensionActions.ts +++ b/apps/web/src/scient/extensions/extensionActions.ts @@ -472,13 +472,17 @@ export function useProviderPluginActions( ), uninstall: async () => { if (lock.locked || plugin.canUninstall !== true) return; + const name = plugin.displayName ?? plugin.name; + // Antigravity keeps one plugin folder per OS user, shared with the Antigravity app. const confirmed = await confirmDestructive( - m( - msg("Remove {name} from {agent}?", { - name: plugin.displayName ?? plugin.name, - agent: label, - }), - ), + provider.driver === "antigravity" + ? m( + msg( + "Remove {name} from Antigravity? It is removed from Antigravity for your user account on the computer Scient runs on, including the Antigravity app and every Antigravity agent there.", + { name }, + ), + ) + : m(msg("Remove {name} from {agent}?", { name, agent: label })), ); if (!confirmed) return; await lock.run("uninstall", () => diff --git a/apps/web/src/scient/extensions/extensionsView.ts b/apps/web/src/scient/extensions/extensionsView.ts index 4c6eb1e529..0fe39b1965 100644 --- a/apps/web/src/scient/extensions/extensionsView.ts +++ b/apps/web/src/scient/extensions/extensionsView.ts @@ -12,6 +12,7 @@ import { type ExtensionAudience, type ExtensionDeliverySkipReason, type ProviderInstanceId, + type ProviderStoreEntry, type ScientPluginSummary, type ServerProvider, type ServerProviderMcpServer, @@ -460,10 +461,13 @@ export function providerExtensionAudience( }; } -/** Who a store's plugin is for: Claude's stores serve Claude and Scient Agent, Codex's serve Codex. */ +/** + * Who a store's plugin is for: Claude's stores serve Claude and Scient Agent, Codex's serve Codex, + * and the Antigravity Marketplace serves Antigravity. + */ export function providerStoreAudience( provider: Pick, - kind: "shared" | "codex", + kind: ProviderStoreEntry["kind"], ): ExtensionAudience { return kind === "shared" ? { layer: "shared", ownerInstanceId: provider.instanceId } @@ -471,8 +475,11 @@ export function providerStoreAudience( layer: "agent", driver: provider.driver, instanceId: provider.instanceId, - label: "Codex", - reason: msg("Uses Codex’s own ChatGPT account"), + label: kind === "codex" ? "Codex" : "Antigravity", + reason: + kind === "codex" + ? msg("Uses Codex’s own ChatGPT account") + : msg("Installed through Antigravity’s own plugin manager"), }; } 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; +} 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-extensions.md b/docs/internals/scient-extensions.md index 36a04b6032..595aa41ed3 100644 --- a/docs/internals/scient-extensions.md +++ b/docs/internals/scient-extensions.md @@ -834,6 +834,56 @@ ServerProviderMcpServer { name; status: "connected" | "failed" | "needs-auth" | ChatGPT** opens `chatgpt.com/apps`. When the same service is also a delivered Scient connector, the agent currently receives both. +### Sign-in from a chat notice + +- **MCP servers (Codex, Claude)**: upstream's notice sign-in (`provider.mcpSignIn.*`). + `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, 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. +- **Codex homes**: chat and this inventory start app-servers of the same + instance with the same `CODEX_HOME`, the instance's effective (shadow) home, so + a chat sign-in is visible here. Read from Scient's code; Codex's own storage was + not checked against its source. Codex keeps MCP OAuth credentials in the OS + keyring by default, which does not depend on the home; with file storage they + 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`, + `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 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 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 + 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. 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 Scient Agent always uses Claude Code's plugins; there is no desktop switch. The @@ -898,6 +948,56 @@ limited to 64 KiB, checked for PNG/JPEG/WebP signatures, converted to has a five-second budget; a slow icon leaves the usual fallback tile. Signed logo URLs never reach the renderer. +### Antigravity Marketplace + +An Antigravity instance whose resolved runtime is the agy CLI exposes Google's +two public catalogs (`antigravity-plugins-official` and +`antigravity-plugins-partners`, fixed `www.gstatic.com` feeds, no sign-in). +Each feed is fetched without redirects, capped at 4 MiB, schema-decoded and +cached for ten minutes; a failed feed is a `sourceFailures` entry while the +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 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, +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 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 +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. + +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, 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/extensions.md b/docs/user/extensions.md index 0de2c5d171..53865318ca 100644 --- a/docs/user/extensions.md +++ b/docs/user/extensions.md @@ -13,7 +13,7 @@ extensions. (Gmail, Google Drive, Google Calendar, GitHub, Slack, Notion, Telegram, PubMed, Semantic Scholar, Exa, Playwright, Context7, Vercel and Cloudflare), then one section per kind of work, such as Papers & literature, Biology & medicine and Code & developer tools, followed by the features built into Scient and - each agent's store in its own section (**From Claude's store**, **From Codex's store**), and **Browse all MCP servers**, which lists the public MCP Registry. Select a + each agent's store in its own section (**From Claude's store**, **From Codex's store**, **From Antigravity's store**), and **Browse all MCP servers**, which lists the public MCP Registry. Select a section title to see the whole category. Search covers the catalog, the registry, and what you have already installed. - **Installed** lists what this environment already has, grouped by who manages @@ -286,6 +286,24 @@ Return to Scient afterwards and the rows update. Under the Installed table, **Add apps on ChatGPT** and **Add connectors on claude.ai** open each account's own page. Scient does not add Google's official MCP servers itself. +## Antigravity plugins + +**From the Antigravity Marketplace** lists Google's own Antigravity plugins and +partner plugins from other developers. It needs an Antigravity agent that uses +the agy command-line runtime; otherwise the store explains what to change. +Category pages show these plugins in **From Antigravity's store**. + +Choose **Add to Antigravity**. A partner plugin first says which developer makes +it; add it only if you trust them. The plugin goes into Antigravity's plugins +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 diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 6fb4a5c4cf..af842e39a3 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 @@ -192,6 +201,20 @@ visible. Google does not expose individual child status, names, models, usage, or reply ownership through ACP. A batch is not a separate controllable thread, and its launch description is not a child result. +## Sign in to a plugin + +When an Antigravity plugin such as Gmail needs you to sign in, its failed call adds a notice with +**Sign in to Gmail**. Choose it to open Google's sign-in page in your browser and approve access; +the running agent receives the approval itself. Then ask the agent to try again. The notice shows +**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 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 When your Antigravity runtime offers `/goal`, send `/goal` followed by a verifiable diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index f646faf121..a138b06c2d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -210,7 +210,7 @@ When an MCP server you added to Claude needs you to sign in, the thread shows a **Sign in**, once per session; on mobile, tap the notice. Approve access on the page it opens. Your browser then goes to a page that may not load, especially when Claude runs on another machine: copy that page's address, paste it into Scient, and choose **Finish sign-in**. Claude keeps the -sign-in and reconnects the server. Connectors you added on claude.ai are signed in on claude.ai, +sign-in and reconnects the server, and **Extensions** shows it signed in. Connectors you added on claude.ai are signed in on claude.ai, so Scient doesn't ask about them. Signing in needs permission to manage providers. ## Claude in Chrome diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index 48ba8d1a51..5bac98e081 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -147,12 +147,13 @@ 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. Your browser then goes -to a page that may not load, especially when Codex runs on another machine: 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; an instance with its own -home, such as a second account, may need to sign in separately. Signing in needs permission to -manage providers. +**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 +signed in. An instance with its own home, such as a second account, may need to sign in separately. +Signing in needs permission to manage providers. ## Use the OpenAI Chrome extension 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/provider.ts b/packages/contracts/src/provider.ts index 0505ff32d4..2dee567e96 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -72,7 +72,9 @@ export type ProviderMcpSignInStartResult = typeof ProviderMcpSignInStartResult.T export const ProviderMcpSignInCompleteInput = Schema.Struct({ ...ProviderMcpSignInStartInput.fields, /** The address the browser was sent to after approving, usually a localhost page. */ - callbackUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(16_384)), + // SCIENT-FORK:START — without it, wait for the agent to report its own callback page was opened. + callbackUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(16_384))), + // SCIENT-FORK:END }); export type ProviderMcpSignInCompleteInput = typeof ProviderMcpSignInCompleteInput.Type; 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/extensionAudience.ts b/packages/contracts/src/scient/extensionAudience.ts index 0a186fedca..c8675891aa 100644 --- a/packages/contracts/src/scient/extensionAudience.ts +++ b/packages/contracts/src/scient/extensionAudience.ts @@ -37,6 +37,8 @@ export type ExtensionAudience = typeof ExtensionAudience.Type; export const ExtensionAgentStores = Schema.Struct({ codex: Schema.optional(TrimmedNonEmptyString), + /** The Antigravity Marketplace entry id, `@`. */ + antigravity: Schema.optional(TrimmedNonEmptyString), }); export function supportsScientClaudePlugins(version: string | null | undefined): boolean { 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/contracts/src/scient/providerStore.ts b/packages/contracts/src/scient/providerStore.ts index 724a1449de..d82c3ccf30 100644 --- a/packages/contracts/src/scient/providerStore.ts +++ b/packages/contracts/src/scient/providerStore.ts @@ -22,14 +22,20 @@ export const ProviderStoreEntry = Schema.Struct({ description: Schema.String, tagline: Schema.optional(Schema.String), category: Schema.optional(Schema.String), - kind: Schema.Literals(["shared", "codex"]), + kind: Schema.Literals(["shared", "codex", "antigravity"]), installed: Schema.Boolean, + /** False when the agent's installed list could not be read; `installed` is then a guess. */ + installationStateKnown: Schema.optional(Schema.Boolean), + /** True when this agent cannot add from its store at all; `disabledReason` says why. */ + storeUnavailable: Schema.optional(Schema.Boolean), version: Schema.optional(Schema.String), publisher: Schema.optional(Schema.String), website: Schema.optional(Schema.String), iconUrl: Schema.optional(ExtensionIconDataUri), includes: Schema.Array(Schema.String), review: Schema.optional(Schema.Literals(["anthropic", "partner"])), + /** Who publishes it, from which of the store's catalogs listed it. */ + publisherType: Schema.optional(Schema.Literals(["google", "third-party"])), disabledReason: Schema.optional(Schema.String), authPolicy: Schema.optional(Schema.String), apps: Schema.Array(ProviderStoreApp), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 34de496ada..a10355e828 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,22 @@ 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?: ( + sessionId: string, + 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 +5453,48 @@ 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?.(sessionId, 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 +6817,12 @@ 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, + notification.sessionId, + event.toolCall.toolCallId, + ); } else if (event._tag === "PlanUpdated") { yield* emitPlan(context, event.payload, update.sessionUpdate !== "plan"); } else if (event._tag === "NoticeReceived") { @@ -11343,6 +11409,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..18fff04d90 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; @@ -737,7 +741,9 @@ export interface ProviderAdapterV2McpSignIn { readonly complete: (input: { readonly providerThread: OrchestrationV2ProviderThread; readonly server: string; - readonly callbackUrl: string; + // SCIENT-FORK:START — undefined waits, bounded, for the agent's own report that it finished. + readonly callbackUrl: string | undefined; + // SCIENT-FORK:END }) => Effect.Effect; } @@ -930,6 +936,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; +} diff --git a/scient-extensions-seams.json b/scient-extensions-seams.json index 7cefd8b245..8be84865c3 100644 --- a/scient-extensions-seams.json +++ b/scient-extensions-seams.json @@ -137,6 +137,11 @@ "anchor": "ProviderNativeInventory", "purpose": "Publish Claude's live plugin and MCP server inventory for its exact provider instance; resolve account capabilities before the cached Extensions account probe." }, + { + "path": "apps/server/src/provider/Drivers/AntigravityDriver.ts", + "anchor": "makeAntigravityInstancePlugins", + "purpose": "Attach the Antigravity Marketplace store and native plugin actions to the exact instance, run through the agy CLI it resolves." + }, { "path": "apps/server/src/provider/Drivers/CodexDriver.ts", "anchor": "makeCodexNativeInventory",