Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,32 +212,6 @@ describe("acpPerTurnPromptUsage", () => {
reasoningTokens: 3,
},
);
// Antigravity 1.5+: inputTokens excludes cached reads, while outputTokens already includes thinking.
assert.deepEqual(
acpPerTurnPromptUsage(
{
inputTokens: 2181,
outputTokens: 23,
totalTokens: 14323,
cachedReadTokens: 12119,
cachedWriteTokens: 0,
thoughtTokens: 19,
},
false,
"completed",
true,
),
{
usageScope: "main_agent",
usageStatus: "complete",
hasSubagents: false,
inputTokens: 14300,
outputTokens: 23,
cachedInputTokens: 12119,
cacheCreationTokens: 0,
reasoningTokens: 19,
},
);
});

it("clamps subsets that exceed their parents and drops unset counters", () => {
Expand Down
138 changes: 138 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2624,3 +2624,141 @@ describe("AntigravityAdapterV2 session system prompt", () => {
}).pipe(Effect.provide(layerSession)),
);
});

describe("AntigravityAdapterV2 prompt usage", () => {
it.effect("counts cache reads and writes in the turn's input tokens", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
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"];
const instanceId = ProviderInstanceId.make("antigravity-prompt-usage-test");
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,
// Antigravity 1.5+ reports inputTokens without the cached reads and writes.
prompt: () =>
Effect.succeed({
stopReason: "end_turn" as const,
usage: {
inputTokens: 100,
outputTokens: 23,
totalTokens: 5923,
cachedReadTokens: 5000,
cachedWriteTokens: 800,
thoughtTokens: 19,
},
}),
})),
),
withProcess: (_stop, task) => task,
defaultModel: Effect.undefined,
});
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-usage-" });
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: workspace,
});
const threadId = ThreadId.make("thread-antigravity-prompt-usage");
const modelSelection = { instanceId, model: "gemini-test-low" } as const;
const session = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-antigravity-prompt-usage"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* session.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const completed = yield* session.events.pipe(
Stream.filter(
(event) =>
event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
),
Stream.runHead,
Effect.forkScoped({ startImmediately: true }),
);
const now = yield* DateTime.now;
yield* session
.startTurn({
appThread: {
createdBy: "user",
creationSource: "web",
id: threadId,
projectId: ProjectId.make("project-antigravity-prompt-usage"),
title: "Antigravity prompt usage",
providerInstanceId: instanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
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-prompt-usage"),
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId: RunAttemptId.make("attempt-antigravity-prompt-usage"),
rootNodeId: NodeId.make("node-antigravity-prompt-usage"),
providerThread,
message: {
createdBy: "user",
creationSource: "web",
messageId: MessageId.make("message-antigravity-prompt-usage"),
text: "say hi",
attachments: [],
},
modelSelection,
runtimePolicy,
})
.pipe(Effect.forkScoped);
const event = yield* Fiber.join(completed);
assert.deepEqual(
event._tag === "Some" && event.value.type === "provider_turn.updated"
? event.value.providerTurn.turnTokenUsage
: undefined,
{
usageScope: "main_agent",
usageStatus: "complete",
hasSubagents: false,
inputTokens: 5900,
outputTokens: 23,
cachedInputTokens: 5000,
cacheCreationTokens: 800,
reasoningTokens: 19,
},
);
}).pipe(Effect.provide(layerSession)),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
extractAntigravityUserInputQuestion,
makeAntigravityReadRepair,
makeAntigravityUserInputResponse,
normalizeAntigravityPromptUsage,
normalizeAntigravityToolCall,
} from "../../provider/acp/AntigravityProtocol.ts";
import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuthSupport.ts";
Expand Down Expand Up @@ -191,7 +192,14 @@ 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)),
Effect.map((response) =>
response.usage == null
? response
: { ...response, usage: normalizeAntigravityPromptUsage(response.usage) },
),
),
handleSessionUpdate: (handler) => {
projectUpdate = handler;
return runtime.handleSessionUpdate((notification) =>
Expand Down Expand Up @@ -300,7 +308,6 @@ export function makeAntigravityAcpAdapterFlavor(
// Antigravity can leave a prompt open without updates; long tools and approvals pause this.
promptInactivityTimeout: "15 minutes",
reportsPerTurnPromptUsage: true,
geminiPromptUsage: true,
...(profileDirectory === undefined
? {}
: {
Expand Down
47 changes: 47 additions & 0 deletions apps/server/src/provider/acp/AntigravityProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
classifyAntigravitySubagentToolCall,
isAntigravityUserInputRequest,
makeAntigravityUserInputResponse,
normalizeAntigravityPromptUsage,
normalizeAntigravitySessionUpdate,
normalizeAntigravityToolCall,
sanitizeAntigravityToolPayload,
Expand Down Expand Up @@ -733,3 +734,49 @@ describe("Antigravity served reads", () => {
});
});
});

describe("normalizeAntigravityPromptUsage", () => {
it("adds cache reads and writes to the uncached input and leaves other counters alone", () => {
expect(
normalizeAntigravityPromptUsage({
inputTokens: 2181,
outputTokens: 23,
totalTokens: 14323,
cachedReadTokens: 12119,
cachedWriteTokens: 0,
thoughtTokens: 19,
}),
).toEqual({
inputTokens: 14300,
outputTokens: 23,
totalTokens: 14323,
cachedReadTokens: 12119,
cachedWriteTokens: 0,
thoughtTokens: 19,
});
expect(
normalizeAntigravityPromptUsage({
inputTokens: 100,
outputTokens: 10,
totalTokens: 910,
cachedReadTokens: 500,
cachedWriteTokens: 300,
}).inputTokens,
).toBe(900);
});

it("treats absent or null cache counters as zero", () => {
expect(
normalizeAntigravityPromptUsage({ inputTokens: 100, outputTokens: 10, totalTokens: 110 }),
).toEqual({ inputTokens: 100, outputTokens: 10, totalTokens: 110 });
expect(
normalizeAntigravityPromptUsage({
inputTokens: 100,
outputTokens: 10,
totalTokens: 110,
cachedReadTokens: null,
cachedWriteTokens: 40,
}).inputTokens,
).toBe(140);
});
});
10 changes: 10 additions & 0 deletions apps/server/src/provider/acp/AntigravityProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,3 +575,13 @@ export function antigravitySubagentOutput(toolCall: AcpToolCallState): string |
const output = toolCall.data.rawOutput;
return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined;
}

