diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 249d27951..d4eca925b 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -715,7 +715,12 @@ const program = Effect.gen(function* () { usage: { inputTokens: 400, outputTokens: 10, totalTokens: 410 }, }; } - if (scenario === "background" || scenario === "hang" || scenario === "exit") { + if ( + scenario === "background" || + scenario === "background-log-error" || + scenario === "hang" || + scenario === "exit" + ) { yield* update(sessionId, { sessionUpdate: "tool_call", ...command, status: "in_progress" }); yield* say(sessionId, "I'll report once the build finishes."); yield* modelCallEnds(sessionId); @@ -725,7 +730,7 @@ const program = Effect.gen(function* () { yield* Effect.sync((): void => process.exit(1)); }).pipe(Effect.forkDetach); } - if (scenario === "background") { + if (scenario === "background" || scenario === "background-log-error") { yield* Effect.gen(function* () { yield* Effect.sleep("400 millis"); yield* update(sessionId, { @@ -735,7 +740,15 @@ const program = Effect.gen(function* () { rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, }); yield* Effect.sleep("100 millis"); - yield* say(sessionId, "The build passed."); + if (scenario === "background-log-error") { + appendLogSteps(sessionId, [ + [15, "I'll report once the build finishes."], + [17, GATEWAY_ERROR], + ]); + yield* say(sessionId, "API error: the request failed."); + } else { + yield* say(sessionId, "The build passed."); + } yield* modelCallEnds(sessionId); }).pipe(Effect.forkDetach); } @@ -750,6 +763,50 @@ const program = Effect.gen(function* () { }, }; } + if (scenario === "ask-question") { + const answer = yield* agent.client.extRequest("elicitation/create", { + sessionId, + mode: "form", + message: "The agent has 2 questions.", + requestedSchema: { + type: "object", + properties: { + q1: { + type: "string", + title: "Which runtime should we target?", + oneOf: [ + { const: "1", title: "Node.js", description: "Default runtime" }, + { const: "2", title: "Deno" }, + ], + }, + q1_other: { + type: "string", + title: "Other", + description: "Optional free-form answer", + }, + q2: { + type: "array", + title: "Which checks should run?", + items: { + anyOf: [ + { const: "1", title: "Typecheck" }, + { const: "2", title: "Unit tests" }, + { const: "3", title: "Lint" }, + ], + }, + }, + q2_other: { + type: "string", + title: "Other", + description: "Optional free-form answer", + }, + }, + }, + }); + yield* say(sessionId, `Answers: ${JSON.stringify(answer)}`); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } if (scenario === "subagent") { yield* update(sessionId, { sessionUpdate: "tool_call", diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index e8ae829f5..c4002a658 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -146,6 +146,7 @@ export const AntigravityDriver: ProviderDriver; + readonly elicitation?: McpElicitation; } interface AcpSessionContext { @@ -433,6 +436,15 @@ interface AcpMachineSession { } >; readonly prompts: Map; + /** Outcome watch kept past prompt deletion so a held turn can re-check after a wake-up reply. */ + readonly watches: Map< + number, + { + readonly watch: AcpPromptOutcomeWatch | undefined; + readonly stopReason: EffectAcpSchema.StopReason; + readonly fallback: AcpTurnCompletedPayload; + } + >; readonly turns: Map< string, { @@ -1871,7 +1883,12 @@ export function makeAcpAdapter( // A side runtime never reaches the user: its questions go unanswered // at once (no answers reads as declined), and nothing is shown. - const requestUserInput: AcpExtensionContext["requestUserInput"] = (request) => + const requestUserInput = (request: { + readonly method: string; + readonly payload: unknown; + readonly questions: Parameters[0]["questions"]; + readonly elicitation?: McpElicitation; + }): Effect.Effect => Effect.gen(function* () { if (lockdown !== undefined) { yield* logNative(input.threadId, `${request.method} (declined: side answer)`, {}); @@ -1880,7 +1897,10 @@ export function makeAcpAdapter( const requestId = ApprovalRequestId.make(crypto.randomUUID()); const runtimeRequestId = RuntimeRequestId.make(requestId); const answers = yield* Deferred.make(); - pendingUserInputs.set(requestId, { answers }); + pendingUserInputs.set(requestId, { + answers, + ...(request.elicitation ? { elicitation: request.elicitation } : {}), + }); const shown = yield* showRequest((turnId) => Effect.gen(function* () { yield* offerRuntimeEvent({ @@ -1890,7 +1910,10 @@ export function makeAcpAdapter( threadId: input.threadId, turnId, requestId: runtimeRequestId, - payload: { questions: request.questions }, + payload: { + questions: request.questions, + ...(request.elicitation ? { elicitation: request.elicitation } : {}), + }, ...(extensionSource ? { raw: { @@ -2027,7 +2050,111 @@ export function makeAcpAdapter( }), }; + const ElicitationCreatePayload = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.String), + mode: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + message: Schema.String, + requestedSchema: Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + type: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + properties: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + required: Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]), + ), + }), + Schema.Null, + ]), + ), + }); + + const handleFormElicitation = ( + method: string, + params: { + readonly sessionId?: string; + readonly mode?: string | null; + readonly message: string; + readonly requestedSchema?: { + readonly type?: string | null; + readonly title?: string | null; + readonly description?: string | null; + readonly properties?: Readonly> | null; + readonly required?: ReadonlyArray | null; + } | null; + }, + ): Effect.Effect< + | { + readonly action: "accept"; + readonly content: Readonly< + Record> + >; + } + | { readonly action: "decline" | "cancel" } + > => + Effect.gen(function* () { + yield* logNative(input.threadId, method, params); + if ( + side !== undefined || + (params.mode !== undefined && params.mode !== null && params.mode !== "form") + ) { + return { action: "decline" as const }; + } + const classified = descriptor.classifyElicitationForm?.(params); + if (classified) { + const answers = yield* requestUserInput({ + method, + payload: params, + questions: classified.questions, + }); + return classified.responseForAnswers(answers); + } + const elicitation = mcpElicitationPrompt({ + serverName: descriptor.presentation.displayName, + message: params.message, + mode: "form", + requestedSchema: params.requestedSchema, + }); + if (!elicitation) { + return { action: "decline" as const }; + } + const answers = yield* requestUserInput({ + method, + payload: params, + questions: [], + elicitation, + }); + const response = yield* Effect.try(() => + mcpElicitationResponse(elicitation, answers), + ).pipe(Effect.orElseSucceed(() => ({ action: "cancel" as const, content: null }))); + if (response.action !== "accept") { + return { action: response.action }; + } + const content = + typeof response.content === "object" && + response.content !== null && + !Array.isArray(response.content) + ? (response.content as Readonly< + Record> + >) + : {}; + return { action: "accept" as const, content }; + }); + const started = yield* Effect.gen(function* () { + yield* acp.handleExtRequest("elicitation/create", ElicitationCreatePayload, (params) => + handleFormElicitation("elicitation/create", params), + ); + yield* acp.handleElicitation((params) => + params.mode === "form" + ? handleFormElicitation("session/elicitation", params).pipe( + Effect.map((action) => ({ action })), + ) + : Effect.succeed({ action: { action: "decline" as const } }), + ); if (descriptor.extensions) { yield* descriptor.extensions.register(extensionContext); } @@ -2253,11 +2380,12 @@ export function makeAcpAdapter( : { text: undefined, hash: projectBriefHash }; const now = yield* nowIso; // ACP passes an HTTP server only to an agent that says it speaks - // HTTP MCP (see supportedMcpServers); without that, it has no room - // tools, and says so. + // HTTP MCP (see supportedMcpServers) or declares `assumeHttpMcp`; + // without that, it has no room tools, and says so. const roomToolsAttached = credential !== undefined && - started.initializeResult.agentCapabilities?.mcpCapabilities?.http === true; + (descriptor.assumeHttpMcp === true || + started.initializeResult.agentCapabilities?.mcpCapabilities?.http === true); const session: ProviderSession = { provider: PROVIDER, providerInstanceId: boundInstanceId, @@ -2352,6 +2480,7 @@ export function makeAcpAdapter( state: initialTurnMachineState(), callers: new Map(), prompts: new Map(), + watches: new Map(), turns: new Map(), timers: new Map(), lastActivityMs: yield* Clock.currentTimeMillis, @@ -3204,13 +3333,68 @@ export function makeAcpAdapter( } case "readOutcome": { const sent = machine.prompts.get(command.prompt); - if (sent === undefined) return; const seen = { turnText: ctx.activeTurnText, providerStatus: ctx.lastProviderStatus }; + if (sent !== undefined) { + const retainedWatch = sent.watch; + const retainedStopReason = + sent.exit !== undefined && Exit.isSuccess(sent.exit) + ? sent.exit.value.stopReason + : undefined; + yield* seam({ point: "outcomeRead", prompt: command.prompt }).pipe( + Effect.andThen(readMachineOutcome(ctx, sent, seen)), + Effect.flatMap((outcome) => { + if (retainedStopReason !== undefined && outcome.state === "completed") { + machine.watches.set(command.prompt, { + watch: retainedWatch, + stopReason: retainedStopReason, + fallback: outcome.answer, + }); + } + return postTurnEvent(ctx, { + type: "outcomeRead", + prompt: command.prompt, + outcome, + }); + }), + Effect.forkIn(ctx.scope), + ); + return; + } + // Post-settle re-check: the prompt's payload is already freed, so + // re-run its watch against the session log for any error written + // during a wake-up reply. + const retained = machine.watches.get(command.prompt); + machine.watches.delete(command.prompt); yield* seam({ point: "outcomeRead", prompt: command.prompt }).pipe( - Effect.andThen(readMachineOutcome(ctx, sent, seen)), - Effect.flatMap((outcome) => - postTurnEvent(ctx, { type: "outcomeRead", prompt: command.prompt, outcome }), + Effect.andThen( + retained?.watch === undefined + ? Effect.succeed(undefined) + : retained.watch.check({ response: { stopReason: retained.stopReason } }).pipe( + Effect.timeoutOption(ACP_OUTCOME_CHECK_TIMEOUT), + Effect.map(Option.getOrUndefined), + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.recheck-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ), ), + Effect.flatMap((hidden) => { + const outcome: AcpPromptOutcomeRead = + hidden !== undefined + ? { + state: "failed", + answer: failedTurnPayload(hidden, retained?.stopReason ?? null), + sessionLost: hidden.sessionLost === true, + } + : { + state: "completed", + answer: retained?.fallback ?? { state: "completed", stopReason: null }, + sessionLost: false, + }; + return postTurnEvent(ctx, { type: "outcomeRead", prompt: command.prompt, outcome }); + }), Effect.forkIn(ctx.scope), ); return; @@ -3376,6 +3560,7 @@ export function makeAcpAdapter( const id = TurnId.make(turnId); const data = machine.turns.get(turnId); machine.turns.delete(turnId); + machine.watches.clear(); const closedItem = yield* ctx.acp.closeAssistantSegmentNow; if (closedItem !== undefined) { yield* offerRuntimeEvent( @@ -4016,6 +4201,19 @@ export function makeAcpAdapter( detail: `Unknown pending user-input request: ${requestId}`, }); } + if (pending.elicitation !== undefined) { + const elicitation = pending.elicitation; + yield* Effect.try({ + try: () => mcpElicitationResponse(elicitation, answers), + catch: (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "elicitation/create", + detail: cause instanceof Error ? cause.message : String(cause), + cause, + }), + }); + } yield* Deferred.succeed(pending.answers, answers); }); diff --git a/apps/server/src/provider/acp/AcpProvider.ts b/apps/server/src/provider/acp/AcpProvider.ts index cf1c5e7b1..3cf67e7c3 100644 --- a/apps/server/src/provider/acp/AcpProvider.ts +++ b/apps/server/src/provider/acp/AcpProvider.ts @@ -262,10 +262,14 @@ export function buildInitialAcpProviderSnapshot( descriptor: AcpProviderDescriptor, settings: Settings, - useRuntime: (acp: AcpSessionRuntimeShape) => Effect.Effect, + useRuntime: ( + acp: AcpSessionRuntimeShape, + noteSessionId: (sessionId: string) => void, + ) => Effect.Effect, environment: NodeJS.ProcessEnv, -) => - Effect.gen(function* () { +) => { + let openedSessionId: string | undefined; + return Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const runtime = yield* makeAcpProviderRuntime(descriptor, { settings, @@ -274,8 +278,20 @@ const withAcpProbeRuntime = ( cwd: process.cwd(), clientInfo: { ...THREADLINES_ACP_CLIENT_INFO, name: "threadlines-provider-probe" }, }); - return yield* useRuntime(runtime); - }).pipe(Effect.scoped); + return yield* useRuntime(runtime, (sessionId) => { + openedSessionId = sessionId; + }); + }).pipe( + Effect.scoped, + Effect.ensuring( + Effect.suspend(() => + openedSessionId !== undefined && descriptor.onEphemeralSessionClosed + ? descriptor.onEphemeralSessionClosed(openedSessionId).pipe(Effect.ignore) + : Effect.void, + ), + ), + ); +}; /** * Starts a probe session and applies the updates the mapping makes with no @@ -285,11 +301,13 @@ const withAcpProbeRuntime = ( const startProbeSession = ( descriptor: AcpProviderDescriptor, acp: AcpSessionRuntimeShape, + noteSessionId?: (sessionId: string) => void, ) => Effect.gen(function* () { - yield* acp + const started = yield* acp .start() .pipe(Effect.timeout(descriptor.modelDiscoveryTimeoutMs ?? ACP_MODEL_DISCOVERY_TIMEOUT_MS)); + noteSessionId?.(started.sessionId); // The runtime's view, not the raw response: for native controls it also // holds the stand-ins for the older `modes` / `models` fields. let configOptions = yield* acp.getConfigOptions; @@ -309,24 +327,48 @@ export const discoverAcpModels = ( withAcpProbeRuntime( descriptor, settings, - (acp) => - startProbeSession(descriptor, acp).pipe( + (acp, noteSessionId) => + Effect.gen(function* () { + const configOptions = yield* startProbeSession(descriptor, acp, noteSessionId); + // An agent that probes every model's options in this single session + // (Antigravity) lists them here rather than spawning a second process. + if (descriptor.discoverModelOptions) { + const listed = yield* descriptor.discoverModelOptions(acp).pipe( + Effect.timeout(descriptor.modelDiscoveryTimeoutMs ?? ACP_MODEL_DISCOVERY_TIMEOUT_MS), + Effect.catchCause((cause) => + Effect.logWarning("ACP model option listing failed", { + provider: descriptor.driverKind, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + if (listed && listed.length > 0) { + const mapping = mappingFor(descriptor); + const choices = flattenSessionConfigSelectOptions(findModelConfigOption(configOptions)); + const bySlug = new Map(listed.map((entry) => [entry.slug, entry.configOptions])); + return buildAcpDiscoveredModels( + choices.map((choice) => ({ + slug: choice.value, + name: choice.name, + capabilities: bySlug.has(choice.value) + ? mapping.capabilitiesFromConfigOptions(bySlug.get(choice.value)!) + : EMPTY_ACP_MODEL_CAPABILITIES, + })), + ); + } + } // Agents that cache their catalog (to skip discovery next time) see // this session's options like any other's. - Effect.tap((configOptions) => - descriptor.onSessionConfigOptions - ? descriptor.onSessionConfigOptions(settings, configOptions).pipe(Effect.ignore) - : Effect.void, - ), - Effect.map((configOptions) => - buildAcpModelsFromConfigOptions({ - configOptions, - mapping: mappingFor(descriptor), - sharedCapabilities: descriptor.modelCapabilitiesVaryByModel !== true, - defaultModelWhenNone: descriptor.sessionControls === "native", - }), - ), - ), + if (descriptor.onSessionConfigOptions) { + yield* descriptor.onSessionConfigOptions(settings, configOptions).pipe(Effect.ignore); + } + return buildAcpModelsFromConfigOptions({ + configOptions, + mapping: mappingFor(descriptor), + sharedCapabilities: descriptor.modelCapabilitiesVaryByModel !== true, + defaultModelWhenNone: descriptor.sessionControls === "native", + }); + }), environment, ); @@ -348,9 +390,9 @@ export const discoverAcpModelCapabilities = + (acp, noteSessionId) => Effect.gen(function* () { - const initialConfigOptions = yield* startProbeSession(descriptor, acp); + const initialConfigOptions = yield* startProbeSession(descriptor, acp, noteSessionId); const modelOption = findModelConfigOption(initialConfigOptions); const modelChoices = flattenSessionConfigSelectOptions(modelOption); if (!modelOption || modelChoices.length === 0) { @@ -418,9 +460,17 @@ export const discoverAcpModelCapabilities = pendingSlugs.filter((_, index) => index % laneCount === lane), ); - const probeLane = (probeAcp: AcpSessionRuntimeShape, laneSlugs: ReadonlyArray) => + const probeLane = ( + probeAcp: AcpSessionRuntimeShape, + laneSlugs: ReadonlyArray, + laneNoteSessionId?: (sessionId: string) => void, + ) => Effect.gen(function* () { - const probeConfigOptions = yield* startProbeSession(descriptor, probeAcp); + const probeConfigOptions = yield* startProbeSession( + descriptor, + probeAcp, + laneNoteSessionId, + ); const probeModelOptionId = findModelConfigOption(probeConfigOptions)?.id ?? modelOption.id; const results: Array = []; @@ -463,7 +513,8 @@ export const discoverAcpModelCapabilities = probeLane(probeAcp, laneSlugs), + (probeAcp, laneNoteSessionId) => + probeLane(probeAcp, laneSlugs, laneNoteSessionId), environment, ), { concurrency: "unbounded" }, diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index c12546f27..a4a731aab 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -84,6 +84,36 @@ export interface AcpPermissionQuestion { readonly optionIdForAnswers: (answers: ProviderUserInputAnswers) => string | undefined; } +/** An ACP form elicitation request (`elicitation/create` or `session/elicitation`). */ +export interface AcpElicitationFormRequest { + readonly sessionId?: string; + readonly mode?: string | null; + readonly message: string; + readonly requestedSchema?: { + readonly type?: string | null; + readonly title?: string | null; + readonly description?: string | null; + readonly properties?: Readonly> | null; + readonly required?: ReadonlyArray | null; + } | null; +} + +export type AcpElicitationFormResponse = + | { + readonly action: "accept"; + readonly content: Readonly>>; + } + | { readonly action: "decline" | "cancel" }; + +/** + * An ACP form elicitation recognized as questions for the user (Antigravity's + * `ask_question`, pairing `qN` choices with `qN_other` free-text fields). + */ +export interface AcpElicitationQuestions { + readonly questions: ReadonlyArray; + readonly responseForAnswers: (answers: ProviderUserInputAnswers) => AcpElicitationFormResponse; +} + /** * Plan mode for agents that plan through a prompt command and a plan file * rather than an ACP session mode (Antigravity's `/plan`). @@ -650,6 +680,27 @@ export interface AcpProviderDescriptor { readonly classifyPermissionRequest?: ( request: EffectAcpSchema.RequestPermissionRequest, ) => AcpPermissionQuestion | undefined; + /** + * Recognizes an agent's own question form inside an ACP form elicitation + * (Antigravity's `ask_question`) so it renders as a single question card + * instead of a raw form. Anything else falls back to the generic form UI. + */ + readonly classifyElicitationForm?: ( + request: AcpElicitationFormRequest, + ) => AcpElicitationQuestions | undefined; + /** + * The agent accepts `type: "http"` MCP servers in `session/new` / + * `session/resume` / `session/load` even though its `initialize` answer + * omits `agentCapabilities.mcpCapabilities.http` (Antigravity 1.5, + * google-antigravity/antigravity-cli#1604). + */ + readonly assumeHttpMcp?: boolean; + /** + * Called after an ephemeral probe, sign-in verification, or text-generation + * session has closed and its process has exited, so the descriptor can clean + * up throwaway conversation records the agent wrote to its profile. + */ + readonly onEphemeralSessionClosed?: (sessionId: string) => Effect.Effect; /** * A permission option whose "always" outlives the session (Grok's * `always-allow` saves a grant for the whole project). Never offered or @@ -808,6 +859,16 @@ export interface AcpProviderDescriptor { readonly listModelOptions?: ( acp: AcpSessionRuntimeShape, ) => Effect.Effect | undefined, EffectAcpErrors.AcpError>; + /** + * Probes every model's own options inside the single discovery (or sign-in + * verification) session, for an agent that starts slowly and switches models + * in milliseconds (Antigravity's per-model `thought_level`). Unlike + * `listModelOptions`, this runs during initial discovery rather than opening + * a second background probe session. + */ + readonly discoverModelOptions?: ( + acp: AcpSessionRuntimeShape, + ) => Effect.Effect | undefined, EffectAcpErrors.AcpError>; /** * Sessions the background capability probe splits the catalog across * (default 4). Agents that start slowly but switch models in milliseconds diff --git a/apps/server/src/provider/acp/AcpProviderRuntime.ts b/apps/server/src/provider/acp/AcpProviderRuntime.ts index 567edcb27..08c25aee9 100644 --- a/apps/server/src/provider/acp/AcpProviderRuntime.ts +++ b/apps/server/src/provider/acp/AcpProviderRuntime.ts @@ -36,6 +36,7 @@ import { export interface AcpProviderRuntimeInput extends Omit< AcpSessionRuntimeOptions, + | "assumeHttpMcp" | "authMethodId" | "authenticateTimeoutMs" | "cancellationNotice" @@ -120,6 +121,7 @@ export const makeAcpProviderRuntime = ( : acpSignInRequiredMessage(descriptor.presentation.displayName), } : {}), + ...(descriptor.assumeHttpMcp ? { assumeHttpMcp: true } : {}), ...(descriptor.clientCapabilities ? { clientCapabilities: descriptor.clientCapabilities } : {}), diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 08d5b44e3..0865177a2 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -48,15 +48,20 @@ const SESSION_CLOSE_TIMEOUT = Duration.seconds(3); /** Short option lists (effort, mode) are worth spelling out in a rejection. */ const MAX_LISTED_CONFIG_OPTION_VALUES = 8; -/** ACP lets a client pass HTTP/SSE MCP servers only to agents that advertise them. */ +/** + * ACP lets a client pass HTTP/SSE MCP servers only to agents that advertise + * them, unless `assumeHttpMcp` is set for an agent that accepts HTTP servers + * without advertising the capability (Antigravity 1.5). + */ export function supportedMcpServers( servers: ReadonlyArray, capabilities: EffectAcpSchema.McpCapabilities | null | undefined, + assumeHttpMcp = false, ): Array { return servers.filter((server) => "type" in server ? server.type === "http" - ? capabilities?.http === true + ? assumeHttpMcp || capabilities?.http === true : capabilities?.sse === true : true, ); @@ -126,6 +131,8 @@ export interface AcpSessionRuntimeOptions { * speaks that transport, as ACP requires. */ readonly mcpServers?: ReadonlyArray; + /** Pass `type: "http"` MCP servers even when `initialize` omits `mcpCapabilities.http`. */ + readonly assumeHttpMcp?: boolean; /** Each line the agent writes to stderr (see `AcpClientOptions.onStderrLine`). */ readonly onStderrLine?: (line: string) => Effect.Effect; /** @@ -891,6 +898,7 @@ const makeAcpSessionRuntime = ( const mcpServers = supportedMcpServers( options.mcpServers ?? [], initializeResult.agentCapabilities?.mcpCapabilities, + options.assumeHttpMcp === true, ); let sessionId: string; diff --git a/apps/server/src/provider/acp/AcpTextGeneration.ts b/apps/server/src/provider/acp/AcpTextGeneration.ts index fc0b57a86..fce60c5a2 100644 --- a/apps/server/src/provider/acp/AcpTextGeneration.ts +++ b/apps/server/src/provider/acp/AcpTextGeneration.ts @@ -81,8 +81,9 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function prompt: string; outputSchemaJson: S; modelSelection: ModelSelection; - }): Effect.Effect => - Effect.gen(function* () { + }): Effect.Effect => { + let openedSessionId: string | undefined; + return Effect.gen(function* () { const outputRef = yield* Ref.make(""); // Workspace hooks and settings can act before a denied tool call // would stop them; agents that read them run in an empty directory. @@ -114,7 +115,8 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function }); const promptResult = yield* Effect.gen(function* () { - yield* runtime.start(); + const started = yield* runtime.start(); + openedSessionId = started.sessionId; const modeState = yield* runtime.getModeState; yield* Effect.ignore( runtime.setMode( @@ -194,7 +196,15 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function : mapAcpError(operation, `${agentName} ACP text generation failed.`, cause), ), Effect.scoped, + Effect.ensuring( + Effect.suspend(() => + openedSessionId !== undefined && descriptor.onEphemeralSessionClosed + ? descriptor.onEphemeralSessionClosed(openedSessionId).pipe(Effect.ignore) + : Effect.void, + ), + ), ); + }; const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( "AcpTextGeneration.generateCommitMessage", diff --git a/apps/server/src/provider/acp/AcpTurnMachine.test.ts b/apps/server/src/provider/acp/AcpTurnMachine.test.ts index afd06b4fa..1dba77eaa 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.test.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -595,11 +595,20 @@ function checkWorld(world: World, steer: boolean): void { expect(step.state.turn).toBeUndefined(); expect(step.commands.some((command) => command.type === "startTurn")).toBe(false); } - // A hold ends through timers alone once the agent's work is done. + // A hold ends through timers (and its final outcome check, when the agent + // spoke during the hold) once the agent's work is done. if (state.turn?.phase.tag === "waiting" && state.requestsOpen === 0) { const heldId = state.turn.id; let current = state; for (let round = 0; round < 8 && current.turn?.id === heldId; round += 1) { + if (current.turn.phase.tag === "settling" && current.turn.newest !== undefined) { + current = stepTurnMachine(current, { + type: "outcomeRead", + prompt: current.turn.newest, + outcome: outcome("completed"), + }).state; + continue; + } const armed = current.timers.find( ([timer]) => timer !== "cancelDeadline" && timer !== "stopCheck", ); @@ -730,7 +739,13 @@ describe("AcpTurnMachine, the reviewed races", () => { expect(state.subagents).toBe(0); expect(state.wakesOwed).toBe(0); const settled = stepTurnMachine(state, fire(state, "settle")); - expect(ends(settled.commands).map((end) => end.turnId)).toEqual(["u1"]); + expect(settled.commands).toContainEqual({ type: "readOutcome", prompt: 1 }); + const rechecked = stepTurnMachine(settled.state, { + type: "outcomeRead", + prompt: 1, + outcome: outcome("completed"), + }); + expect(ends(rechecked.commands).map((end) => end.turnId)).toEqual(["u1"]); }); /** A turn holding two subagents, its answer read. */ @@ -972,4 +987,33 @@ describe("AcpTurnMachine, the reviewed races", () => { expect(state.turn?.newest).toBe(2); expect(state.turn?.phase.tag).toBe("prompting"); }); + + it("re-checks the outcome before settling when the agent spoke after its prompt answered", () => { + const held = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + { type: "workEnded", id: "c1" }, + { type: "agentOutput", newTurnId: "a1" }, + { type: "replyEnded" }, + ]).state; + const settling = stepTurnMachine(held, fire(held, "settle")); + expect(settling.commands).toContainEqual({ type: "readOutcome", prompt: 1 }); + expect(ends(settling.commands)).toEqual([]); + const failed = stepTurnMachine(settling.state, { + type: "outcomeRead", + prompt: 1, + outcome: outcome("failed", true), + }); + expect(ends(failed.commands)).toEqual([ + { + type: "endTurn", + turnId: "u1", + end: { kind: "answered", outcome: outcome("failed", true) }, + }, + ]); + expect(failed.commands).toContainEqual({ type: "markSessionLost" }); + expect(failed.commands).toContainEqual({ type: "stopSession", reason: "sessionLost" }); + }); }); diff --git a/apps/server/src/provider/acp/AcpTurnMachine.ts b/apps/server/src/provider/acp/AcpTurnMachine.ts index ea145bf98..807835002 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.ts @@ -85,8 +85,8 @@ export interface AcpMachineTurn { readonly newest: number | undefined; readonly phase: | { readonly tag: "prompting" } - | { readonly tag: "settling" } - | { readonly tag: "waiting"; readonly end: AcpTurnEnd }; + | { readonly tag: "settling"; readonly final?: true } + | { readonly tag: "waiting"; readonly end: AcpTurnEnd; readonly recheck?: true }; readonly stopRequested: boolean; } @@ -445,7 +445,12 @@ export function stepTurnMachine( commands.push({ type: "startTurn", turnId: newTurnId }); return; } - if (turn.phase.tag !== "prompting") state.replyOpen = true; + if (turn.phase.tag !== "prompting") { + state.replyOpen = true; + if (turn.phase.tag === "waiting" && turn.phase.recheck !== true) { + state.turn = { ...turn, phase: { ...turn.phase, recheck: true } }; + } + } }; /** @@ -475,12 +480,33 @@ export function stepTurnMachine( commands.push({ type: "readChildren", generation, launches }); }; - /** A held turn whose work is all done and quiet, or that went silent, ends. */ + /** A held turn ends directly (interrupted by a new send). */ const endWaiting = () => { const turn = state.turn; if (turn?.phase.tag === "waiting") endTurn(turn.phase.end); }; + /** + * A held turn whose work is all done and quiet, or that went silent, ends. + * When the agent spoke after its prompt answered, the outcome is checked one + * last time so an upstream error written during a wake-up reply isn't hidden. + */ + const finishWaiting = () => { + const turn = state.turn; + if (turn?.phase.tag !== "waiting") return; + if ( + turn.phase.recheck === true && + turn.newest !== undefined && + turn.phase.end.kind === "answered" && + turn.phase.end.outcome.state === "completed" + ) { + state.turn = { ...turn, phase: { tag: "settling", final: true } }; + commands.push({ type: "readOutcome", prompt: turn.newest }); + return; + } + endTurn(turn.phase.end); + }; + switch (event.type) { case "send": { if (state.ended) { @@ -575,11 +601,11 @@ export function stepTurnMachine( endTurn(end); break; } - if (event.outcome.state === "completed" && workPending(state)) { + if (turn.phase.final !== true && event.outcome.state === "completed" && workPending(state)) { state.turn = { ...turn, phase: { tag: "waiting", end } }; break; } - if (event.outcome.state !== "completed") clearWork(); + if (event.outcome.state !== "completed" || turn.phase.final === true) clearWork(); endTurn(end); break; } @@ -719,11 +745,11 @@ export function stepTurnMachine( else if (state.wakesOwed > 0) state.wakesOwed -= 1; break; case "settle": - if (!workPending(state)) endWaiting(); + if (!workPending(state)) finishWaiting(); break; case "silent": clearWork(); - endWaiting(); + finishWaiting(); break; case "noticeExpiry": state.noticesExpected = 0; diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 81e979654..493bdb497 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -1,16 +1,28 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + import { RUNTIME_MODES } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; import { describe, expect, it } from "vite-plus/test"; import type * as EffectAcpSchema from "effect-acp/schema"; +import { antigravityEnvironment } from "../antigravity/AntigravityProfile.ts"; +import { removeAntigravitySessionFiles } from "../antigravity/AntigravitySessionLog.ts"; +import { supportedMcpServers } from "./AcpSessionRuntime.ts"; import { antigravityAgentMode, antigravityAgentProblem, antigravityModelsFromCatalog, antigravityModelsFromChoices, + extractAntigravityElicitationForm, + isAntigravityCatalogComplete, isAntigravityPlanFileEdit, isLegacyAntigravityServerPath, nextAntigravityCatalog, parseAntigravitySignInUrl, + probeAntigravityModelOptions, resolveAntigravityModelId, } from "./AntigravityAcpSupport.ts"; @@ -225,3 +237,204 @@ describe("isAntigravityPlanFileEdit", () => { expect(isAntigravityPlanFileEdit(edit(`${brain}/s2/plan.md`), brain, "s1")).toBe(false); }); }); + +describe("Antigravity audit improvements", () => { + it("folds Extra High and XHigh effort names", () => { + const models = antigravityModelsFromChoices([ + { value: "gemini-4-pro-xhigh", name: "Gemini 4 Pro (XHigh)" }, + { value: "gemini-4-pro-high", name: "Gemini 4 Pro (High)" }, + { value: "gemini-4-flash-extra", name: "Gemini 4 Flash (Extra High)" }, + { value: "gemini-4-flash-low", name: "Gemini 4 Flash (Low)" }, + ]); + expect(models.map((model) => model.slug)).toEqual(["gemini-4-pro", "gemini-4-flash"]); + const proEffort = models[0]?.capabilities?.optionDescriptors?.[0]; + expect(proEffort?.type === "select" ? proEffort.options.map((o) => o.id) : []).toEqual([ + "high", + "xhigh", + ]); + }); + + it("probes each model's thought_level options in one session and restores the initial model", async () => { + const levelsByModel: Record | undefined> = { + "gemini-4-argon": ["low", "high"], + "claude-sonnet": undefined, + "gpt-6": ["minimal", "medium", "xhigh"], + }; + let current = "gemini-4-argon"; + const switched: Array = []; + const optionsFor = (slug: string): ReadonlyArray => [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: slug, + options: Object.keys(levelsByModel).map((value) => ({ value, name: value })), + }, + ...(levelsByModel[slug] + ? [ + { + id: "thought_level", + name: "Thinking", + category: "thought_level" as const, + type: "select" as const, + currentValue: levelsByModel[slug]![0]!, + options: levelsByModel[slug]!.map((value) => ({ value, name: value })), + }, + ] + : []), + ]; + const probed = await Effect.runPromise( + probeAntigravityModelOptions({ + getConfigOptions: Effect.sync(() => optionsFor(current)), + setConfigOption: (_configId, value) => + Effect.sync(() => { + current = String(value); + switched.push(current); + return { configOptions: [...optionsFor(current)] }; + }), + }), + ); + expect(probed?.thoughtLevels["gemini-4-argon"]?.options.map((o) => o.value)).toEqual([ + "low", + "high", + ]); + expect(probed?.thoughtLevels["claude-sonnet"]).toBeNull(); + expect(probed?.thoughtLevels["gpt-6"]?.options.map((o) => o.value)).toEqual([ + "minimal", + "medium", + "xhigh", + ]); + expect(switched).toEqual(["claude-sonnet", "gpt-6", "gemini-4-argon"]); + expect(current).toBe("gemini-4-argon"); + expect( + isAntigravityCatalogComplete({ + choices: probed!.choices, + thoughtLevels: { "gemini-4-argon": probed!.thoughtLevels["gemini-4-argon"]! }, + }), + ).toBe(false); + expect( + isAntigravityCatalogComplete({ + choices: probed!.choices, + thoughtLevels: probed!.thoughtLevels, + probed: true, + }), + ).toBe(true); + }); + + it("folds ask_question elicitations numerically and rejects non-ask_question forms", () => { + const form = extractAntigravityElicitationForm({ + mode: "form", + message: "The agent has 3 questions.", + requestedSchema: { + type: "object", + properties: { + q10: { + type: "string", + title: "Tenth?", + oneOf: [{ const: "1", title: "Yes" }], + }, + q10_other: { type: "string", title: "Other" }, + q2: { + type: "array", + title: "Pick many", + items: { + anyOf: [ + { const: "a", title: "Alpha" }, + { const: "b", title: "Beta" }, + ], + }, + }, + q2_other: { type: "string", title: "Other" }, + q1: { + type: "string", + title: "First?", + oneOf: [ + { const: "1", title: "One", description: "First choice" }, + { const: "2", title: "Two" }, + ], + }, + q1_other: { type: "string", title: "Other" }, + }, + }, + }); + expect(form?.questions.map((q) => [q.id, q.header, q.multiSelect])).toEqual([ + ["q1", "Question 1", false], + ["q2", "Question 2", true], + ["q10", "Question 3", false], + ]); + expect(form?.responseForAnswers({ q1: "One", q2: ["Alpha", "Beta"], q10: "Maybe" })).toEqual({ + action: "accept", + content: { q1: "1", q2: ["a", "b"], q10_other: "Maybe" }, + }); + expect(form?.responseForAnswers({})).toEqual({ action: "cancel" }); + // Required fields or extra keys fall back to the generic elicitation form. + expect( + extractAntigravityElicitationForm({ + mode: "form", + message: "Login", + requestedSchema: { + type: "object", + required: ["q1"], + properties: { + q1: { type: "string", title: "First?", oneOf: [{ const: "1", title: "One" }] }, + q1_other: { type: "string", title: "Other" }, + }, + }, + }), + ).toBeUndefined(); + }); + + it("keeps HTTP MCP servers when assumeHttpMcp is set", () => { + const servers = [ + { type: "http" as const, name: "room", url: "http://127.0.0.1:9999/mcp", headers: [] }, + ]; + expect(supportedMcpServers(servers, undefined, false)).toEqual([]); + expect(supportedMcpServers(servers, undefined, true)).toEqual(servers); + }); + + it("hardens Antigravity child env and sets Linux SSL_CERT_FILE when unset", () => { + const env = antigravityEnvironment({ + base: { + PATH: "/usr/bin", + ELECTRON_RUN_AS_NODE: "1", + CHROME_CRASHPAD_PIPE_NAME: "/tmp/pipe", + NIX_SSL_CERT_FILE: "/nix/ca-bundle.crt", + }, + profileDir: "/tmp/profile", + tempDir: "/tmp/run", + platform: "linux", + pathExists: (candidate) => candidate === "/nix/ca-bundle.crt", + }); + expect(env.ELECTRON_RUN_AS_NODE).toBeUndefined(); + expect(env.CHROME_CRASHPAD_PIPE_NAME).toBeUndefined(); + expect(env.PAGER).toBe("cat"); + expect(env.GH_PAGER).toBe("cat"); + expect(env.GIT_PAGER).toBe("cat"); + expect(env.GIT_TERMINAL_PROMPT).toBe("0"); + expect(env.SSL_CERT_FILE).toBe("/nix/ca-bundle.crt"); + }); + + it("removes ephemeral session artifacts inside the profile without following symlinks", async () => { + const dir = await NodeFS.mkdtemp(path.join(os.tmpdir(), "agy-cleanup-")); + try { + const appDir = path.join(dir, "antigravity-acp"); + await NodeFS.mkdir(path.join(appDir, "conversations"), { recursive: true }); + await NodeFS.mkdir(path.join(appDir, "brain", "ephemeral-1"), { recursive: true }); + await NodeFS.mkdir(path.join(appDir, "annotations"), { recursive: true }); + await NodeFS.writeFile(path.join(appDir, "conversations", "ephemeral-1.db"), "db"); + await NodeFS.writeFile(path.join(appDir, "conversations", "ephemeral-1.db-wal"), "wal"); + await NodeFS.writeFile(path.join(appDir, "conversations", "keep.db"), "keep"); + await NodeFS.writeFile(path.join(appDir, "brain", "ephemeral-1", "plan.md"), "plan"); + await NodeFS.writeFile(path.join(appDir, "annotations", "ephemeral-1.pbtxt"), "note"); + + await Effect.runPromise(removeAntigravitySessionFiles(dir, "ephemeral-1")); + + expect(await NodeFS.readdir(path.join(appDir, "conversations"))).toEqual(["keep.db"]); + expect(await NodeFS.readdir(path.join(appDir, "brain"))).toEqual([]); + expect(await NodeFS.readdir(path.join(appDir, "annotations"))).toEqual([]); + } finally { + await NodeFS.rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7b3e319fd..2b4929976 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -43,8 +43,10 @@ import { ProviderDriverKind, type ProviderInteractionMode, type ProviderOptionSelection, + type ProviderUserInputAnswers, type RuntimeMode, type ServerProviderModel, + type UserInputQuestion, } from "@threadlines/contracts"; import { createModelCapabilities, @@ -64,6 +66,7 @@ import { } from "../antigravity/AntigravityRelease.ts"; import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; import { antigravityAttachmentDelivery } from "../antigravity/AntigravityAttachments.ts"; +import { removeAntigravitySessionFiles } from "../antigravity/AntigravitySessionLog.ts"; import { antigravitySubagents } from "../antigravity/AntigravitySubagents.ts"; import { normalizeAntigravitySessionUpdate, @@ -110,12 +113,20 @@ import type { ProviderMaintenanceCommandAction, } from "../providerMaintenance.ts"; import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; -import type { AcpProviderDescriptor, AcpProviderProbeOutcome } from "./AcpProviderDescriptor.ts"; +import type { + AcpElicitationFormRequest, + AcpElicitationFormResponse, + AcpElicitationQuestions, + AcpModelOptions, + AcpProviderDescriptor, + AcpProviderProbeOutcome, +} from "./AcpProviderDescriptor.ts"; import { flattenSessionConfigSelectOptions, selectConfigOptionCurrentValue, } from "./AcpProviderModels.ts"; import { type AcpToolCallState, findModelConfigOption } from "./AcpRuntimeModel.ts"; +import type { AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; import { ProviderSetupError } from "../Errors.ts"; const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings); @@ -245,9 +256,10 @@ export function parseAntigravitySignInUrl(line: string): string | undefined { // ── Models: one family per model, effort as an option ──────────────── -const EFFORT_NAME = /^(.*\S)\s*\((High|Medium|Low|Minimal)\)$/iu; -const EFFORT_ORDER = ["high", "medium", "low", "minimal"]; +const EFFORT_NAME = /^(.*\S)\s*\((Extra High|XHigh|High|Medium|Low|Minimal)\)$/iu; +const EFFORT_ORDER = ["extra high", "xhigh", "high", "medium", "low", "minimal"]; export const ANTIGRAVITY_EFFORT_OPTION_ID = "effort"; +const ANTIGRAVITY_MODEL_PROBE_STEP_TIMEOUT = "4 seconds"; export interface AntigravityModelFamily { readonly slug: string; @@ -410,13 +422,88 @@ export function nextAntigravityCatalog( if (currentValue && (current || Object.keys(thoughtLevels).length > 0)) { thoughtLevels[currentValue] = current ?? null; } + const previousListed = new Set((previous?.choices ?? []).map((choice) => choice.value)); + const probed = + previous?.probed === true && choices.every((choice) => previousListed.has(choice.value)); return { choices, ...(currentValue ? { currentValue } : {}), ...(Object.keys(thoughtLevels).length > 0 ? { thoughtLevels } : {}), + ...(probed ? { probed: true } : {}), }; } +/** + * Whether a saved catalog already has per-model reasoning levels for every + * listed model (or came from an older effort-in-name agent). An incomplete + * catalog triggers one discovery pass so every model's own options are known. + */ +export function isAntigravityCatalogComplete(catalog: AntigravityCatalogCache): boolean { + if (catalog.probed === true) return true; + if (catalog.choices.some((choice) => EFFORT_NAME.test(choice.name.trim()))) return true; + const levels = catalog.thoughtLevels; + if (!levels) return false; + return catalog.choices.every((choice) => choice.value in levels); +} + +/** + * Cycles through every listed model inside one open ACP session to capture + * each model's own `thought_level` options, then restores the initial model. + * Returns `undefined` for older effort-in-name agents or sessions without a + * model option. + */ +export const probeAntigravityModelOptions = ( + acp: Pick, +) => + Effect.gen(function* () { + const initialOptions = yield* acp.getConfigOptions; + const modelOption = findModelConfigOption(initialOptions); + const choices = flattenSessionConfigSelectOptions(modelOption); + if (!modelOption || choices.length === 0) return undefined; + if (choices.some((choice) => EFFORT_NAME.test(choice.name.trim()))) return undefined; + + const currentValue = selectConfigOptionCurrentValue(modelOption); + const modelOptions: Array = []; + const thoughtLevels: Record = {}; + let switched = false; + + if (currentValue) { + modelOptions.push({ slug: currentValue, configOptions: initialOptions }); + thoughtLevels[currentValue] = antigravityThoughtLevels(initialOptions) ?? null; + } + + for (const choice of choices) { + if (choice.value === currentValue) continue; + const nextOptions = yield* acp.setConfigOption(modelOption.id, choice.value).pipe( + Effect.flatMap((response) => + response.configOptions && response.configOptions.length > 0 + ? Effect.succeed(response.configOptions) + : acp.getConfigOptions, + ), + Effect.timeout(ANTIGRAVITY_MODEL_PROBE_STEP_TIMEOUT), + Effect.catchCause(() => Effect.succeed(undefined)), + ); + if (nextOptions) { + switched = true; + modelOptions.push({ slug: choice.value, configOptions: nextOptions }); + thoughtLevels[choice.value] = antigravityThoughtLevels(nextOptions) ?? null; + } + } + + if (switched && currentValue) { + yield* acp + .setConfigOption(modelOption.id, currentValue) + .pipe(Effect.timeout(ANTIGRAVITY_MODEL_PROBE_STEP_TIMEOUT), Effect.ignore); + } + + return { + choices, + ...(currentValue ? { currentValue } : {}), + thoughtLevels, + modelOptions, + }; + }); + /** * The agent's model id for a family slug and the selected effort; agent ids * (custom models) pass through. @@ -491,6 +578,214 @@ function antigravityOptionWarning(option: EffectAcpSchema.PermissionOption): str return text.length > 0 ? `${text.slice(0, 500)}.` : undefined; } +interface AntigravityElicitationOption { + readonly const: string; + readonly label: string; + readonly description: string; +} + +const QUESTION_KEY = /^q([1-9]\d*)$/u; +const QUESTION_OTHER_KEY = /^q([1-9]\d*)_other$/u; + +function parseElicitationOptions( + raw: unknown, +): ReadonlyArray | undefined { + if (!Array.isArray(raw) || raw.length === 0) return undefined; + const seenValues = new Set(); + const seenLabels = new Set(); + const options: Array = []; + for (const entry of raw) { + if (typeof entry !== "object" || entry === null) return undefined; + const candidate = entry as { const?: unknown; title?: unknown; description?: unknown }; + if (typeof candidate.const !== "string" || candidate.const.length === 0) return undefined; + const label = + typeof candidate.title === "string" && candidate.title.trim().length > 0 + ? candidate.title.trim() + : candidate.const; + if (seenValues.has(candidate.const) || seenLabels.has(label)) return undefined; + seenValues.add(candidate.const); + seenLabels.add(label); + const description = + typeof candidate.description === "string" && candidate.description.trim().length > 0 + ? candidate.description.trim() + : label; + options.push({ const: candidate.const, label, description }); + } + return options; +} + +/** + * Folds Antigravity 1.5's `ask_question` ACP form elicitation (paired `qN` + * choice fields + `qN_other` free-text fields, sorted numerically from Go's + * lexicographic map order) into Threadlines' standard question card. + * Returns `undefined` for any other form so the generic form UI handles it. + */ +export function extractAntigravityElicitationForm( + request: AcpElicitationFormRequest, +): AcpElicitationQuestions | undefined { + if (request.mode !== undefined && request.mode !== null && request.mode !== "form") { + return undefined; + } + const schema = request.requestedSchema; + if (!schema || typeof schema.properties !== "object" || schema.properties === null) { + return undefined; + } + if (Array.isArray(schema.required) && schema.required.length > 0) return undefined; + + const properties = schema.properties; + const keys = Object.keys(properties); + if (keys.length === 0) return undefined; + + const questionNumbers = new Set(); + const otherNumbers = new Set(); + for (const key of keys) { + const qMatch = QUESTION_KEY.exec(key); + if (qMatch) { + questionNumbers.add(Number(qMatch[1])); + continue; + } + const otherMatch = QUESTION_OTHER_KEY.exec(key); + if (otherMatch) { + otherNumbers.add(Number(otherMatch[1])); + continue; + } + return undefined; + } + if (questionNumbers.size === 0 || questionNumbers.size !== otherNumbers.size) return undefined; + for (const num of questionNumbers) { + if (!otherNumbers.has(num)) return undefined; + } + + const orderedNumbers = [...questionNumbers].toSorted((a, b) => a - b); + const parsed: Array<{ + readonly key: string; + readonly otherKey: string; + readonly multiSelect: boolean; + readonly options: ReadonlyArray; + readonly question: UserInputQuestion; + }> = []; + + for (const [index, num] of orderedNumbers.entries()) { + const key = `q${num}`; + const otherKey = `q${num}_other`; + const field = properties[key]; + const other = properties[otherKey]; + if ( + typeof field !== "object" || + field === null || + typeof other !== "object" || + other === null + ) { + return undefined; + } + const otherRecord = other as { type?: unknown; enum?: unknown; oneOf?: unknown }; + if (otherRecord.type !== "string" || otherRecord.enum != null || otherRecord.oneOf != null) { + return undefined; + } + + const fieldRecord = field as { + type?: unknown; + title?: unknown; + oneOf?: unknown; + items?: unknown; + }; + const title = + typeof fieldRecord.title === "string" && fieldRecord.title.trim().length > 0 + ? fieldRecord.title.trim() + : undefined; + if (!title) return undefined; + + let multiSelect = false; + let options: ReadonlyArray | undefined; + if (fieldRecord.type === "string") { + options = parseElicitationOptions(fieldRecord.oneOf); + } else if ( + fieldRecord.type === "array" && + typeof fieldRecord.items === "object" && + fieldRecord.items !== null + ) { + multiSelect = true; + options = parseElicitationOptions((fieldRecord.items as { anyOf?: unknown }).anyOf); + } + if (!options) return undefined; + + parsed.push({ + key, + otherKey, + multiSelect, + options, + question: { + id: key, + header: `Question ${index + 1}`, + question: title, + options: options.map((option) => ({ + label: option.label, + description: option.description, + })), + multiSelect, + }, + }); + } + + const responseForAnswers = (answers: ProviderUserInputAnswers): AcpElicitationFormResponse => { + if (Object.keys(answers).length === 0) return { action: "cancel" }; + const content: Record> = {}; + for (const item of parsed) { + const raw = answers[item.key]; + if (raw === undefined || raw === null) continue; + const findOption = (value: string) => + item.options.find((option) => option.const === value || option.label === value); + + if (!item.multiSelect) { + const text = + typeof raw === "string" + ? raw.trim() + : Array.isArray(raw) && raw.length === 1 && typeof raw[0] === "string" + ? raw[0].trim() + : ""; + if (!text) continue; + const matched = findOption(text); + if (matched) content[item.key] = matched.const; + else content[item.otherKey] = text; + continue; + } + + if (typeof raw === "string") { + const text = raw.trim(); + if (!text) continue; + const matched = findOption(text); + if (matched) content[item.key] = [matched.const]; + else content[item.otherKey] = text; + continue; + } + + if (Array.isArray(raw)) { + const selected: Array = []; + const custom: Array = []; + for (const entry of raw) { + if (typeof entry !== "string") continue; + const text = entry.trim(); + if (!text) continue; + const matched = findOption(text); + if (matched) { + if (!selected.includes(matched.const)) selected.push(matched.const); + } else { + custom.push(text); + } + } + if (selected.length > 0) content[item.key] = selected; + if (custom.length > 0) content[item.otherKey] = custom.join("\n"); + } + } + return Object.keys(content).length > 0 ? { action: "accept", content } : { action: "cancel" }; + }; + + return { + questions: parsed.map((item) => item.question), + responseForAnswers, + }; +} + // ── Plan mode: `/plan` writes a plan file into the profile ─────────── function toolCallPaths(data: Record): ReadonlyArray { @@ -757,19 +1052,26 @@ export function makeAntigravityDescriptor( * custom binary its path, size and change time, so replacing the file * lists models afresh. */ + let lastAgentTag: string | undefined; const agentTag = (settings: AntigravitySettings) => { const custom = settings.binaryPath.trim(); - if (custom) { - return Effect.promise(() => - fs.stat(custom).then( - (stat) => `custom:${resolvePath(custom)}:${stat.size}:${Math.trunc(stat.mtimeMs)}`, - () => undefined, - ), - ); - } - return runtime - ? runtime.installed.pipe(Effect.map((installed) => installed?.version)) - : Effect.succeed(undefined); + const read = custom + ? Effect.promise(() => + fs.stat(custom).then( + (stat) => `custom:${resolvePath(custom)}:${stat.size}:${Math.trunc(stat.mtimeMs)}`, + () => undefined, + ), + ) + : runtime + ? runtime.installed.pipe(Effect.map((installed) => installed?.version)) + : Effect.succeed(undefined); + return read.pipe( + Effect.tap((tag) => + Effect.sync(() => { + if (tag !== undefined) lastAgentTag = tag; + }), + ), + ); }; const readCatalog = (agentVersion: string | undefined) => @@ -871,8 +1173,16 @@ export function makeAntigravityDescriptor( : {}), agentModeFor: ({ runtimeMode, interactionMode, availableModeIds }) => antigravityAgentMode(runtimeMode, interactionMode, availableModeIds), + // `agy acp` 1.5 accepts `type: "http"` MCP servers in `session/new` / + // `session/resume` / `session/load` while omitting `mcpCapabilities.http` + // in `initialize` (google-antigravity/antigravity-cli#1604). + assumeHttpMcp: true, + clientCapabilities: { elicitation: { form: {} } }, classifyPermissionRequest: antigravityQuestion, + classifyElicitationForm: extractAntigravityElicitationForm, permissionOptionWarning: antigravityOptionWarning, + onEphemeralSessionClosed: (sessionId) => + removeAntigravitySessionFiles(paths.profileDir, sessionId), cancellationNotice: "The request was cancelled by the client.", // Tool text bounded, no inline images, `call_mcp_tool` shown as the MCP tool. normalizeSessionUpdate: normalizeAntigravitySessionUpdate, @@ -1025,7 +1335,9 @@ export function makeAntigravityDescriptor( version, ...signInStatus, ...latest, - ...(catalog ? { models: antigravityModelsFromCatalog(catalog) } : {}), + ...(catalog && isAntigravityCatalogComplete(catalog) + ? { models: antigravityModelsFromCatalog(catalog) } + : {}), } satisfies AcpProviderProbeOutcome; return usage ? withAntigravityUsage(outcome, yield* usage.status) : outcome; }), @@ -1041,9 +1353,24 @@ export function makeAntigravityDescriptor( ), ), modelDiscoveryTimeoutMs: ANTIGRAVITY_DISCOVERY_TIMEOUT_MS, - // Discovery mirrors the selected model's options (its reasoning levels) - // onto every model; the next status check reads each model's own from - // the saved list. Older agents name the level in the model: fold those. + discoverModelOptions: (acp) => + Effect.gen(function* () { + const probed = yield* probeAntigravityModelOptions(acp); + if (!probed) return undefined; + const init = yield* acp.getInitializeResult; + const agentVersion = lastAgentTag ?? init?.agentInfo?.version?.trim() ?? undefined; + yield* writeAntigravityCatalog(paths.profileDir, { + choices: probed.choices, + ...(probed.currentValue ? { currentValue: probed.currentValue } : {}), + thoughtLevels: probed.thoughtLevels, + probed: true, + fingerprint, + ...(agentVersion ? { agentVersion } : {}), + }); + return probed.modelOptions; + }), + // Older agents name the level in the model: fold those. Newer agents are + // probed once per catalog in `listModelOptions` and read from disk thereafter. enrichDiscoveredModels: (models) => Effect.succeed( models.some((model) => EFFORT_NAME.test(model.name.trim())) diff --git a/apps/server/src/provider/antigravity/AntigravityAuth.ts b/apps/server/src/provider/antigravity/AntigravityAuth.ts index 197edf5a8..b7b46d29d 100644 --- a/apps/server/src/provider/antigravity/AntigravityAuth.ts +++ b/apps/server/src/provider/antigravity/AntigravityAuth.ts @@ -383,6 +383,7 @@ export function makeAntigravityAuthFlows(input: { // method's sign-in: one Google refuses a session (no plan, unverified) // stays signed out. yield* emit("Checking the sign-in…"); + let verifiedSessionId: string | undefined; yield* Effect.scoped( Effect.gen(function* () { const acp = yield* makeAcpProviderRuntime(input.descriptor, { @@ -392,9 +393,22 @@ export function makeAntigravityAuthFlows(input: { cwd: input.profileDir, clientInfo: THREADLINES_ACP_CLIENT_INFO, }); - yield* acp.start(); + const started = yield* acp.start(); + verifiedSessionId = started.sessionId; + // Reuse this already-open session to capture every model's own + // `thought_level` options so the picker is accurate right away. + if (input.descriptor.discoverModelOptions) { + yield* input.descriptor.discoverModelOptions(acp).pipe(Effect.ignore); + } }), ).pipe( + Effect.ensuring( + Effect.suspend(() => + verifiedSessionId !== undefined && input.descriptor.onEphemeralSessionClosed + ? input.descriptor.onEphemeralSessionClosed(verifiedSessionId).pipe(Effect.ignore) + : Effect.void, + ), + ), Effect.timeoutOrElse({ duration: VERIFY_TIMEOUT, orElse: () => diff --git a/apps/server/src/provider/antigravity/AntigravityProfile.ts b/apps/server/src/provider/antigravity/AntigravityProfile.ts index 0f22e2523..1de7bd182 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -12,6 +12,7 @@ * @module provider/antigravity/AntigravityProfile */ import { createHash, randomBytes } from "node:crypto"; +import { existsSync } from "node:fs"; import * as fs from "node:fs/promises"; import { join, resolve } from "node:path"; @@ -61,9 +62,27 @@ export const antigravityTokenPath = (profileDir: string) => export const antigravityLegacyTokenPath = (profileDir: string) => join(antigravityAgentDir(profileDir), "acp_token.json"); -/** Credentials and project settings that would steer the agent away from this profile. */ +/** Credentials, project settings and host-Electron internals that steer or break the child. */ const STRIPPED_ENV_KEY = - /^(GEMINI_|GOOGLE_|GCLOUD_|CLOUDSDK_|AGY_|ANTIGRAVITY_)|^(BROWSER|PYTHONUNBUFFERED|PYTHONHOME|PYTHONPATH)$/iu; + /^(GEMINI_|GOOGLE_|GCLOUD_|CLOUDSDK_|AGY_|ANTIGRAVITY_)|^(BROWSER|PYTHONUNBUFFERED|PYTHONHOME|PYTHONPATH|ELECTRON_RUN_AS_NODE|CHROME_CRASHPAD_PIPE_NAME)$/iu; + +const LINUX_CA_BUNDLE_PATHS = [ + "/etc/ssl/certs/ca-bundle.crt", + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/cert.pem", +] as const; + +function resolveLinuxSslCertFile( + base: NodeJS.ProcessEnv, + exists: (path: string) => boolean, +): string | undefined { + const candidates = [ + ...(base.NIX_SSL_CERT_FILE?.trim() ? [base.NIX_SSL_CERT_FILE.trim()] : []), + ...LINUX_CA_BUNDLE_PATHS, + ]; + return candidates.find((candidate) => exists(candidate)); +} /** * What the CLI takes for a session over SSH. It then keeps a Google sign-in @@ -96,6 +115,8 @@ export function antigravityEnvironment(input: { readonly tempDir: string; readonly platform: NodeJS.Platform; readonly credentials?: Readonly>; + /** Test seam for Linux CA bundle discovery. */ + readonly pathExists?: (path: string) => boolean; }): NodeJS.ProcessEnv { const env: NodeJS.ProcessEnv = {}; for (const [key, value] of Object.entries(input.base)) { @@ -107,6 +128,15 @@ export function antigravityEnvironment(input: { env.AGY_CLI_DISABLE_AUTO_UPDATE = "1"; env.SSH_CONNECTION = input.base.SSH_CONNECTION?.trim() || SSH_CONNECTION_STAND_IN; env.BROWSER = noopBrowser(input.platform, input.base); + // Keep subcommands run by the agent non-interactive so pagers and git prompts never hang. + env.PAGER = "cat"; + env.GH_PAGER = "cat"; + env.GIT_PAGER = "cat"; + env.GIT_TERMINAL_PROMPT = "0"; + if (input.platform === "linux" && !env.SSL_CERT_FILE?.trim() && !env.SSL_CERT_DIR?.trim()) { + const certFile = resolveLinuxSslCertFile(input.base, input.pathExists ?? existsSync); + if (certFile) env.SSL_CERT_FILE = certFile; + } if (input.platform === "win32") { env.TEMP = input.tempDir; env.TMP = input.tempDir; @@ -250,6 +280,8 @@ export interface AntigravityCatalogCache { * it had none. Models not seen yet are missing. */ readonly thoughtLevels?: Readonly>; + /** True once a probe pass has checked every listed model's `thought_level` options. */ + readonly probed?: boolean; /** The sign-in it was listed for (`antigravityCredentialFingerprint`). */ readonly fingerprint?: string; /** The managed runtime version that listed it; absent for a custom binary. */ @@ -329,6 +361,7 @@ export const readAntigravityCatalog = ( ? { currentValue: parsed.currentValue } : {}), ...(thoughtLevels ? { thoughtLevels } : {}), + ...(parsed.probed === true ? { probed: true } : {}), fingerprint: sign.fingerprint, ...(sign.agentVersion ? { agentVersion: sign.agentVersion } : {}), } diff --git a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts index d85f7b950..733b08b75 100644 --- a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -229,3 +229,31 @@ export const antigravityTurnSteps = (profileDir: string, sessionId: string, afte }); return typeof steps === "string" ? undefined : steps.value; }).pipe(Effect.orElseSucceed(() => undefined)); + +/** + * Removes the CLI's on-disk files for one throwaway session (model discovery, + * sign-in verification, text generation) once its process has exited. Every + * path is verified inside the profile with no symlinks via + * `antigravityProfileEntry`. + */ +export const removeAntigravitySessionFiles = (profileDir: string, sessionId: string) => + Effect.promise(async () => { + if (!SESSION_ID.test(sessionId)) return; + const files: ReadonlyArray> = [ + ["conversations", `${sessionId}.db`], + ["conversations", `${sessionId}.db-wal`], + ["conversations", `${sessionId}.db-shm`], + ["conversations", `${sessionId}.db-journal`], + ["annotations", `${sessionId}.pbtxt`], + ]; + for (const segments of files) { + const entry = await antigravityProfileEntry(profileDir, segments, "file"); + if (typeof entry !== "string") { + await NodeFSP.rm(entry.path, { force: true }).catch(() => undefined); + } + } + const brainEntry = await antigravityProfileEntry(profileDir, ["brain", sessionId], "directory"); + if (typeof brainEntry !== "string") { + await NodeFSP.rm(brainEntry.path, { recursive: true, force: true }).catch(() => undefined); + } + }); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index b327f4d2a..c362fd2b8 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -437,6 +437,94 @@ describe("Antigravity turns", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); + it.live( + "fails a held turn when an upstream error lands during its post-prompt wake-up reply", + () => + Effect.gen(function* () { + const agy = yield* startAgy("background-log-error"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "build it", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ + state: "failed", + failureCategory: "server_error", + errorMessage: + "Antigravity: Bad Gateway: Failed to connect to backend API (502 Bad Gateway)", + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "folds ask_question form elicitations into a question card and returns flat ACP answers", + () => + Effect.gen(function* () { + const agy = yield* startAgy("ask-question"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "ask me", + attachments: [], + }); + yield* agy.waitFor((events) => + events.some((event) => event.type === "user-input.requested"), + ); + const requested = agy.events.find( + (event): event is Extract => + event.type === "user-input.requested", + )!; + expect(requested.payload.questions).toEqual([ + { + id: "q1", + header: "Question 1", + question: "Which runtime should we target?", + options: [ + { label: "Node.js", description: "Default runtime" }, + { label: "Deno", description: "Deno" }, + ], + multiSelect: false, + }, + { + id: "q2", + header: "Question 2", + question: "Which checks should run?", + options: [ + { label: "Typecheck", description: "Typecheck" }, + { label: "Unit tests", description: "Unit tests" }, + { label: "Lint", description: "Lint" }, + ], + multiSelect: true, + }, + ]); + yield* agy.adapter.respondToUserInput( + agy.threadId, + ApprovalRequestId.make(String(requested.requestId)), + { q1: "Bun instead", q2: ["Typecheck", "Lint"] }, + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain( + JSON.stringify({ + action: "accept", + content: { q1_other: "Bun instead", q2: ["1", "3"] }, + }), + ); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("attaches HTTP MCP servers even when agy omits mcpCapabilities.http in initialize", () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + const frames = yield* agy.frames(); + const initFrame = frames.find((frame) => frame.method === "initialize") as + | { params?: { clientCapabilities?: { elicitation?: unknown } } } + | undefined; + expect(initFrame?.params?.clientCapabilities?.elicitation).toEqual({ form: {} }); + const newSessionFrame = frames.find((frame) => frame.method === "session/new") as + | { params?: { mcpServers?: ReadonlyArray<{ type?: string; name?: string }> } } + | undefined; + expect(newSessionFrame?.params?.mcpServers?.some((server) => server.type === "http")).toBe( + true, + ); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + it.live("carries an exhausted quota's reset time to the usage-limit notice", () => Effect.gen(function* () { const agy = yield* startAgy("quota"); @@ -1472,6 +1560,60 @@ describe("Antigravity turn reading", () => { nowMs, })?.failureCategory, ).toBe("model_unavailable"); + // 1.5 JSON quota details + retryDelay + protobuf length byte prefix before status name. + expect( + antigravityFailure({ + errorText: + 'PRESOURCE_EXHAUSTED (code 429): Exhausted. {"details":[{"reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetTimeStamp":"2026-11-23T11:00:00Z","retryDelay":"45.2s"}}]}', + nowMs, + }), + ).toEqual({ + errorMessage: "You've reached your Antigravity quota for now.", + failureCategory: "rate_limit", + usageLimit: { resetsAt: "2026-11-23T12:00:45.200Z" }, + }); + expect( + antigravityFailure({ + errorText: "PRESOURCE_EXHAUSTED (code 429): Too many requests.", + nowMs, + }), + ).toEqual({ + errorMessage: "Antigravity: Too many requests. (429 RESOURCE_EXHAUSTED)", + failureCategory: "rate_limit", + }); + // VALIDATION_REQUIRED surfaces only allowlisted Google verification URLs. + expect( + antigravityFailure({ + errorText: + 'PERMISSION_DENIED: Verify your account. {"reason":"VALIDATION_REQUIRED","validation_url":"https://accounts.google.com/v3/signin/continue?plt=xyz"}', + nowMs, + }), + ).toEqual({ + errorMessage: + "Google needs you to verify this account before Antigravity can continue. Verify it at https://accounts.google.com/v3/signin/continue?plt=xyz, then try again.", + failureCategory: "auth", + }); + expect( + antigravityFailure({ + errorText: "VALIDATION_REQUIRED https://evil.example/v3/signin/continue", + nowMs, + })?.errorMessage, + ).not.toContain("evil.example"); + // Mid-turn 401 after the model already answered is retryable; initial 401 is auth. + expect( + antigravityFailure({ + errorText: "UNAUTHENTICATED (code 401): Request had invalid authentication credentials.", + reachedModel: true, + nowMs, + })?.failureCategory, + ).toBe("server_error"); + expect( + antigravityFailure({ + errorText: "UNAUTHENTICATED (code 401): Request had invalid authentication credentials.", + reachedModel: false, + nowMs, + })?.failureCategory, + ).toBe("auth"); }); it.effect( diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 95aa30092..01a1cc202 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -33,6 +33,7 @@ import type { AcpWorkAfterPrompt, } from "../acp/AcpProviderDescriptor.ts"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { antigravityVerificationUrl } from "./AntigravityAuth.ts"; import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.ts"; import { antigravityChildLaunches } from "./AntigravityChildRecords.ts"; import { isAntigravitySubagentLaunch } from "./AntigravitySubagents.ts"; @@ -117,17 +118,26 @@ export function antigravityTurnUsageTotals( */ const API_ERROR = /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/su; +/** Canonical gRPC status codes, so a preceding protobuf length byte isn't swallowed into the name. */ +const GRPC_STATUS_NAMES = + "CANCELLED|UNKNOWN|INVALID_ARGUMENT|DEADLINE_EXCEEDED|NOT_FOUND|ALREADY_EXISTS|PERMISSION_DENIED|RESOURCE_EXHAUSTED|FAILED_PRECONDITION|ABORTED|OUT_OF_RANGE|UNIMPLEMENTED|INTERNAL|UNAVAILABLE|DATA_LOSS|UNAUTHENTICATED"; /** 1.5 with a Google account: "STATUS (code NNN): message". */ -const STATUS_ERROR = /(? = { ns: 1e-6, @@ -145,20 +155,33 @@ const LOST_SESSION_MESSAGE = "Antigravity's saved conversation can no longer be sent to the model. The next message starts a new Antigravity session with this thread's history."; const UNKNOWN_ERROR_MESSAGE = "Antigravity stopped this turn because of an error."; -/** When an exhausted quota resets, as the error says, in ISO time. */ -function quotaResetAt(text: string, nowMs: number): string | undefined { - const stamp = RESET_TIMESTAMP.exec(text)?.[1]; - if (stamp !== undefined) { - const ms = Date.parse(stamp); - if (Number.isFinite(ms)) return new Date(ms).toISOString(); - } - const delay = RESET_DELAY.exec(text)?.[1]; - if (delay === undefined) return undefined; +function parseGoDurationMs(delay: string): number { let delayMs = 0; for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) { delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0); } - return delayMs > 0 ? new Date(nowMs + delayMs).toISOString() : undefined; + return delayMs; +} + +/** + * When an exhausted quota resets, as the error says, in ISO time. Prefers a + * future `quotaResetTimeStamp`, else a positive `quotaResetDelay` or + * `retryDelay`, else a valid past timestamp when no delay was given. + */ +function quotaResetAt(text: string, nowMs: number): string | undefined { + const stampMatch = RESET_TIMESTAMP.exec(text); + const stamp = stampMatch?.[1] ?? stampMatch?.[2]; + const stampMs = stamp !== undefined ? Date.parse(stamp) : Number.NaN; + if (Number.isFinite(stampMs) && stampMs > nowMs) { + return new Date(stampMs).toISOString(); + } + const delayMatch = RESET_DELAY.exec(text) ?? RETRY_DELAY.exec(text); + const delay = delayMatch?.[1] ?? delayMatch?.[2]; + if (delay !== undefined) { + const delayMs = parseGoDurationMs(delay); + if (delayMs > 0) return new Date(nowMs + Math.ceil(delayMs)).toISOString(); + } + return Number.isFinite(stampMs) ? new Date(stampMs).toISOString() : undefined; } /** HTTP status, message and status name, from either rendering. */ @@ -201,6 +224,15 @@ export function antigravityFailure(input: { if (LOST_THINKING_SIGNATURE.test(text)) { return { errorMessage: LOST_SESSION_MESSAGE, sessionLost: true }; } + if (VALIDATION_REQUIRED.test(text)) { + const url = antigravityVerificationUrl(text); + return { + errorMessage: url + ? `Google needs you to verify this account before Antigravity can continue. Verify it at ${url}, then try again.` + : "Google needs you to verify this account before Antigravity can continue. Sign in to Google in your browser to verify it, then try again.", + failureCategory: "auth", + }; + } const api = parseApiError(text); if (api === undefined) return { errorMessage: UNKNOWN_ERROR_MESSAGE }; const rateLimited = api.httpStatus === 429 || api.status === "RESOURCE_EXHAUSTED"; @@ -211,7 +243,11 @@ export function antigravityFailure(input: { ? input.reachedModel === true ? "server_error" : "model_unavailable" - : httpStatusFailureCategory(api.httpStatus); + : api.httpStatus === 401 || api.status === "UNAUTHENTICATED" + ? input.reachedModel === true + ? "server_error" + : "auth" + : httpStatusFailureCategory(api.httpStatus); return { errorMessage: `Antigravity: ${api.message} (${api.status.startsWith(String(api.httpStatus)) ? api.status : `${api.httpStatus} ${api.status}`})`, ...(failureCategory !== undefined ? { failureCategory } : {}), @@ -296,6 +332,7 @@ function antigravityPromptOutcome( errorText !== undefined && (parseApiError(errorText) !== undefined || QUOTA_EXHAUSTED.test(errorText) || + VALIDATION_REQUIRED.test(errorText) || LOST_THINKING_SIGNATURE.test(errorText)); return recognized ? yield* withMeterReset(antigravityFailure({ errorText, nowMs })) diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts index 00830a784..d61ef6ad3 100644 --- a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts @@ -197,6 +197,7 @@ const signedInSnapshot = (method: AntigravityAuthMethod) => const setup = (input: { route: Route; method?: AntigravityAuthMethod; + project?: string; token?: Parameters[1] | false; timeouts?: { request: Duration.Input; read: Duration.Input }; models?: ServerProvider["models"]; @@ -210,6 +211,7 @@ const setup = (input: { profileDir, method, fingerprint: "fingerprint-a", + ...(input.project ? { project: input.project } : {}), fetch: google.fetch, ...(input.timeouts ? { timeouts: input.timeouts } : {}), }); @@ -743,4 +745,20 @@ describe("Antigravity plan limits", () => { }); }), ); + + it.effect("sends the configured Google Cloud project in Cloud Code requests for Enterprise", () => + Effect.gen(function* () { + const { readOnce, google } = yield* setup({ + method: "oauth-business", + project: "acme-enterprise-proj", + route: googleRoute({ summary: { body: SUMMARY } }), + }); + yield* readOnce; + const posts = google.sent.filter((request) => request.method === "POST"); + assert.isAbove(posts.length, 0); + for (const request of posts) { + assert.equal(request.body, JSON.stringify({ project: "acme-enterprise-proj" })); + } + }), + ); }); diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.ts b/apps/server/src/provider/antigravity/AntigravityUsage.ts index fc50992b2..317139acd 100644 --- a/apps/server/src/provider/antigravity/AntigravityUsage.ts +++ b/apps/server/src/provider/antigravity/AntigravityUsage.ts @@ -557,8 +557,10 @@ const askHosts = ( operation: "retrieveUserQuotaSummary" | "fetchAvailableModels", parse: (answer: unknown, requestedAtMs: number) => ReadonlyArray, timeout: Duration.Input, -) => - Effect.forEach( + project?: string, +) => { + const body = project ? JSON.stringify({ project }) : "{}"; + return Effect.forEach( HOSTS_BY_METHOD[method], (host) => Effect.gen(function* () { @@ -566,7 +568,7 @@ const askHosts = ( const answer = yield* requestJson( fetch, `https://${host}/v1internal:${operation}`, - { method: "POST", accessToken, body: "{}" }, + { method: "POST", accessToken, body }, timeout, ); return { answered: true, windows: parse(answer, requestedAtMs) }; @@ -578,6 +580,7 @@ const askHosts = ( windows: mergeHosts(answers.map((answer) => answer.windows)), })), ); +}; /** * One full read. The summary comes first; when it has no Gemini row (Google @@ -589,6 +592,7 @@ const readQuotaWindows = ( method: GoogleMethod, accessToken: string, timeout: Duration.Input, + project?: string, ) => Effect.gen(function* () { const summary = yield* askHosts( @@ -598,6 +602,7 @@ const readQuotaWindows = ( "retrieveUserQuotaSummary", antigravitySummaryWindows, timeout, + project, ); if (summary.windows.some((window) => window.family.gemini)) return summary; const models = yield* askHosts( @@ -607,6 +612,7 @@ const readQuotaWindows = ( "fetchAvailableModels", antigravityModelWindows, timeout, + project, ); if (summary.windows.length === 0) { return { windows: models.windows, complete: summary.complete && models.complete }; @@ -686,6 +692,8 @@ export interface AntigravityUsageReaderInput { readonly method: AntigravityAuthMethod; /** `antigravityCredentialFingerprint` of the instance's sign-in. */ readonly fingerprint: string; + /** Google Cloud project for Gemini Enterprise (`oauth-business`), sent in Cloud Code requests. */ + readonly project?: string; /** Test seam; by default a fetch held to `ANTIGRAVITY_USAGE_HOSTS` with no redirects. */ readonly fetch?: DownloadFetch; /** Test seam; by default 10 seconds per request and 30 per read. */ @@ -789,7 +797,13 @@ export const makeAntigravityUsageReader = ( return yield* Effect.gen(function* () { const [windows, email] = yield* Effect.all( [ - readQuotaWindows(fetch, method, token.accessToken, timeouts.request), + readQuotaWindows( + fetch, + method, + token.accessToken, + timeouts.request, + input.project?.trim() || undefined, + ), token.email !== undefined || emails.has(key) ? Effect.succeed(token.email ?? emails.get(key)) : readEmail(fetch, token.accessToken, timeouts.request), diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index e3f299b89..c680ba025 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -46,7 +46,12 @@ thread's earlier turns as context. ## Models and Access Levels The model picker lists the models your account has, Claude and GPT models included where your plan -has them. The reasoning level is its own choice next to the model. +has them. The reasoning level is its own choice next to the model, probed per model in a single +session during sign-in or the first status check and cached per account and Antigravity version. +Questions asked via Antigravity's `ask_question` tool appear as normal multi-step question cards +(supporting single-select, multi-select, and custom answers). Threadlines' built-in HTTP MCP tools +(browser panel, rooms, pages, commands, devices) are attached to every session even though +`agy acp` omits `mcpCapabilities.http` in its `initialize` response. | Access level | What Antigravity runs | | ----------------- | ------------------------------------------------------------------------------ | @@ -242,21 +247,25 @@ never through a link, up to each kind's limit and 50 MB inline per message. ### When a turn fails -Antigravity sometimes ends a turn normally while the reply is really an upstream error. Threadlines +Antigravity sometimes ends a turn normally while the reply is really an upstream error (including +during a reply it started by itself after a background command or subagent finished). Threadlines reads the error the CLI reports (1.5.9+) and, where the CLI reports none, the last step of the turn in the CLI's own session log (`antigravity-acp/conversations/.db` in the profile, a -private format read only for this). The log doesn't say which prompt wrote a step, so an error +private format read only for this), checking again before a held turn settles if the agent spoke +after its prompt answered. The log doesn't say which prompt wrote a step, so an error counts for the newest prompt when it is the log's last step and was written after that prompt went out. That never hides the newest prompt's own failure; the cost is that an older prompt's late error, with nothing written after it, fails a turn whose steer was answered. When the log can't be read, the prompt's own answer stands (the agent's words about the error stay in its reply). The turn then fails with Google's words and a -Retry. An +Retry (or Google's account verification link when `VALIDATION_REQUIRED` is returned). An exhausted quota fails with its reset time, so the usage-limit notice above the composer says when it resets and can continue then. A conversation Google can no longer continue (a model rejected a saved thinking block) stops its session, and the next message starts a new one with the thread's history, also one sent in the moment the session is stopping. A message whose mode or model couldn't be set never reaches Antigravity: its turn fails, and the earlier conversation Threadlines had put in -front of it goes with the next message instead. +front of it goes with the next message instead. Throwaway sessions opened for sign-in checks, +model discovery, or text generation have their conversation files cleaned up from the profile once +they exit. ### Editing an Earlier Message