feat(antigravity): show account usage (#10232)

* feat(antigravity): show account usage

Resolve the provider launch for usage discovery and report quota windows from agy.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(usage): clear reports when a provider executable is missing

Usage discovery treated a missing executable as a transient error and kept the previous account report. Treat the unresolved launch as absent so the next refresh removes that report.

---------

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-20 11:57:43 +07:00
1 parent cba515ef73
commit 1972864b19
16 files changed
+400 -5

No files matched your search

+5 -1
View File
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
import { z, type ZodType } from "zod";
import { ProviderLaunchSchema } from "./provider.js";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
export interface UsageWindow {
@@ -65,12 +66,13 @@ export interface UsageAccount {
}
export const UsageScopeSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("global") }),
z.object({ kind: z.literal("global"), launch: ProviderLaunchSchema.optional() }),
z.object({
kind: z.literal("session"),
provider: z.string(),
model: z.string().optional(),
env: z.record(z.string(), z.string()),
launch: ProviderLaunchSchema.optional(),
}),
]);
export type UsageScope = z.infer<typeof UsageScopeSchema>;
@@ -79,6 +81,8 @@ export interface UsageSourceRegistration {
id: string;
label: string;
icon?: string;
/** Provider whose resolved launch is needed for discovery. */
provider?: string;
input: ZodType;
/** Accounts for this scope only. The same key in any scope identifies the same account. */
discover(scope: UsageScope): Promise<UsageAccount[]>;
@@ -699,6 +699,7 @@ export interface AgentPermissionResult {
}
export interface AgentUsageSession {
launch?: import("@getpaseo/plugin/server/provider").ProviderLaunch;
provider: string;
model?: string;
env: Record<string, string>;
@@ -849,6 +850,9 @@ export interface AgentClientUpdateContext extends AgentClientInstallationContext
}
export interface AgentClient {
resolveUsageLaunch?(): Promise<
import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined
>;
readonly provider: AgentProvider;
readonly capabilities: AgentCapabilityFlags;
/**
@@ -2512,6 +2512,30 @@ describe("plugin provider launch and status", () => {
}
});
test("exposes the session launch for usage discovery", async () => {
const harness = createProviderHarness();
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([{ ...harness.registration, command: [process.execPath, "acp"] }]);
try {
const client = registry.clients()[harness.registration.id]!;
const session = await client.createSession(
{ provider: harness.registration.id, cwd: "/workspace" },
{ env: { HOME: "/session-home" } },
);
expect(session.usageSession?.()).toMatchObject({
provider: harness.registration.id,
model: "plugin-model",
env: { HOME: "/session-home" },
launch: { command: process.execPath, args: ["acp"], env: { HOME: "/session-home" } },
sessionKey: expect.any(String),
});
await session.close();
expect(session.usageSession?.()).toBeNull();
} finally {
await registry.shutdown();
}
});
test("resolves relative executable paths before sending launch data", async () => {
const harness = createProviderHarness();
const launches: Array<ProviderLaunch | undefined> = [];
@@ -137,6 +137,7 @@ function isProviderRequestReply(
class ProviderRuntime {
private connection: ProviderConnection | null = null;
connectedLaunch: ProviderLaunch | undefined;
private connecting: Promise<ProviderConnection> | null = null;
private closed = false;
private generation = 0;
@@ -192,6 +193,12 @@ class ProviderRuntime {
return { command: launch.command, args: launch.args, env: launch.env };
}
async resolveUsageLaunch(): Promise<ProviderLaunch | undefined> {
const launch = await this.resolveEffectiveLaunch();
if (!launch?.resolved) return undefined;
return { command: launch.command, args: launch.args, env: launch.env };
}
async inspectInstallation(signal: AbortSignal): Promise<ProviderInspection> {
const inspect = this.registration.installation?.inspect;
if (!inspect) throw new Error("Provider does not report its installation");
@@ -425,8 +432,9 @@ class ProviderRuntime {
}
private async establishConnection(generation: number): Promise<ProviderConnection> {
const launch = await this.resolveLaunch();
const rawConnection = await this.registration.connect({
launch: await this.resolveLaunch(),
launch,
versions: [PROVIDER_PROTOCOL_VERSION],
capabilities: PROVIDER_CAPABILITIES,
});
@@ -440,6 +448,7 @@ class ProviderRuntime {
await rawConnection.close().catch(() => undefined);
throw error;
}
this.connectedLaunch = launch;
const connection = normalizeConnection(rawConnection);
const unsubscribe = connection.onEvent((event) => this.accept(event));
if (this.closed || generation !== this.generation) {
@@ -1032,6 +1041,10 @@ class PluginAgentClient implements AgentClient {
this.runtime.onSessionOpened((session, opened) => this.acceptChild(session, opened));
}
resolveUsageLaunch() {
return this.runtime.resolveUsageLaunch();
}
get capabilities(): AgentCapabilityFlags {
return agentCapabilities(this.runtime.negotiatedCapabilities);
}
@@ -1197,6 +1210,12 @@ class PluginAgentClient implements AgentClient {
},
bind,
config.settings,
this.runtime.connectedLaunch
? {
...this.runtime.connectedLaunch,
env: { ...this.runtime.connectedLaunch.env, ...config.env },
}
: undefined,
);
bind(bridge);
return session;
@@ -1297,6 +1316,7 @@ class PluginAgentSession implements AgentSession {
) => Promise<ProviderRuntimeSession>,
private readonly onBind: (bridge: ProviderRuntimeSession) => void,
givenOptions: Readonly<Record<string, JsonValue>>,
private readonly usageLaunch: ProviderLaunch | undefined,
) {
this.subagentIdsBySession.set(bridge.id, null);
// Every setting the session opened with that was not given, including ones nobody set.
@@ -1312,6 +1332,17 @@ class PluginAgentSession implements AgentSession {
this.unsubscribe = bridge.onEvent((event) => this.accept(event, true));
}
usageSession() {
if (this.closed || !this.usageLaunch) return null;
return {
provider: this.provider,
model: this.bridge.config.model,
env: this.usageLaunch.env,
launch: this.usageLaunch,
sessionKey: this.bridge.id,
};
}
get id(): string {
return this.describePersistence()?.sessionId ?? this.bridge.id;
}
@@ -623,6 +623,7 @@ function wrapClientProvider(
unarchiveNativeSession: unarchiveNativeSession
? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider })
: undefined,
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
isAvailable: (signal, options) => inner.isAvailable(signal, options),
getDiagnostic: inner.getDiagnostic?.bind(inner),
@@ -473,6 +473,12 @@ export class ProviderSnapshotManager {
return client;
}
async resolveUsageLaunch(provider: string) {
const definition = this.generation.definitions[provider];
if (!definition?.enabled) return undefined;
return this.ensureClient(provider, definition).resolveUsageLaunch?.();
}
async listProviders(input: ProviderSnapshotReadOptions = {}): Promise<ProviderSnapshotEntry[]> {
const target = resolveProviderSnapshotTarget(input.cwd);
if (input.wait) {
+1
View File
@@ -677,6 +677,7 @@ export async function createPaseoDaemon(
usageAgents: {
hasAgent: (id) => agentManager.getAgent(id) !== null,
usageSession: (id) => agentManager.usageSession(id),
resolveLaunch: (provider) => providerSnapshotManager.resolveUsageLaunch(provider),
},
managedSources: new ManagedPluginSources(config.paseoHome, {
registries: config.pluginRegistries,
+28 -1
View File
@@ -669,12 +669,39 @@ export class PluginService {
const registered: string[] = [];
try {
for (const source of metadata) {
if (
source.provider &&
!this.runtime
.getProviderRegistrations?.(pluginId)
.some((provider) => provider.id === source.provider)
) {
throw new Error(
`Usage source ${source.id} references a provider outside plugin ${pluginId}`,
);
}
this.usageSources.register({
id: source.id,
label: source.label,
icon: source.icon,
discover: async (scope) => {
const result = await this.runtime.discoverUsage(pluginId, source.id, scope);
const launch =
scope.kind === "global" && source.provider
? await this.dependencies.usageAgents?.resolveLaunch?.(source.provider)
: undefined;
const scoped =
scope.kind === "session" && source.provider !== scope.provider
? {
kind: "session" as const,
provider: scope.provider,
model: scope.model,
env: scope.env,
}
: scope;
const result = await this.runtime.discoverUsage(
pluginId,
source.id,
scoped.kind === "global" && launch ? { ...scoped, launch } : scoped,
);
if (!Array.isArray(result))
throw new Error(`Invalid usage discovery from ${source.id}`);
return result;
@@ -41,6 +41,7 @@ export interface PluginProviderInstallationMetadata {
export interface PluginUsageSourceMetadata {
id: string;
label: string;
provider?: string;
icon?: string;
}
@@ -175,6 +176,7 @@ const usageSourceMetadataSchema = z
.object({
id: z.string().min(1),
label: z.string().min(1),
provider: z.string().min(1).optional(),
icon: z.string().optional(),
})
.strict();
@@ -448,6 +448,7 @@ export function createPluginWorker(options: {
.map(async (source) => ({
id: source.id,
label: source.label,
provider: source.provider,
icon: source.icon
? await readPluginProviderIcon(message.pluginDirectory, source.icon)
: undefined,
@@ -410,3 +410,57 @@ dns.lookup = function(host, ...args) {
},
60_000,
);
test("resolves a plugin provider launch for cold usage discovery", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-usage-launch-"));
const directory = path.join(root, "launch-source");
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: "launch-source", requirements: { paseo: ">=0.9.2" } }),
);
await writeFile(
path.join(directory, "index.server.ts"),
`
import { z } from 'zod';
export default function contribute(server) {
server.registerProvider({ id: 'usage-launch-fixture', label: 'Launch fixture', command: [${JSON.stringify(process.execPath)}, 'fixture-arg'], connect: async () => { throw new Error('Must not connect'); } });
server.registerUsageSource({ id: 'launch-fixture', label: 'Launch fixture', provider: 'usage-launch-fixture', input: z.object({}),
discover: async scope => scope.kind === 'global' && scope.launch?.args[0] === 'fixture-arg' ? [{ key: 'default', input: {} }] : [],
fetch: async () => ({ status: 'available', windows: [{ id: 'weekly', label: 'Weekly', usedPct: 12 }] }) });
return () => {};
}`,
);
const daemon = await createTestPaseoDaemon({
daemonVersion: "0.16.2",
pluginsEnabled: false,
builtinPlugins: new BuiltinPluginLoader(root, ["launch-source"]),
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.16.2",
});
try {
await client.connect();
const result = await client.listUsageReports();
expect(result.reports).toContainEqual(
expect.objectContaining({
id: "launch-fixture:default",
report: expect.objectContaining({
status: "available",
windows: [{ id: "weekly", label: "Weekly", usedPct: 12 }],
}),
}),
);
await client.patchDaemonConfig({
providers: {
"usage-launch-fixture": { command: [path.join(root, "missing-cli")] },
},
});
expect((await client.listUsageReports()).reports).toEqual([]);
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true });
}
}, 60_000);
@@ -33,6 +33,9 @@ interface KnownReport {
export interface AgentUsageLookup {
hasAgent(id: string): boolean;
usageSession(id: string): AgentUsageSession | null;
resolveLaunch?(
provider: string,
): Promise<import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined>;
}
export interface ListUsageReportsOptions {
@@ -134,6 +137,7 @@ export class UsageSourceRegistry {
provider: session.provider,
model: session.model,
env: session.env,
launch: session.launch,
});
const current = this.agents.usageSession(agentId);
if (
@@ -1,7 +1,10 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { Usage } from "./server/usage.js";
import { createAntigravityProvider } from "./server/provider.js";
export default function contribute(server: PluginServerContext) {
const usage = new Usage();
server.registerUsageSource(usage.registration());
server.registerProvider(createAntigravityProvider());
return () => {};
}
@@ -0,0 +1,101 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, it } from "vitest";
import { Usage } from "./usage.js";
const directories: string[] = [];
afterEach(async () => {
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true })));
});
it("discovers the resolved account and maps the CLI's quota buckets", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-"));
directories.push(directory);
const cli = path.join(directory, "cli.cjs");
await writeFile(
cli,
`
if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(['-p', '/usage', '--output-format', 'json'])) process.exit(2);
console.log(JSON.stringify({ status: 'SUCCESS', command: { name: 'usage', data: { groups: [
{ name: 'Gemini Models', buckets: [
{ id: 'gemini-5h', name: 'Five Hour Limit Remaining', window: '5h', remaining_fraction: 0.25, reset_time: '2026-11-19T14:25:08Z' },
{ id: 'gemini-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 0.7 },
{ id: 'disabled', name: 'Weekly', window: 'weekly', disabled: true, remaining_fraction: 1 }
] }
] } } }));
`,
);
const usage = new Usage();
const launch = {
command: process.execPath,
args: [cli, "acp", "--disable-telemetry"],
env: { HOME: directory },
};
const source = usage.registration();
const accounts = await source.discover({ kind: "global", launch });
expect(accounts).toHaveLength(1);
expect(
await source.discover({
kind: "session",
provider: "antigravity",
env: { HOME: directory },
launch,
}),
).toEqual(accounts);
expect(
await source.discover({
kind: "session",
provider: "antigravity",
env: { HOME: `${directory}-other` },
}),
).toEqual([]);
expect(
await source.discover({ kind: "session", provider: "codex", env: { HOME: directory } }),
).toEqual([]);
const otherLaunch = { ...launch, env: { HOME: `${directory}-other` } };
const other = await source.discover({
kind: "session",
provider: "antigravity",
env: otherLaunch.env,
launch: otherLaunch,
});
expect(other[0]?.key).not.toBe(accounts[0]?.key);
expect(other[0]?.input).not.toEqual(accounts[0]?.input);
expect(await source.fetch(accounts[0]!.input)).toMatchObject({
status: "available",
windows: [
{ id: "gemini-5h", usedPct: 75, remainingPct: 25, resetsAt: "2026-11-19T14:25:08Z" },
{ id: "gemini-weekly", usedPct: expect.closeTo(30), summary: true },
{ id: "disabled", usedPct: null, remainingPct: null },
],
});
});
it("surfaces CLI errors instead of reporting a successful quota", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-"));
directories.push(directory);
const cli = path.join(directory, "cli.cjs");
await writeFile(
cli,
`console.log(JSON.stringify({ status: 'ERROR', error: 'Authentication required' }));`,
);
const usage = new Usage();
const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } };
const source = usage.registration();
const [account] = await source.discover({ kind: "global", launch });
await expect(source.fetch(account!.input)).rejects.toThrow("Authentication required");
});
it("reports a failed CLI without exposing its stderr", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-"));
directories.push(directory);
const cli = path.join(directory, "cli.cjs");
await writeFile(cli, `process.stderr.write('authentication token=private'); process.exit(1);`);
const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } };
const source = new Usage().registration();
const [account] = await source.discover({ kind: "global", launch });
await expect(source.fetch(account!.input)).rejects.toThrow(
"Antigravity usage command failed or timed out. Check that agy is signed in.",
);
});
@@ -0,0 +1,120 @@
import { homedir } from "node:os";
import path from "node:path";
import { z } from "zod";
import { execCommand } from "@getpaseo/plugin/server";
import type { ProviderLaunch } from "@getpaseo/plugin/server/provider";
import {
hashAccountKey,
toneFromUsedPct,
unavailable,
windowFromUsedPct,
type UsageSourceRegistration,
} from "@getpaseo/plugin/server/usage";
const input = z.object({ launch: z.string() }).strict();
const response = z.object({
status: z.string(),
error: z.string().optional(),
response: z.string().optional(),
command: z
.object({
name: z.literal("usage"),
data: z.object({
groups: z.array(
z.object({
name: z.string(),
buckets: z.array(
z.object({
id: z.string().min(1),
name: z.string(),
window: z.string(),
remaining_fraction: z.number().min(0).max(1).nullish(),
reset_time: z.string().nullish(),
disabled: z.boolean().optional(),
}),
),
}),
),
}),
})
.optional(),
});
function accountKey(env: ProviderLaunch["env"]): string {
return hashAccountKey(
path.resolve(
env.ANTIGRAVITY_HOME ?? path.join(env.HOME ?? homedir(), ".gemini", "antigravity-cli"),
),
);
}
export class Usage {
private readonly launches = new Map<string, ProviderLaunch>();
registration(): UsageSourceRegistration {
return {
id: "antigravity",
label: "Antigravity",
icon: "icon.svg",
input,
provider: "antigravity",
discover: async (scope) => {
if (scope.kind === "session" && scope.provider !== "antigravity") return [];
if (!scope.launch) return [];
const launch = scope.launch;
const key = accountKey(launch.env);
const locator = hashAccountKey(JSON.stringify(launch));
this.launches.set(locator, launch);
return [{ key, input: { launch: locator } }];
},
fetch: async (value) => {
const { launch: locator } = input.parse(value);
const launch = this.launches.get(locator);
if (!launch) throw new Error("Antigravity launch no longer exists");
const acpIndex = launch.args.indexOf("acp");
if (acpIndex < 0) throw new Error("Antigravity launch does not contain the acp subcommand");
let result;
try {
result = await execCommand(
launch.command,
[...launch.args.slice(0, acpIndex), "-p", "/usage", "--output-format", "json"],
{
env: launch.env,
timeout: 18_000,
maxBuffer: 1024 * 1024,
},
);
} catch {
throw new Error(
"Antigravity usage command failed or timed out. Check that agy is signed in.",
);
}
const data = response.parse(JSON.parse(result.stdout));
if (data.status !== "SUCCESS") {
throw new Error(data.error || data.response || `agy usage returned ${data.status}`);
}
if (!data.command) throw new Error("agy did not return usage data");
const windows = data.command.data.groups.flatMap((group) =>
group.buckets.flatMap((bucket) => {
if (!bucket.disabled && bucket.remaining_fraction == null) return [];
const used = bucket.disabled ? null : (1 - bucket.remaining_fraction!) * 100;
return [
windowFromUsedPct({
id: bucket.id,
label: `${group.name} · ${bucket.name}${bucket.disabled ? " · Disabled" : ""}`,
shortLabel: `${group.name} ${bucket.window}`,
summary: !bucket.disabled && bucket.window === "weekly",
utilizationPct: used,
resetsAt: bucket.disabled ? null : bucket.reset_time,
tone: used === null ? "default" : toneFromUsedPct(used),
}),
];
}),
);
if (windows.length === 0)
return unavailable({ kind: "no_quota", detail: "No usage quota reported by agy" });
return { status: "available", windows };
},
};
}
}
+14 -2
View File
@@ -504,6 +504,11 @@ offers `updateUrl` on the same terms.
`server.registerUsageSource()`. Import its contract and helpers from
`@getpaseo/plugin/server/usage`.
A source that needs its plugin's provider command may set `provider` to that provider's ID.
The daemon supplies the resolved launch in `scope.launch` for global discovery and for that
provider's sessions. The launch includes the trusted process environment; keep it daemon-side and
use an opaque store locator as the input. It is absent when the provider is unavailable.
A source implements two calls:
```ts
@@ -515,13 +520,20 @@ interface UsageAccount {
}
type UsageScope =
| { kind: "global" }
| { kind: "session"; provider: string; model?: string; env: Record<string, string> };
| { kind: "global"; launch?: ProviderLaunch }
| {
kind: "session";
provider: string;
model?: string;
env: Record<string, string>;
launch?: ProviderLaunch;
};
interface UsageSourceRegistration {
id: string;
label: string;
icon?: string;
provider?: string;
input: ZodType;
discover(scope: UsageScope): Promise<UsageAccount[]>;
fetch(input: unknown): Promise<UsageReport>;