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
496 changes: 496 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts

Large diffs are not rendered by default.

188 changes: 188 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6345,3 +6345,191 @@ describe("AntigravityAdapterV2 command exits", () => {
}).pipe(Effect.provide(layerSession)),
);
});

describe("AntigravityAdapterV2 silent ADC drop recovery", () => {
it.effect("fails a silent USER_INPUT-only turn and restarts the runtime on the next send", () =>
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),
);
const profileDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-antigravity-adc-drop-",
});
const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");
yield* fileSystem.makeDirectory(conversations, { recursive: true });
const appendStep = (type: number, status: number, payload: string) => {
const database = new NodeSqlite.DatabaseSync(path.join(conversations, "mock-session-1.db"));
try {
database.exec(
"CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, step_payload BLOB)",
);
database
.prepare("INSERT INTO steps (step_type, status, step_payload) VALUES (?, ?, ?)")
.run(type, status, Buffer.from(payload));
} finally {
database.close();
}
};
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
let runtimeOrdinal = 0;
const promptRuntimes: Array<number> = [];
const resumeIds: Array<string | undefined> = [];
const instanceId = ProviderInstanceId.make("antigravity-adc-drop-test");
const threadId = ThreadId.make("thread-antigravity-adc-drop");
const adapter = yield* makeAntigravityAdapterV2({
instanceId,
selfInvocation: yield* resolveSelfInvocation(),
profileDirectory,
maxRuntimeAgeBeforeTurn: "45 minutes",
makeRuntime: (input) => {
const currentRuntime = ++runtimeOrdinal;
resumeIds.push(input.resumeSessionId);
let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
return 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* () {
promptRuntimes.push(currentRuntime);
appendStep(14, 3, `Prompt on runtime ${currentRuntime}`);
// Simulate agy's 60m ADC OAuth failure on runtime 1: only USER_INPUT is
// recorded and session/prompt resolves cleanly with no output or usage.
if (currentRuntime === 1) {
return { stopReason: "end_turn" as const };
}
yield* sessionUpdate!(
normalizeAntigravitySessionUpdate({
sessionId: "mock-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: `Reply from runtime ${currentRuntime}` },
},
}),
);
appendStep(15, 3, `Reply from runtime ${currentRuntime}`);
return {
stopReason: "end_turn" as const,
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
};
}),
})),
);
},
withProcess: (_stop, task) => task,
defaultModel: Effect.undefined,
});
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-adc-drop"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* session.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const runTurn = (ordinal: number) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
yield* session.startTurn({
appThread: {
createdBy: "user",
creationSource: "web",
id: threadId,
projectId: ProjectId.make("project-antigravity-adc-drop"),
title: "Antigravity ADC drop",
providerInstanceId: instanceId,
modelSelection,
runtimeMode: runtimePolicy.runtimeMode,
interactionMode: runtimePolicy.interactionMode,
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-adc-drop-${ordinal}`),
runOrdinal: ordinal,
providerTurnOrdinal: ordinal,
attemptId: RunAttemptId.make(`attempt-antigravity-adc-drop-${ordinal}`),
rootNodeId: NodeId.make(`node-antigravity-adc-drop-${ordinal}`),
providerThread,
message: {
createdBy: "user",
creationSource: "web",
messageId: MessageId.make(`msg-antigravity-adc-drop-${ordinal}`),
text: `Hello ${ordinal}`,
attachments: [],
},
modelSelection,
runtimePolicy,
});
const events = Array.from(
yield* session.events.pipe(
Stream.takeUntil((event) => event.type === "turn.terminal"),
Stream.runCollect,
),
);
return events.at(-1);
});

// Turn 1 hits the silent drop on runtime 1 and fails with a retryable provider error.
const firstTerminal = yield* runTurn(1);
assert.equal(firstTerminal?.type, "turn.terminal");
assert.equal(firstTerminal?.type === "turn.terminal" ? firstTerminal.status : null, "failed");
assert.equal(
firstTerminal?.type === "turn.terminal" && firstTerminal.status === "failed"
? firstTerminal.failure.retryable
: null,
true,
);

// Turn 2 automatically restarts onto runtime 2 (resuming mock-session-1) and succeeds.
const secondTerminal = yield* runTurn(2);
assert.equal(
secondTerminal?.type === "turn.terminal" ? secondTerminal.status : null,
"completed",
);

assert.deepEqual(promptRuntimes, [1, 2]);
assert.deepEqual(resumeIds, [undefined, "mock-session-1"]);
}).pipe(Effect.provide(layerSession)),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { SelfInvocation } from "@t3tools/shared/nodeRuntime";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import type * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
Expand Down Expand Up @@ -118,6 +119,8 @@ export interface AntigravityAdapterV2Options {
readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
/** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */
readonly profileDirectory?: string;
/** Recycles long-lived ACP runtimes before a new turn (used for ADC's 60m token cliff). */
readonly maxRuntimeAgeBeforeTurn?: Duration.Input;
}

/**
Expand Down Expand Up @@ -358,6 +361,9 @@ export function makeAntigravityAcpAdapterFlavor(
checksVersionAtHandshake: true,
// Antigravity can leave a prompt open without updates; long tools and approvals pause this.
promptInactivityTimeout: "15 minutes",
...(options.maxRuntimeAgeBeforeTurn === undefined
? {}
: { maxRuntimeAgeBeforeTurn: options.maxRuntimeAgeBeforeTurn }),
reportsPerTurnPromptUsage: true,
geminiPromptUsage: true,
...(profileDirectory === undefined
Expand Down
14 changes: 13 additions & 1 deletion apps/server/src/provider/Drivers/AntigravityDriver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"
import { knownProviderFailureMessage } from "@t3tools/provider-core/server/failure";
import { resolveProviderCompatibility } from "../providerCompatibility.ts";
import { writeProviderStatusCache } from "../providerStatusCache.ts";
import { AntigravityDriver } from "./AntigravityDriver.ts";
import { AntigravityDriver, antigravityMaxRuntimeAgeBeforeTurn } from "./AntigravityDriver.ts";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as ProviderHostLive from "../ProviderHostLive.ts";
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
Expand Down Expand Up @@ -1129,4 +1129,16 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
yield* h.assertClosed;
}),
);

it("enables 45-minute runtime recycling only for Agent Platform ADC auth", () => {
expect(antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "" })).toBe(
"45 minutes",
);
expect(
antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "AIza-test" }),
).toBeUndefined();
expect(
antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-personal", apiKey: "" }),
).toBeUndefined();
});
});
13 changes: 13 additions & 0 deletions apps/server/src/provider/Drivers/AntigravityDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ import { readProviderStatusCache, resolveProviderStatusCachePath } from "../prov
import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";

const DRIVER = ProviderDriverKind.make("antigravity");
// agy acp in Agent Platform ADC mode fails OAuth refresh with context canceled at 60 minutes;
// recycling between turns at 45 minutes keeps sessions on a fresh token without hitting the cliff.
const ANTIGRAVITY_ADC_MAX_RUNTIME_AGE = "45 minutes" as const;

export function antigravityMaxRuntimeAgeBeforeTurn(
auth: Pick<AntigravityAuthConfig, "authMethod" | "apiKey">,
): typeof ANTIGRAVITY_ADC_MAX_RUNTIME_AGE | undefined {
return auth.authMethod === "agent-platform" && !auth.apiKey.trim()
? ANTIGRAVITY_ADC_MAX_RUNTIME_AGE
: undefined;
}
const decodeSettings = Schema.decodeSync(AntigravitySettings);
const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
Expand Down Expand Up @@ -820,6 +831,7 @@ export const AntigravityDriver: ProviderDriver<
),
);
const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
const maxRuntimeAgeBeforeTurn = antigravityMaxRuntimeAgeBeforeTurn(auth);
const orchestrationAdapter = yield* makeAntigravityAdapterV2({
instanceId,
selfInvocation,
Expand All @@ -832,6 +844,7 @@ export const AntigravityDriver: ProviderDriver<
),
),
profileDirectory,
...(maxRuntimeAgeBeforeTurn === undefined ? {} : { maxRuntimeAgeBeforeTurn }),
onSessionStarted: (started, cwd, session) =>
provider
.onSessionStarted(started, cwd, session)
Expand Down
49 changes: 48 additions & 1 deletion apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ describe("watchAntigravityPromptOutcome", () => {
const turn = (
steps: ReadonlyArray<readonly [number, Uint8Array]>,
result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" },
options?: { readonly retired?: boolean },
options?: { readonly retired?: boolean; readonly receivedOutput?: boolean },
) =>
Effect.gen(function* () {
const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId);
Expand Down Expand Up @@ -451,6 +451,53 @@ describe("watchAntigravityPromptOutcome", () => {
retryable: true,
}),
);
// After 60 minutes in Agent Platform ADC mode, agy's OAuth refresh fails with
// context canceled and resolves session/prompt with only USER_INPUT and no output.
assert.deepEqual(
yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: false }),
reusable({
class: "provider_error",
message:
"Antigravity ended the turn without contacting the model. T3 Code will restart the agent; send your message again to continue.",
code: null,
retryable: true,
}),
);
// Local replies, reported usage, inactivity-retired prompts, and steers after a
// model reply must not trip the silent-drop check.
assert.isUndefined(
yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: true }),
);
assert.isUndefined(
yield* turn(
[[USER_INPUT, input]],
{
stopReason: "end_turn",
usage: { inputTokens: 10, outputTokens: 2, totalTokens: 12 },
},
{ receivedOutput: false },
),
);
assert.isUndefined(
yield* turn(
[[USER_INPUT, input]],
{ stopReason: "end_turn" },
{ retired: true, receivedOutput: false },
),
);
assert.isUndefined(
yield* steered(
[
[USER_INPUT, input],
[PLANNER_RESPONSE, reply],
],
[[USER_INPUT, input]],
),
);
assert.equal(
(yield* steered([[USER_INPUT, input]], [[USER_INPUT, input]]))?.failure.retryable,
true,
);
}).pipe(Effect.provide(NodeServices.layer)),
);

Expand Down
Loading
Loading