From 74d289db05778261cb7f49fb2a700694691b1f00 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 23 Nov 2026 22:46:51 -0600 Subject: [PATCH] wip(antigravity): trusted /swarm request, flag and run selection Co-Authored-By: Claude Opus 5.5 --- .../acpx/antigravity-swarm-route.test.ts | 8 +- .../drivers/acpx/antigravity-swarm-route.ts | 8 ++ .../src/drivers/acpx/runtime-host.ts | 3 +- packages/shared/src/feature-catalog.ts | 8 ++ packages/shared/src/types/instance.ts | 5 + packages/shared/src/validators/instance.ts | 2 + packages/shared/src/validators/issue.ts | 5 + .../instance-settings-service.test.ts | 1 + server/src/routes/issues.ts | 21 ++++ server/src/services/antigravity-swarm.test.ts | 23 ++++ server/src/services/antigravity-swarm.ts | 113 ++++++++++++++++++ .../services/heartbeat/runtime-selection.ts | 8 ++ server/src/services/instance-settings.ts | 2 + .../native-runtime/native-execution-input.ts | 5 +- ui/src/pages/InstanceExperimentalSettings.tsx | 12 ++ 15 files changed, 221 insertions(+), 3 deletions(-) create mode 100644 server/src/services/antigravity-swarm.test.ts create mode 100644 server/src/services/antigravity-swarm.ts diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts index b682a7487c5..38b78c3aa84 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; -import { antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; +import { antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; import { createAcpxModeBinding, resolveAcpxProviderMode } from "./provider-mode.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; @@ -43,6 +43,12 @@ describe("Antigravity swarm route selection", () => { expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/Users/owner"); }); + it("keeps Paperclip delegation tools out of a swarm turn", () => { + const tools = ["paperclip_finish_task", "paperclip_block_task", "paperclip_create_task", "paperclip_create_issue", "paperclip_hire_agent", + "paperclip_read_task", "paperclip_call_assigned_tool", "paperclip_search_assigned_tools"].map(name => ({ name })); + expect(antigravitySwarmTools(tools).map(tool => tool.name)).toEqual(["paperclip_finish_task", "paperclip_block_task", "paperclip_read_task", "paperclip_call_assigned_tool", "paperclip_search_assigned_tools"]); + }); + it("routes a swarm turn to the CLI runtime instead of ACPX", async () => { const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-route-"))); roots.push(root); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts index 8ff0d97e89a..c0c9d6ace4d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts @@ -72,3 +72,11 @@ export function antigravitySwarmLaunchEnvironment( if ((input.platform ?? process.platform) === "darwin") environment.HOME = input.realHome ?? userInfo().homedir; return { ...environment, ...ANTIGRAVITY_CLI_DISTRIBUTION.environment }; } + +/** Paperclip tools that create tasks, assign work or hire. A swarm is one run with one assignee. */ +const DELEGATION_TOOL = /^paperclip_(?:create_(?:task|issue|subtask|agent)|hire|delegate|assign|reassign)/; + +/** The bridge catalog for a swarm turn: the run's tools without delegation. */ +export function antigravitySwarmTools>>(tools: readonly T[]): T[] { + return tools.filter(tool => !(typeof tool.name === "string" && DELEGATION_TOOL.test(tool.name))); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index bb17e5c876d..02828c543f2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -23,7 +23,7 @@ import { stageManagedGrokCredential } from "./grok-credentials.js"; import { stageManagedAntigravityCredential } from "./antigravity-credentials.js"; import { claudeNativeSkillPrompt } from "./native-skill-prompt.js"; import { prepareStdioMcpBindings } from "../stdio-mcp.js"; -import { antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; +import { antigravitySwarmLaunchEnvironment, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; import type { AcpRuntimeOptions, @@ -690,6 +690,7 @@ export class AcpxRuntimeHost { signal: options.signal, acquire: () => startRunnerToolBridge({ ...options.semanticTools!, + ...(swarmRoute && options.semanticTools!.tools ? { tools: antigravitySwarmTools(options.semanticTools!.tools) } : {}), preserveToolNames: options.assignedMcpTransport === "prp", preloadClaudeTaskTools: options.agent === "claude", }), diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts index 35d8a9a5f5d..017d4be12f1 100644 --- a/packages/shared/src/feature-catalog.ts +++ b/packages/shared/src/feature-catalog.ts @@ -409,6 +409,14 @@ export const INSTANCE_FEATURE_CATALOG: Record; diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.ts index 2b42f241364..f4f34788906 100644 --- a/server/src/__tests__/instance-settings-service.test.ts +++ b/server/src/__tests__/instance-settings-service.test.ts @@ -167,6 +167,7 @@ describe("instance settings service", () => { enableOwnerInstanceAdmin: false, enableSandboxDuplexBridge: false, enableMcpTasks: false, + enableAntigravitySwarm: false, enableRunnerPreviewIngress: false, enableWorktreeRunExecution: false, worktreeRunExecutionActivatedAt: null, diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 00d6b137e2a..c30ab4714ee 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -78,6 +78,7 @@ import { z } from "zod"; import { and, asc, desc, eq, inArray, isNull, notInArray, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import type { ChatChannelService } from "../services/chat-channels.js"; +import { ANTIGRAVITY_SWARM_COMMAND, ANTIGRAVITY_SWARM_UNAVAILABLE, antigravitySwarmCommentRefusal, recordAntigravitySwarmRequest } from "../services/antigravity-swarm.js"; import { activityLog, agentWakeupRequests, @@ -19326,6 +19327,18 @@ export function issueRoutes( "Issue not found", ); if (!issue) return; + // Trusted /swarm: the composer sends it as a structured field; comment text is never read as a command. + const swarmRequested = req.body.nativeCommand === ANTIGRAVITY_SWARM_COMMAND; + if (swarmRequested) { + if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Only a signed-in user can start a swarm"); + const refusal = issue.conversationAgentId + ? "Swarm works in task comments, not in chats." + : await antigravitySwarmCommentRefusal(db, issue); + if (refusal) { + res.status(422).json({ error: refusal, code: ANTIGRAVITY_SWARM_UNAVAILABLE }); + return; + } + } if (issue.conversationAgentId && req.actor.type === "board") { if (!req.actor.userId) throw forbidden("Board user access required"); if (req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can send messages or start a new session"); @@ -20047,6 +20060,12 @@ export function issueRoutes( comment, currentIssue.assigneeAgentId, ); + if (swarmRequested && req.actor.type === "board" && req.actor.userId) { + await recordAntigravitySwarmRequest(db, { + companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: comment.id, userId: req.actor.userId, + }); + } + const swarmWakeContext = swarmRequested ? { antigravitySwarmCommentId: comment.id } : {}; await revalidateActiveSourceRecoveryAfterCommittedWrite({ issue: currentIssue, @@ -20198,6 +20217,7 @@ export function issueRoutes( taskId: currentIssue.id, commentId: comment.id, wakeCommentId: comment.id, + ...swarmWakeContext, source: "issue.comment.reopen", wakeReason: "issue_reopened_via_comment", reopenedFrom: reopenFromStatus, @@ -20235,6 +20255,7 @@ export function issueRoutes( taskId: currentIssue.id, commentId: comment.id, wakeCommentId: comment.id, + ...swarmWakeContext, source: "issue.comment", wakeReason: "issue_commented", ...(resumeRequested === true diff --git a/server/src/services/antigravity-swarm.test.ts b/server/src/services/antigravity-swarm.test.ts new file mode 100644 index 00000000000..b56bfed47c3 --- /dev/null +++ b/server/src/services/antigravity-swarm.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { antigravitySwarmRefusal, requestedAntigravitySwarmCommentId } from "./antigravity-swarm.js"; + +const antigravity = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }; + +describe("trusted /swarm for Google Antigravity", () => { + it("is available only when the experimental flag is on, for a local Antigravity assignee", () => { + expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity })).toBeNull(); + expect(antigravitySwarmRefusal({ enabled: false, agent: antigravity })).toMatch(/not turned on/); + expect(antigravitySwarmRefusal({ enabled: true, agent: null })).toMatch(/Google Antigravity agent/); + expect(antigravitySwarmRefusal({ enabled: true, agent: { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } } })) + .toMatch(/Google Antigravity agent/); + expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity, remote: true })).toMatch(/this computer/); + }); + + it("reads a swarm request only from the wake's structured marker, never from comment text", () => { + const id = "6f1c1b0e-5a52-4b0a-9a51-0d6c9c3b2f11"; + expect(requestedAntigravitySwarmCommentId({ antigravitySwarmCommentId: id })).toBe(id); + expect(requestedAntigravitySwarmCommentId({ commentId: id, wakeCommentId: id })).toBeNull(); + expect(requestedAntigravitySwarmCommentId({ antigravitySwarmCommentId: "/swarm do it" })).toBeNull(); + expect(requestedAntigravitySwarmCommentId(null)).toBeNull(); + }); +}); diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts new file mode 100644 index 00000000000..cc559ec1b29 --- /dev/null +++ b/server/src/services/antigravity-swarm.ts @@ -0,0 +1,113 @@ +import { and, eq, sql } from "drizzle-orm"; +import { activityLog, agents, issueComments, type Db } from "@paperclipai/db"; +import { logActivity } from "./activity-log.js"; +import { instanceSettingsService } from "./instance-settings.js"; +import { PaperclipRunnerProviderProfileError } from "./native-runtime/provider-profile.js"; + +/** + * Google Antigravity's native `/swarm`, started only by a signed-in user. + * + * Source of trust: the task composer applies `parseLeadingUserCommand` (the + * one rule, packages/shared) to what the user typed and submits a structured + * `nativeCommand: "swarm"`. The server accepts it only from a signed-in board + * user, records the request in the activity log (server-written only) and + * marks the assignee's wake with the comment id. A run is a swarm only when + * that record exists. Comment text is never read as a command here, so + * pasted, quoted, agent or API text stays text. + * + * A requested swarm that cannot run is refused with a plain message; it is + * never run as an ordinary request. + */ +export const ANTIGRAVITY_SWARM_COMMAND = "swarm" as const; +export const ANTIGRAVITY_SWARM_UNAVAILABLE = "antigravity_swarm_unavailable"; + +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; + +export function isAntigravityAgent(agent: { adapterType: string; adapterConfig: unknown } | null): boolean { + const config = record(agent?.adapterConfig); + return agent?.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity"; +} + +export function antigravitySwarmRefusal(input: { + enabled: boolean; + agent: { adapterType: string; adapterConfig: unknown } | null; + remote?: boolean; +}): string | null { + if (!input.enabled) { + return "Swarm is not turned on for this Paperclip. An instance admin can turn on \"Google Antigravity swarm\" in Settings, Experimental."; + } + if (!isAntigravityAgent(input.agent)) return "Swarm works only for tasks assigned to a Google Antigravity agent."; + if (input.remote) return "Swarm is not available for this agent: it runs only on this computer, not in a cloud or remote environment."; + return null; +} + +/** The comment id a wake carries when the user asked for a swarm. Verified against the activity log before use. */ +export function requestedAntigravitySwarmCommentId(context: unknown): string | null { + const value = record(context).antigravitySwarmCommentId; + return typeof value === "string" && /^[0-9a-f-]{36}$/i.test(value) ? value : null; +} + +export const ANTIGRAVITY_SWARM_REQUESTED_ACTION = "issue.antigravity_swarm_requested"; + +async function swarmEnabled(db: Db): Promise { + return (await instanceSettingsService(db).getExperimentalReadOnly()).enableAntigravitySwarm === true; +} + +/** Comment-time check, so an unavailable swarm is refused before anything is posted. */ +export async function antigravitySwarmCommentRefusal(db: Db, issue: { companyId: string; assigneeAgentId: string | null }): Promise { + const [agent] = issue.assigneeAgentId + ? await db.select({ adapterType: agents.adapterType, adapterConfig: agents.adapterConfig }).from(agents) + .where(and(eq(agents.id, issue.assigneeAgentId), eq(agents.companyId, issue.companyId))) + : []; + return antigravitySwarmRefusal({ enabled: await swarmEnabled(db), agent: agent ?? null }); +} + +/** + * Run-time decision for the run a comment woke. Returns true when this run is + * the user's swarm. Throws a plain-language failure when the swarm was asked + * for but cannot run here, so the run is not silently an ordinary request. + */ +export async function recordAntigravitySwarmRequest(db: Db, input: { companyId: string; issueId: string; commentId: string; userId: string }): Promise { + await logActivity(db, { + companyId: input.companyId, actorType: "user", actorId: input.userId, issueId: input.issueId, + action: ANTIGRAVITY_SWARM_REQUESTED_ACTION, entityType: "issue", entityId: input.issueId, + details: { commentId: input.commentId, summary: "Asked the Google Antigravity agent to run a swarm." }, + }); +} + +/** + * Run-time decision for the run a comment woke. Returns true when this run is + * the user's swarm. Throws a plain-language failure when the swarm was asked + * for but cannot run here, so the run is not silently an ordinary request. + */ +export async function resolveAntigravitySwarmRun(db: Db, input: { + companyId: string; + issueId: string; + runId: string; + agent: { id: string; adapterType: string; adapterConfig: unknown }; + context: unknown; + remote: boolean; +}): Promise { + const commentId = requestedAntigravitySwarmCommentId(input.context); + if (!commentId) return false; + const [requested] = await db.select({ id: activityLog.id }).from(activityLog) + .innerJoin(issueComments, and(eq(issueComments.id, commentId), eq(issueComments.issueId, input.issueId), eq(issueComments.companyId, input.companyId))) + .where(and(eq(activityLog.companyId, input.companyId), eq(activityLog.action, ANTIGRAVITY_SWARM_REQUESTED_ACTION), + eq(activityLog.entityId, input.issueId), eq(activityLog.actorType, "user"), eq(activityLog.actorId, issueComments.authorUserId), + sql`${activityLog.details}->>'commentId' = ${commentId}`)) + .limit(1); + if (!requested) return false; + const refusal = antigravitySwarmRefusal({ enabled: await swarmEnabled(db), agent: input.agent, remote: input.remote }); + if (refusal) throw new PaperclipRunnerProviderProfileError(ANTIGRAVITY_SWARM_UNAVAILABLE, refusal); + await logActivity(db, { + companyId: input.companyId, actorType: "system", actorId: "paperclip", agentId: input.agent.id, runId: input.runId, + issueId: input.issueId, action: "issue.antigravity_swarm_started", entityType: "issue", entityId: input.issueId, + details: { + commentId, + summary: "Started a Google Antigravity swarm with helpers. Helper actions inside the task folder are approved automatically; actions outside it are blocked. Usage is reported as one total for the coordinator and its helpers.", + }, + }); + return true; +} diff --git a/server/src/services/heartbeat/runtime-selection.ts b/server/src/services/heartbeat/runtime-selection.ts index f55c5b40e59..1bd2d9981cf 100644 --- a/server/src/services/heartbeat/runtime-selection.ts +++ b/server/src/services/heartbeat/runtime-selection.ts @@ -1,4 +1,5 @@ import { assertPaperclipRunnerBinaryConfiguration } from "../native-runtime/native-codex-runner.js"; +import { resolveAntigravitySwarmRun } from "../antigravity-swarm.js"; import { antigravityForcesSameSessionRecovery } from "../native-runtime/antigravity-release.js"; import { readNativeWorkspaceMigration, migratedNativeExecutionCwd } from "../native-runtime/native-workspace-migration.js"; import { resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js"; @@ -836,6 +837,12 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele } const workspaceMigration = persistedExecutionWorkspace?.metadata?.nativeWorkspaceMigration ? await readNativeWorkspaceMigration(db, { companyId: agent.companyId, id: nativeExecutionWorkspaceId }) : null; + // A trusted /swarm runs Google Antigravity's native swarm on the CLI route. + const antigravitySwarm = agent.adapterType === "paperclip_runner" + && await resolveAntigravitySwarmRun(db, { + companyId: agent.companyId, issueId: issueRef.id, runId: run.id, agent, + context, remote: executionTarget?.kind === "remote", + }); const buildExecution = ({ normalizedSessionId, resumedSession }: { normalizedSessionId: string; resumedSession: boolean }) => buildNativeExecutionInput({ agentKeyId: agentIdentity?.keyId, @@ -919,6 +926,7 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele } : null, ...nativeProvider, + ...(antigravitySwarm ? { antigravitySwarm: true } : {}), lifecyclePolicy: effectiveLifecyclePolicy, interactionResponses, completionContract: { diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index 2fe5d05f781..eb256c8d522 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -298,6 +298,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableOwnerInstanceAdmin: parsed.data.enableOwnerInstanceAdmin ?? false, enableSandboxDuplexBridge: parsed.data.enableSandboxDuplexBridge ?? false, enableMcpTasks: parsed.data.enableMcpTasks ?? false, + enableAntigravitySwarm: parsed.data.enableAntigravitySwarm ?? false, enableRunnerPreviewIngress: parsed.data.enableRunnerPreviewIngress ?? false, enableWorktreeRunExecution: parsed.data.enableWorktreeRunExecution ?? false, worktreeRunExecutionActivatedAt: parsed.data.worktreeRunExecutionActivatedAt ?? null, @@ -360,6 +361,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableOwnerInstanceAdmin: false, enableSandboxDuplexBridge: false, enableMcpTasks: false, + enableAntigravitySwarm: false, enableRunnerPreviewIngress: false, enableWorktreeRunExecution: false, worktreeRunExecutionActivatedAt: null, diff --git a/server/src/services/native-runtime/native-execution-input.ts b/server/src/services/native-runtime/native-execution-input.ts index 9e71e45cf50..594c3a0102c 100644 --- a/server/src/services/native-runtime/native-execution-input.ts +++ b/server/src/services/native-runtime/native-execution-input.ts @@ -107,6 +107,8 @@ export interface BuildNativeExecutionInput { opencodePermissionMode?: NativeOpenCodePermissionMode; acpxPermissionMode?: NativeAcpxPermissionMode; acpxSessionMode?: "agent" | "plan" | "ask"; + /** Set only for a run the signed-in user started with a trusted /swarm (services/antigravity-swarm.ts). */ + antigravitySwarm?: boolean; piThinkingLevel?: "off" | "low" | "high" | "max"; claudeEffort?: "low" | "medium" | "high" | "xhigh" | "max"; grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh"; @@ -148,7 +150,8 @@ export function buildNativeExecutionInput(input: BuildNativeExecutionInput): Nat if (input.issue.workMode !== "standard" && input.issue.workMode !== "planning" && input.issue.workMode !== "ask" && input.issue.workMode !== "skill_test") { throw new Error("native_execution_input_invalid: issue work mode must be standard, planning, ask, or skill_test"); } - const mode = resolvePaperclipRunnerCursorMode(input.provider, input.acpxAgent, input.acpxSessionMode); + const mode = input.antigravitySwarm === true && input.provider === "acpx" && input.acpxAgent === "antigravity" + ? "swarm" : resolvePaperclipRunnerCursorMode(input.provider, input.acpxAgent, input.acpxSessionMode); const piThinkingLevel = resolvePaperclipRunnerPiThinkingLevel(input.provider, input.acpxAgent, input.piThinkingLevel); const executionMode = input.executionMode ?? (input.issue.workMode === "planning" ? "plan" : "default"); diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx index a134d5e7066..a38db1c8e7b 100644 --- a/ui/src/pages/InstanceExperimentalSettings.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.tsx @@ -438,6 +438,18 @@ export function InstanceExperimentalSettings() { ariaLabel="Toggle durable app actions experimental setting" /> + toggleMutation.mutate({ enableAntigravitySwarm: checked })} + disabled={toggleMutation.isPending} + settingKey="enableAntigravitySwarm" + managed={managedKeys.enableAntigravitySwarm} + ariaLabel="Toggle Google Antigravity swarm experimental setting" + /> +