wip(antigravity): trusted /swarm request, flag and run selection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-23 22:46:51 -06:00
1 parent 55267905fc
commit 74d289db05
15 files changed
+221 -3

No files matched your search

@@ -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);
@@ -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<T extends Readonly<Record<string, unknown>>>(tools: readonly T[]): T[] {
return tools.filter(tool => !(typeof tool.name === "string" && DELEGATION_TOOL.test(tool.name)));
}
@@ -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",
}),
+8
View File
@@ -409,6 +409,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
cloudDefault: false,
selfHostedDefault: false,
},
enableAntigravitySwarm: {
title: "Google Antigravity swarm",
description:
"Let you start Google Antigravity's native swarm by writing /swarm at the start of a task or comment. Helpers change files only in the task folder and are approved automatically there. Local computers with a Google sign-in only.",
tier: "managed",
cloudDefault: false,
selfHostedDefault: false,
},
enableSandboxDuplexBridge: {
title: "Sandbox Duplex Bridge",
description:
+5
View File
@@ -156,6 +156,11 @@ export interface InstanceExperimentalSettings {
* declared, so behavior matches a client without it.
*/
enableMcpTasks: boolean;
/**
* Let a signed-in user start Google Antigravity's native swarm with `/swarm`
* in the task composer. Local hosts with a Google sign-in only. Default off.
*/
enableAntigravitySwarm: boolean;
/**
* @deprecated Compatibility-only. Provider WebSocket ingress now follows
* enableNativeRunner and this value has no runtime effect.
@@ -101,6 +101,8 @@ export const instanceExperimentalSettingsSchema = z.object({
// MCP Tasks (io.modelcontextprotocol/tasks): durable long provider calls.
// Off: Paperclip never declares the extension, so servers never return tasks.
enableMcpTasks: z.boolean().default(false),
// Trusted /swarm for Google Antigravity agents (Antigravity CLI route). Default off.
enableAntigravitySwarm: z.boolean().default(false),
// Deprecated compatibility key. Runner ingress follows enableNativeRunner;
// this remains accepted so older stored rows and managed configs keep loading.
enableRunnerPreviewIngress: z.boolean().default(false),
+5
View File
@@ -1215,6 +1215,11 @@ export const addIssueCommentSchema = z.object({
reopen: z.boolean().optional(),
resume: z.boolean().optional(),
interrupt: z.boolean().optional(),
/**
* A native command the signed-in user started with the composer's leading
* `/name` (parseLeadingUserCommand). Only "swarm" (Google Antigravity) exists.
*/
nativeCommand: z.literal("swarm").optional(),
});
export type AddIssueComment = z.infer<typeof addIssueCommentSchema>;
@@ -167,6 +167,7 @@ describe("instance settings service", () => {
enableOwnerInstanceAdmin: false,
enableSandboxDuplexBridge: false,
enableMcpTasks: false,
enableAntigravitySwarm: false,
enableRunnerPreviewIngress: false,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
+21
View File
@@ -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
@@ -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();
});
});
+113
View File
@@ -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<string, unknown>;
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<boolean> {
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<string | null> {
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<void> {
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<boolean> {
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;
}
@@ -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: {
+2
View File
@@ -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,
@@ -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");
@@ -438,6 +438,18 @@ export function InstanceExperimentalSettings() {
ariaLabel="Toggle durable app actions experimental setting"
/>
<ExperimentalToggleCard
title="Google Antigravity swarm"
description="Write /swarm at the start of a task or comment to a Google Antigravity agent to start its native swarm: a coordinator, helpers and a checker that work together in the task folder."
footnote="Local computers with a Google sign-in only. Helper changes inside the task folder are approved automatically; changes elsewhere are blocked."
checked={experimentalQuery.data?.enableAntigravitySwarm === true}
onCheckedChange={(checked) => toggleMutation.mutate({ enableAntigravitySwarm: checked })}
disabled={toggleMutation.isPending}
settingKey="enableAntigravitySwarm"
managed={managedKeys.enableAntigravitySwarm}
ariaLabel="Toggle Google Antigravity swarm experimental setting"
/>
<ExperimentalToggleCard
title="Enable Environments"
description="Show environment management in company settings and allow project and agent environment assignment controls."