Skip to content
Merged
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
35 changes: 24 additions & 11 deletions apps/server/src/provider/acp/AcpProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -671,21 +671,38 @@ export const enrichAcpSnapshot = <Settings extends AcpProviderSettings>(input: {
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
/**
* Patches the current live snapshot in place so out-of-band patches
* (e.g. background usage readings) that landed while enrichment ran survive.
*/
readonly updateSnapshot?: (
update: (current: ServerProvider) => ServerProvider,
) => Effect.Effect<void>;
readonly stampIdentity: (snapshot: ServerProvider) => ServerProvider;
readonly httpClient: HttpClient.HttpClient;
/** The status checks' catalog: its options are probed once per read. */
readonly catalog?: AcpCatalogCache;
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
const { descriptor, settings, snapshot, publishSnapshot, stampIdentity } = input;
const displayName = descriptor.presentation.displayName;
const applyUpdate = (
fallbackBase: ServerProvider,
update: (current: ServerProvider) => ServerProvider,
) =>
input.updateSnapshot
? input.updateSnapshot((current) => stampIdentity(update(current)))
: publishSnapshot(stampIdentity(update(fallbackBase)));

const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
snapshot,
input.maintenanceCapabilities,
).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enriched) =>
publishSnapshot(stampIdentity(enriched)).pipe(Effect.as(enriched)),
applyUpdate(snapshot, (current) => ({
...current,
...(enriched.versionAdvisory ? { versionAdvisory: enriched.versionAdvisory } : {}),
})).pipe(Effect.as(enriched)),
),
Effect.catchCause((cause) =>
Effect.logWarning(`${displayName} version advisory enrichment failed`, {
Expand Down Expand Up @@ -730,17 +747,13 @@ export const enrichAcpSnapshot = <Settings extends AcpProviderSettings>(input: {
return Effect.void;
}
if (claim !== "none") input.catalog?.rememberCapabilities(claim, capabilitiesBySlug);
return publishSnapshot(
stampIdentity({
...baseSnapshot,
models: baseSnapshot.models.map((model) => {
const capabilities = model.isCustom
? undefined
: capabilitiesBySlug.get(model.slug);
return capabilities ? { ...model, capabilities } : model;
}),
return applyUpdate(baseSnapshot, (current) => ({
...current,
models: current.models.map((model) => {
const capabilities = model.isCustom ? undefined : capabilitiesBySlug.get(model.slug);
return capabilities ? { ...model, capabilities } : model;
}),
);
}));
}),
Effect.catchCause((cause) =>
Effect.logWarning(`${displayName} ACP background capability enrichment failed`, {
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/provider/acp/AcpProviderDescriptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,12 @@ export interface AcpProviderDescriptor<Settings extends AcpProviderSettings> {
* snapshot is built. Must be cheap and never throw.
*/
readonly snapshotExtras?: () => Partial<Pick<ServerProvider, "community">>;
/**
* Folds out-of-band state (e.g. a background usage read that finished while
* model discovery was still running) into a freshly checked snapshot inside
* the same atomic commit. Must be cheap and never throw.
*/
readonly reconcileSnapshot?: (previous: ServerProvider, next: ServerProvider) => ServerProvider;
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
/** Message shown when the binary cannot be spawned. */
readonly notInstalledMessage: string;
Expand Down
67 changes: 65 additions & 2 deletions apps/server/src/provider/acp/AcpProviderDriver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/http";
import { ChildProcessSpawner } from "effect/process";
import type { ServerProvider } from "@threadlines/contracts";
import {
ProviderDriverKind,
ProviderInstanceId,
type ServerProvider,
} from "@threadlines/contracts";
import { describe, expect, it } from "vite-plus/test";

import { checkAcpProviderStatus, makeAcpCatalogCache } from "./AcpProvider.ts";
import { checkAcpProviderStatus, enrichAcpSnapshot, makeAcpCatalogCache } from "./AcpProvider.ts";
import {
groupSessionCommands,
withSessionCommands,
Expand Down Expand Up @@ -351,3 +355,62 @@ describe.skipIf(process.platform === "win32")(
});
},
);

describe("enrichAcpSnapshot", () => {
it("preserves out-of-band accountUsage patches when applying version advisory via updateSnapshot", async () => {
const initial: ServerProvider = {
instanceId: ProviderInstanceId.make("cursor"),
driver: ProviderDriverKind.make("cursor"),
displayName: "Cursor",
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated", type: "oauth-personal" },
checkedAt: "2026-11-24T00:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
};
const usage: NonNullable<ServerProvider["accountUsage"]> = {
source: "grok-billing",
checkedAt: "2026-11-24T00:00:01.000Z",
primaryLimitId: "antigravity",
limits: [
{
limitId: "antigravity",
limitName: "Antigravity usage",
scoped: [
{
scopeLabel: "Gemini",
usedPercent: 12,
remainingPercent: 88,
},
],
},
],
};
// Out-of-band patch landed on the live snapshot before enrichment finished.
let live: ServerProvider = { ...initial, accountUsage: usage };
await Effect.runPromise(
enrichAcpSnapshot({
descriptor: { ...CURSOR_ACP_DESCRIPTOR, modelCapabilitiesVaryByModel: false },
settings: { enabled: true, binaryPath: "agent", apiEndpoint: "", customModels: [] },
snapshot: initial,
maintenanceCapabilities: {
...CURSOR_ACP_DESCRIPTOR.maintenance,
packageName: null,
},
publishSnapshot: () => Effect.die("expected updateSnapshot to be used"),
updateSnapshot: (update) =>
Effect.sync(() => {
live = update(live);
}),
stampIdentity: (next) => next,
httpClient: HttpClient.make(() => Effect.die("no network expected")),
}).pipe(Effect.provide(NodeServices.layer)),
);
expect(live.accountUsage).toEqual(usage);
expect(live.versionAdvisory?.currentVersion).toBe("1.0.0");
});
});
11 changes: 10 additions & 1 deletion apps/server/src/provider/acp/AcpProviderDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,14 +373,23 @@ export function makeAcpProviderDriver<Settings extends AcpProviderSettings, R =
),
checkProvider,
scheduledCheckProvider: check(true),
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
...(descriptor.reconcileSnapshot
? { reconcileSnapshot: descriptor.reconcileSnapshot }
: {}),
enrichSnapshot: ({
settings,
snapshot: currentSnapshot,
publishSnapshot,
updateSnapshot,
}) =>
enrichAcpSnapshot({
descriptor,
settings,
environment: processEnv,
snapshot: currentSnapshot,
maintenanceCapabilities,
publishSnapshot,
updateSnapshot,
stampIdentity,
httpClient,
catalog,
Expand Down
9 changes: 8 additions & 1 deletion apps/server/src/provider/acp/AntigravityAcpSupport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1216,7 +1216,11 @@ export function makeAntigravityDescriptor(
// Each launch shows as a subagent, read from the CLI's own records.
subagents: antigravitySubagents(paths.profileDir),
// Work that outlives a prompt, steering, hidden failures, turn tokens.
...antigravityTurnBehavior<AntigravitySettings>(paths.profileDir, usage?.usageLimitFor),
...antigravityTurnBehavior<AntigravitySettings>(
paths.profileDir,
usage?.usageLimitFor,
usage?.refresh,
),
planMode: {
promptPrefix: "/plan ",
isPlanFile: (toolCall, sessionId) =>
Expand Down Expand Up @@ -1251,6 +1255,7 @@ export function makeAntigravityDescriptor(
isolateTextGeneration: true,
onSessionConfigOptions: (settings, configOptions) =>
Effect.gen(function* () {
if (usage) yield* usage.refresh;
const agentVersion = yield* agentTag(settings);
const next = nextAntigravityCatalog(yield* readCatalog(agentVersion), configOptions);
if (!next) return;
Expand All @@ -1260,6 +1265,7 @@ export function makeAntigravityDescriptor(
...(agentVersion ? { agentVersion } : {}),
});
}),
...(usage ? { reconcileSnapshot: (_previous, next) => usage.reconcile(next) } : {}),
notInstalledMessage: NOT_INSTALLED_MESSAGE,
// The same test the probe makes: a custom binary only has to exist; the
// managed runtime is found when a complete copy is on disk. Both read the
Expand Down Expand Up @@ -1380,6 +1386,7 @@ export function makeAntigravityDescriptor(
discoverModelOptions: (acp) =>
Effect.gen(function* () {
const probed = yield* probeAntigravityModelOptions(acp);
if (usage) yield* usage.refresh;
if (!probed) return undefined;
const init = yield* acp.getInitializeResult;
const agentVersion = lastAgentTag ?? init?.agentInfo?.version?.trim() ?? undefined;
Expand Down
7 changes: 6 additions & 1 deletion apps/server/src/provider/antigravity/AntigravityTurns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ function acpErrorText(error: unknown): string | undefined {
export function antigravityTurnBehavior<Settings extends AcpProviderSettings>(
profileDir: string,
readUsageLimit?: (model: string) => Effect.Effect<RuntimeUsageLimit | undefined>,
onPromptSettled?: Effect.Effect<void>,
): Pick<AcpProviderDescriptor<Settings>, "turnMachine" | "usageLedger" | "turnUsageTotals"> {
return {
// Turns outlive their prompt (1.5.10 sends what the agent does after a
Expand All @@ -283,7 +284,7 @@ export function antigravityTurnBehavior<Settings extends AcpProviderSettings>(
workAfterPrompt: antigravityWorkAfterPrompt,
steer: ANTIGRAVITY_STEERS,
silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT,
outcome: antigravityPromptOutcome(profileDir, readUsageLimit),
outcome: antigravityPromptOutcome(profileDir, readUsageLimit, onPromptSettled),
},
usageLedger: { provider: "antigravity" },
turnUsageTotals: antigravityTurnUsageTotals,
Expand All @@ -306,6 +307,7 @@ export function antigravityTurnBehavior<Settings extends AcpProviderSettings>(
function antigravityPromptOutcome(
profileDir: string,
readUsageLimit?: (model: string) => Effect.Effect<RuntimeUsageLimit | undefined>,
onPromptSettled?: Effect.Effect<void>,
): AcpPromptOutcome {
return {
watch: (sessionId, model) =>
Expand All @@ -322,6 +324,9 @@ function antigravityPromptOutcome(
: Effect.succeed(failure);
const check: AcpPromptOutcomeWatch["check"] = (answer) =>
Effect.gen(function* () {
// The CLI may have just renewed its OAuth token or consumed quota;
// poke the usage reader off the critical path.
if (onPromptSettled) yield* onPromptSettled.pipe(Effect.ignore);
const nowMs = yield* Clock.currentTimeMillis;
// 1.5.9+ fails the prompt with the real error.
// Words it doesn't recognize keep the core's own reading.
Expand Down
Loading
Loading