/** Antigravity 1.5+ reports inputTokens without the cached reads and writes. */
export function normalizeAntigravityPromptUsage(
usage: EffectAcpSchema.Usage,
): EffectAcpSchema.Usage {
return {
...usage,
inputTokens: usage.inputTokens + (usage.cachedReadTokens ?? 0) + (usage.cachedWriteTokens ?? 0),
};
}
9 changes: 1 addition & 8 deletions packages/provider-acp/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,15 +367,11 @@ export function acpPerTurnPromptUsage(
usage: EffectAcpSchema.Usage | null | undefined,
hasSubagents: boolean,
terminalStatus: OrchestrationV2ProviderTurn["status"],
geminiUsage = false,
): TurnTokenUsage {
if (usage == null) {
return { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents };
}
const inputTokens = geminiUsage
? usage.inputTokens + (usage.cachedReadTokens ?? 0)
: usage.inputTokens;
const outputTokens = usage.outputTokens;
const { inputTokens, outputTokens } = usage;
// TurnTokenUsage contract: input includes cache read + write and reasoning
// is a subset of output, so clamp counters that exceed their parent and
// drop the ones the agent left unset. Cache writes are capped at whatever
Expand Down Expand Up @@ -710,8 +706,6 @@ export interface AcpAdapterV2Flavor {
* leaves usage semantics open, so this stays unset until proven live.
*/
readonly reportsPerTurnPromptUsage?: boolean;
/** Antigravity 1.5+ usage: inputTokens leaves out cachedReadTokens, while outputTokens already includes thoughtTokens. */
readonly geminiPromptUsage?: boolean;
/**
* Fails a dispatched prompt after this long with no update for its session while no
* agent request, tool or subagent is open, and replaces the agent before the next turn.
Expand Down Expand Up @@ -8542,7 +8536,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
context.promptUsage,
context.subagents.size > 0,
status,
flavor.geminiPromptUsage,
),
}),
});
Expand Down
Loading