From ff08c18023f6ea2a08ff618aec1726a9636a0e75 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 06:44:41 +0000 Subject: [PATCH 01/35] fix(acp-registry): periodic refreshes no longer revert new models to stale session state --- .../AcpRegistryRuntimeCoordinator.test.ts | 50 +++ .../server/AcpRegistryRuntimeCoordinator.ts | 102 +++++- .../src/server/driver.test.ts | 268 +++++++++++++++ .../src/server/driver.ts | 322 +++++++++++++----- .../provider-acp-registry/src/server/probe.ts | 2 + 5 files changed, 642 insertions(+), 102 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index a6662853ae028..0da589ef1ee8b 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -257,4 +257,54 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); + + it.effect( + "tracks live configuration revisions so stale snapshots are neither replayed nor able to clear newer ones", + () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + const configFor = (id: string) => ({ + models: [{ id, name: id, description: null }], + currentModelId: id, + configOptions: [], + modelsFromModelSelect: true, + }); + + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v1")); + const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(first.revision).toBeGreaterThan(0); + + // Watching past the already-observed revision skips the stale replay, then delivers newer updates. + const received: Array = []; + const secondSeen = yield* Deferred.make(); + const watcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration) => + Effect.sync(() => { + received.push(configuration.currentModelId); + }).pipe(Effect.andThen(Deferred.succeed(secondSeen, undefined)), Effect.asVoid), + { afterRevision: first.revision }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); + yield* Deferred.await(secondSeen); + yield* Fiber.interrupt(watcher); + expect(received).toEqual(["model-v2"]); + + // An outdated revision cannot clear a newer live configuration. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, first.revision), + ).toBe(false); + expect(Option.isSome(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + + const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision), + ).toBe(true); + expect(Option.isNone(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), + ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index bec80c06ddd39..7d1d1367bbe3c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -25,6 +25,22 @@ interface AvailableCommandsUpdate { interface LiveConfigurationUpdate { readonly instanceId: ProviderInstanceId; readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +interface LiveConfigurationEntry { + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +interface LiveConfigurationState { + readonly nextRevision: number; + readonly entries: ReadonlyMap; +} + +export interface AcpRegistryLiveConfigurationSnapshot { + readonly configuration: Option.Option; + readonly revision: number; } interface UrlAuthActionUpdate { @@ -67,6 +83,10 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< onUpdate: (commands: AcpRegistryAvailableCommands) => Effect.Effect, ) => Effect.Effect; readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; + readonly clearLiveConfigurationIfRevision: ( + instanceId: ProviderInstanceId, + revision: number, + ) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, @@ -74,9 +94,13 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; + readonly getLiveConfigurationWithRevision: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; readonly watchLiveConfiguration: ( instanceId: ProviderInstanceId, onUpdate: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + options?: { readonly afterRevision?: number }, ) => Effect.Effect; readonly requestUrlAuthentication: ( instanceId: ProviderInstanceId, @@ -103,9 +127,10 @@ const make = Effect.gen(function* () { new Map(), ); const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurationByInstance = yield* Ref.make( - new Map(), - ); + const liveConfigurations = yield* Ref.make({ + nextRevision: 0, + entries: new Map(), + }); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -206,43 +231,82 @@ const make = Effect.gen(function* () { const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = (instanceId) => - Ref.update(liveConfigurationByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; + Ref.update(liveConfigurations, (state) => { + if (!state.entries.has(instanceId)) return state; + const entries = new Map(state.entries); + entries.delete(instanceId); + return { ...state, entries }; + }); + + const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = + (instanceId, revision) => + Ref.modify(liveConfigurations, (state) => { + const current = state.entries.get(instanceId); + if (current === undefined) return [true, state] as const; + if (current.revision !== revision) return [false, state] as const; + const entries = new Map(state.entries); + entries.delete(instanceId); + return [true, { ...state, entries }] as const; }); const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, configuration), - ).pipe( - Effect.andThen( + Ref.modify(liveConfigurations, (state) => { + const revision = state.nextRevision + 1; + const entries = new Map(state.entries); + entries.set(instanceId, { configuration, revision }); + return [revision, { nextRevision: revision, entries }] as const; + }).pipe( + Effect.flatMap((revision) => PubSub.publish(liveConfigurationUpdates, { instanceId, configuration, + revision, }), ), Effect.asVoid, ); + const getLiveConfigurationWithRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationWithRevision"] = + Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfigurationWithRevision")( + function* (instanceId) { + const state = yield* Ref.get(liveConfigurations); + const entry = state.entries.get(instanceId); + return { + configuration: Option.fromNullishOr(entry?.configuration), + revision: entry?.revision ?? state.nextRevision, + }; + }, + ); + const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(liveConfigurationByInstance)).get(instanceId)); + return (yield* getLiveConfigurationWithRevision(instanceId)).configuration; }); const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = - (instanceId, onUpdate) => + (instanceId, onUpdate, options) => Effect.scoped( Effect.gen(function* () { + const afterRevision = options?.afterRevision; const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); - const current = yield* getLiveConfiguration(instanceId); - if (Option.isSome(current)) { - yield* onUpdate(current.value); + const current = (yield* Ref.get(liveConfigurations)).entries.get(instanceId); + let deliveredRevision = afterRevision ?? 0; + if ( + current !== undefined && + (afterRevision === undefined || current.revision > afterRevision) + ) { + deliveredRevision = current.revision; + yield* onUpdate(current.configuration); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.configuration)), + Stream.filter( + (update) => update.instanceId === instanceId && update.revision > deliveredRevision, + ), + Stream.runForEach((update) => { + deliveredRevision = update.revision; + return onUpdate(update.configuration); + }), ); }), ); @@ -344,8 +408,10 @@ const make = Effect.gen(function* () { getAvailableCommands, watchAvailableCommands, clearLiveConfiguration, + clearLiveConfigurationIfRevision, publishLiveConfiguration, getLiveConfiguration, + getLiveConfigurationWithRevision, watchLiveConfiguration, requestUrlAuthentication, acceptUrlAuthentication, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 684eb21d7456b..600aa4ccbdc5c 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -12,6 +12,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -20,11 +21,13 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import { AcpRegistryDriver, + acpRegistryProbeSupersedesLiveCatalog, applyAcpRegistryAvailableCommands, applyAcpRegistryLiveConfiguration, buildCheckedAcpRegistrySnapshot, @@ -862,6 +865,51 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.generation).toBe(5); expect(updated.entry).toBeNull(); }); + + it("lets authoritative fresh probes supersede live catalogs without letting provisional probes regress them", () => { + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 3, + probedModelsFromModelSelect: false, + liveModelCount: 2, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: true, + liveModelCount: 3, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 1, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 3, + }), + ).toBe(false); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 0, + probedModelsFromModelSelect: false, + liveModelCount: 2, + }), + ).toBe(false); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 0, + probedModelsFromModelSelect: false, + liveModelCount: 0, + }), + ).toBe(true); + }); }); describe("acpRegistryAdvertisesModelCatalog", () => { @@ -1189,3 +1237,223 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }), ); }); + +it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { + it.effect( + "picks up new models on a post-TTL refresh instead of reverting to an earlier session's catalog", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-periodic-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.succeed({ + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model"]); + + const learnedEffort = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === + true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + undefined, + { + currentModelId: "old-model", + availableModels: [ + { modelId: "old-model", name: "old-model" }, + { modelId: "other-model", name: "other-model" }, + ], + }, + ), + ); + yield* Fiber.join(learnedEffort); + + // Upstream adds a model and the enrichment cache expires without manual invalidation. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["old-model", "other-model", "new-model"]), + ); + yield* TestClock.adjust("16 minutes"); + + const postTtl = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const updated = Option.getOrThrow(yield* Fiber.join(postTtl)); + expect(updated.models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + expect( + updated.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => option.id), + ).toEqual(["effort"]); + + // Subsequent cached refresh must keep the new catalog instead of reverting to old session state. + const nextCached = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model", "new-model"]); + }), + ); + + it.effect("keeps a live session catalog published while a post-TTL probe is in flight", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-inflight-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const secondProbeEntered = yield* Deferred.make(); + const releaseSecondProbe = yield* Deferred.make(); + const secondProbeClosed = yield* Deferred.make(); + let resolves = 0; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.gen(function* () { + resolves += 1; + if (resolves === 2) { + yield* Effect.addFinalizer(() => + Deferred.succeed(secondProbeClosed, undefined).pipe(Effect.asVoid), + ); + yield* Deferred.succeed(secondProbeEntered, undefined); + yield* Deferred.await(releaseSecondProbe); + } + return { + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }), + ); + + const initial = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["old-model", "other-model", "stale-probe-model"]), + ); + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(secondProbeEntered); + + const liveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.map((m) => m.slug).join() === "entitled-model"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "entitled-model", name: "Entitled", description: null }], + currentModelId: "entitled-model", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(liveApplied); + + yield* Deferred.succeed(releaseSecondProbe, undefined); + yield* Deferred.await(secondProbeClosed); + // Follow-up refresh waits for the semaphore/probe settlement and must preserve the live catalog. + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); + expect( + Option.map( + yield* coordinator.getLiveConfiguration(identity.instanceId), + (config) => config.currentModelId, + ), + ).toEqual(Option.some("entitled-model")); + }), + ); +}); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 46d8ed3219aa4..b784dde0cff72 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -85,6 +85,19 @@ interface AcpRegistryEnrichmentCache { } | null; } +export function acpRegistryProbeSupersedesLiveCatalog(input: { + readonly probedModelCount: number; + readonly probedModelsFromModelSelect: boolean; + readonly liveModelCount: number; +}): boolean { + return ( + input.probedModelCount > 1 || + (input.probedModelCount === 1 && + (input.probedModelsFromModelSelect || input.liveModelCount <= 1)) || + input.liveModelCount === 0 + ); +} + export function isAcpRegistryCacheValid( entry: NonNullable, inspectedVersion: string | null, @@ -153,6 +166,44 @@ const makeUnsupportedTextGeneration = (): ProviderTextGeneration => { }; }; +function mergeLearnedModelOptions( + models: ReadonlyArray, + learned: ReadonlyArray, +): ReadonlyArray { + if (learned.length === 0) return models; + const learnedBySlug = new Map( + learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), + ); + let changed = false; + const merged = models.map((model) => { + if (model.isCustom) return model; + const previousDescriptors = + learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; + if (previousDescriptors.length === 0) return model; + const currentDescriptors = model.capabilities?.optionDescriptors ?? []; + const currentIds = new Set(currentDescriptors.map((descriptor) => descriptor.id)); + const hasAdvertisedReasoning = currentDescriptors.some( + (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", + ); + const extra = previousDescriptors.filter( + (descriptor) => + !currentIds.has(descriptor.id) && + (!hasAdvertisedReasoning || + descriptor.type !== "select" || + descriptor.role !== "reasoning"), + ); + if (extra.length === 0) return model; + changed = true; + return { + ...model, + capabilities: createModelCapabilities({ + optionDescriptors: [...currentDescriptors, ...extra], + }), + }; + }); + return changed ? merged : models; +} + function modelsFromDiscovery( discovery: | Pick< @@ -512,59 +563,97 @@ export function buildCheckedAcpRegistrySnapshot( }); } -export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")( - function* ( - input: SnapshotIdentity & { - readonly settings: AcpRegistrySettings; - readonly cwd: string; - readonly environment: NodeJS.ProcessEnv; - }, - probeConfiguration: AcpRegistryConfigurationProbe, - ): Effect.fn.Return { - const checkedAt = DateTime.formatIso(yield* DateTime.now); - if (!input.settings.enabled) { - return yield* buildInitialAcpRegistrySnapshot(input); - } - const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; - const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); - if (Result.isFailure(inspected)) { - return buildCheckedAcpRegistrySnapshot({ +interface DetailedAcpRegistryProviderStatus { + readonly provider: ServerProvider; + readonly probedModelCount: number; + readonly probedModelsFromModelSelect: boolean; +} + +const checkAcpRegistryProviderStatusDetailed = Effect.fn( + "AcpRegistryDriver.checkProviderStatusDetailed", +)(function* ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + }, + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.fn.Return< + DetailedAcpRegistryProviderStatus, + never, + AcpRegistrySupport.AcpRegistryCatalog | Requirements +> { + const checkedAt = DateTime.formatIso(yield* DateTime.now); + const withoutProbe = (provider: ServerProvider): DetailedAcpRegistryProviderStatus => ({ + provider, + probedModelCount: 0, + probedModelsFromModelSelect: false, + }); + if (!input.settings.enabled) { + return withoutProbe(yield* buildInitialAcpRegistrySnapshot(input)); + } + const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; + const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); + if (Result.isFailure(inspected)) { + return withoutProbe( + buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: { status: "failed", message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`, }, - }); - } - if (inspected.success.status !== "ready") { - return buildCheckedAcpRegistrySnapshot({ + }), + ); + } + if (inspected.success.status !== "ready") { + return withoutProbe( + buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: inspected.success, - }); - } - const probed = yield* Effect.result( - probeConfiguration({ - instanceId: input.instanceId, - settings: input.settings, - cwd: input.cwd, - environment: providerProbeEnvironment(input.environment), }), ); - return Result.isFailure(probed) - ? buildCheckedAcpRegistrySnapshot({ + } + const probed = yield* Effect.result( + probeConfiguration({ + instanceId: input.instanceId, + settings: input.settings, + cwd: input.cwd, + environment: providerProbeEnvironment(input.environment), + }), + ); + return Result.isFailure(probed) + ? withoutProbe( + buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: inspected.success, probeError: probed.failure, - }) - : buildCheckedAcpRegistrySnapshot({ + }), + ) + : { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: inspected.success, probe: probed.success, - }); + }), + probedModelCount: probed.success.probe.models.length, + probedModelsFromModelSelect: probed.success.modelsFromModelSelect === true, + }; +}); + +export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")( + function* ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + }, + probeConfiguration: AcpRegistryConfigurationProbe, + ): Effect.fn.Return { + return (yield* checkAcpRegistryProviderStatusDetailed(input, probeConfiguration)).provider; }, ); @@ -704,8 +793,10 @@ export const AcpRegistryDriver: ProviderDriver { + Effect.tap(({ liveConfiguration }) => + options?.recordLiveRevision === true + ? Ref.set(lastObservedLiveRevision, liveConfiguration.revision) + : Effect.void, + ), + Effect.flatMap(({ commands, liveConfiguration, authAction }) => { const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(configuration, { + return Option.match(liveConfiguration.configuration, { onNone: () => Effect.succeed(withCommands), - onSome: (liveConfiguration) => - applyLiveConfiguration(withCommands, liveConfiguration), + onSome: (configuration) => applyLiveConfiguration(withCommands, configuration), }).pipe( Effect.map((withConfiguration) => applyAcpRegistryUrlAuthAction(withConfiguration, authAction), @@ -749,9 +845,9 @@ export const AcpRegistryDriver: ProviderDriver withLiveRuntimeState(provider, { recordLiveRevision: true })), ); - const enrichProvider = checkAcpRegistryProviderStatus( + const enrichProvider = checkAcpRegistryProviderStatusDetailed( { ...readinessInput, cwd: host.paths.cwd, @@ -791,27 +887,27 @@ export const AcpRegistryDriver: ProviderDriver - current.generation === cacheState.generation - ? { - ...current, - entry: { - provider: enriched, - expiresAt: completedAt + acpRegistryProbeTtlMs(enriched), - }, - } - : current, - ); + if (effectiveConfig.source === "local" && enriched.provider.status === "ready") { + yield* Ref.set(reportedLocalVersion, enriched.provider.version); } - return { provider: enriched, generation: cacheState.generation }; + return { + provider: enriched.provider, + generation: cacheState.generation, + fresh: true, + probeStartLiveRevision, + probedModelCount: enriched.probedModelCount, + probedModelsFromModelSelect: enriched.probedModelsFromModelSelect, + }; }); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< @@ -843,15 +939,68 @@ export const AcpRegistryDriver: ProviderDriver Effect.void, - onSome: ({ provider, generation }) => + onSome: ({ + provider, + generation, + fresh, + probeStartLiveRevision, + probedModelCount, + probedModelsFromModelSelect, + }) => liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, - ), - ), + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + if (current.generation !== generation) return; + let resolved = provider; + if (fresh && provider.status === "ready") { + const liveSnapshot = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( + instanceId, + ) + : { configuration: Option.none(), revision: 0 }; + const previousLiveModels = Option.match(liveSnapshot.configuration, { + onNone: () => 0, + onSome: (configuration) => configuration.models.length, + }); + const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount, + probedModelsFromModelSelect, + liveModelCount: previousLiveModels, + }); + // A fresh non-provisional probe supersedes any live session catalog observed before it started. + const cleared = probeSupersedesLiveCatalog + ? Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + ) + : true + : false; + const models = yield* Ref.modify(learnedModels, (learned) => { + const merged = mergeLearnedModelOptions(provider.models, learned); + return [merged, cleared ? merged : learned] as const; + }); + resolved = models === provider.models ? provider : { ...provider, models }; + const published = yield* withLiveRuntimeState(resolved); + if ( + cleared || + (!probeSupersedesLiveCatalog && + liveSnapshot.revision === probeStartLiveRevision) + ) { + const completedAt = yield* Clock.currentTimeMillis; + yield* Ref.set(enrichmentCache, { + ...current, + entry: { + provider: resolved, + expiresAt: completedAt + acpRegistryProbeTtlMs(published), + }, + }); + } + yield* publishSnapshot(published); + return; + } + yield* withLiveRuntimeState(resolved).pipe(Effect.flatMap(publishSnapshot)); + }), ), }), ), @@ -873,29 +1022,34 @@ export const AcpRegistryDriver: ProviderDriver - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => applyLiveConfiguration(current, configuration)), - Effect.tap(() => - Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => - Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - }), + const publishLiveConfiguration = Ref.get(lastObservedLiveRevision).pipe( + Effect.flatMap((afterRevision) => + runtimeCoordinator.value.watchLiveConfiguration( + instanceId, + (configuration) => + liveSnapshotSemaphore.withPermit( + getSnapshot.pipe( + Effect.flatMap((current) => applyLiveConfiguration(current, configuration)), + Effect.tap(() => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + }), + ), + ), ), ), + Effect.flatMap(publishSnapshot), ), ), - Effect.flatMap(publishSnapshot), - ), + { afterRevision }, ), + ), ); const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( instanceId, diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 03002f914adf5..0d5cc21d9f581 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -386,6 +386,7 @@ export interface AcpRegistryConfigurationProbeResult { readonly probe: AcpRegistryProbeResult; readonly slashCommands: ReadonlyArray; readonly skills: ReadonlyArray; + readonly modelsFromModelSelect?: boolean; } export type AcpRegistryConfigurationProbe = ( @@ -635,6 +636,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: result.commands.slashCommands, skills: result.commands.skills, + modelsFromModelSelect: result.liveConfiguration.modelsFromModelSelect === true, }; }, ); From 576d5c749571abf33b4f286900a200579f4a21ad Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 07:01:51 +0000 Subject: [PATCH 02/35] fix(acp-registry): address review findings on catalog reconciliation and revision delivery --- .../server/AcpRegistryRuntimeCoordinator.ts | 26 ++-- .../src/server/driver.test.ts | 144 +++++++++++++++--- .../src/server/driver.ts | 119 +++++++++++---- 3 files changed, 229 insertions(+), 60 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 7d1d1367bbe3c..016c67a1ae440 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -239,15 +239,18 @@ const make = Effect.gen(function* () { }); const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = - (instanceId, revision) => - Ref.modify(liveConfigurations, (state) => { - const current = state.entries.get(instanceId); - if (current === undefined) return [true, state] as const; - if (current.revision !== revision) return [false, state] as const; - const entries = new Map(state.entries); - entries.delete(instanceId); - return [true, { ...state, entries }] as const; - }); + Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( + function* (instanceId, revision) { + return yield* Ref.modify(liveConfigurations, (state) => { + const current = state.entries.get(instanceId); + if (current === undefined) return [true, state] as const; + if (current.revision !== revision) return [false, state] as const; + const entries = new Map(state.entries); + entries.delete(instanceId); + return [true, { ...state, entries }] as const; + }); + }, + ); const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => @@ -300,10 +303,9 @@ const make = Effect.gen(function* () { yield* onUpdate(current.configuration); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter( - (update) => update.instanceId === instanceId && update.revision > deliveredRevision, - ), + Stream.filter((update) => update.instanceId === instanceId), Stream.runForEach((update) => { + if (update.revision <= deliveredRevision) return Effect.void; deliveredRevision = update.revision; return onUpdate(update.configuration); }), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 600aa4ccbdc5c..77cfb20cecd05 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -872,6 +872,7 @@ describe("acpRegistryEnrichmentCache", () => { probedModelCount: 3, probedModelsFromModelSelect: false, liveModelCount: 2, + liveModelsFromModelSelect: true, }), ).toBe(true); expect( @@ -879,6 +880,15 @@ describe("acpRegistryEnrichmentCache", () => { probedModelCount: 1, probedModelsFromModelSelect: true, liveModelCount: 3, + liveModelsFromModelSelect: true, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: true, + liveModelCount: 1, + liveModelsFromModelSelect: true, }), ).toBe(true); expect( @@ -886,13 +896,23 @@ describe("acpRegistryEnrichmentCache", () => { probedModelCount: 1, probedModelsFromModelSelect: false, liveModelCount: 1, + liveModelsFromModelSelect: false, }), ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 1, + liveModelsFromModelSelect: true, + }), + ).toBe(false); expect( acpRegistryProbeSupersedesLiveCatalog({ probedModelCount: 1, probedModelsFromModelSelect: false, liveModelCount: 3, + liveModelsFromModelSelect: true, }), ).toBe(false); expect( @@ -900,6 +920,7 @@ describe("acpRegistryEnrichmentCache", () => { probedModelCount: 0, probedModelsFromModelSelect: false, liveModelCount: 2, + liveModelsFromModelSelect: true, }), ).toBe(false); expect( @@ -907,6 +928,7 @@ describe("acpRegistryEnrichmentCache", () => { probedModelCount: 0, probedModelsFromModelSelect: false, liveModelCount: 0, + liveModelsFromModelSelect: false, }), ).toBe(true); }); @@ -973,15 +995,36 @@ createInterface({ input: process.stdin }).on("line", (line) => { result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, }); } else if (method === "session/new") { - const modelIds = JSON.parse(readFileSync(process.argv[2], "utf8")); + const rawModels = JSON.parse(readFileSync(process.argv[2], "utf8")); + const availableModels = rawModels.map((entry) => + typeof entry === "string" ? { modelId: entry, name: entry } : entry, + ); + const hasMeta = availableModels.some((entry) => entry._meta !== undefined); send({ id, result: { sessionId: "probe-session", models: { - currentModelId: modelIds[0], - availableModels: modelIds.map((modelId) => ({ modelId, name: modelId })), + currentModelId: availableModels[0]?.modelId, + availableModels, }, + ...(hasMeta + ? { + configOptions: [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + } + : {}), }, }); send({ @@ -1290,19 +1333,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), ).toEqual(["old-model", "other-model"]); - const learnedEffort = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === - true, - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, + const sessionWithEffort = (currentModelId: string) => normalizeAcpRegistryLiveConfiguration( [ { @@ -1319,20 +1350,50 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ], undefined, { - currentModelId: "old-model", + currentModelId, availableModels: [ { modelId: "old-model", name: "old-model" }, { modelId: "other-model", name: "other-model" }, ], }, + ); + const learnedEffort = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === + true && + snapshot.models + .find((model) => model.slug === "other-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === + true, ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithEffort("other-model"), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithEffort("old-model"), ); yield* Fiber.join(learnedEffort); - // Upstream adds a model and the enrichment cache expires without manual invalidation. + // Upstream adds a model and explicitly disables reasoning on other-model; TTL expires without manual invalidation. yield* fileSystem.writeFileString( modelsPath, - JSON.stringify(["old-model", "other-model", "new-model"]), + JSON.stringify([ + "new-model", + "old-model", + { + modelId: "other-model", + name: "other-model", + _meta: { supportsReasoningEffort: false }, + }, + ]), ); yield* TestClock.adjust("16 minutes"); @@ -1342,24 +1403,63 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; const updated = Option.getOrThrow(yield* Fiber.join(postTtl)); expect(updated.models.map((model) => model.slug)).toEqual([ + "new-model", "old-model", "other-model", - "new-model", ]); expect( updated.models .find((model) => model.slug === "old-model") ?.capabilities?.optionDescriptors?.map((option) => option.id), ).toEqual(["effort"]); + expect( + updated.models + .find((model) => model.slug === "other-model") + ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], + ).toEqual([]); - // Subsequent cached refresh must keep the new catalog instead of reverting to old session state. + // Subsequent cached refresh must keep the cached catalog instead of re-probing or reverting to old session state. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["unexpected-reprobe", "other-model"]), + ); const nextCached = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; expect( Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), - ).toEqual(["old-model", "other-model", "new-model"]); + ).toEqual(["new-model", "old-model", "other-model"]); + + // Readiness must keep the last accepted catalog when enrichment is skipped during foreground startup, + // and drop that fallback once caches are invalidated. + const startupEntered = yield* Deferred.make(); + const releaseStartup = yield* Deferred.make(); + const startup = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(startupEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseStartup)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(startupEntered); + + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); + + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "default", + ]); + + yield* Deferred.succeed(releaseStartup, undefined); + yield* Fiber.join(startup); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b784dde0cff72..e42f7282b8e94 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -89,13 +89,15 @@ export function acpRegistryProbeSupersedesLiveCatalog(input: { readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; readonly liveModelCount: number; + readonly liveModelsFromModelSelect: boolean; }): boolean { - return ( - input.probedModelCount > 1 || - (input.probedModelCount === 1 && - (input.probedModelsFromModelSelect || input.liveModelCount <= 1)) || - input.liveModelCount === 0 - ); + if (input.liveModelCount === 0) return true; + if (input.probedModelCount > 1) return true; + if (input.probedModelCount === 1) { + if (input.probedModelsFromModelSelect) return true; + return input.liveModelCount === 1 && !input.liveModelsFromModelSelect; + } + return false; } export function isAcpRegistryCacheValid( @@ -166,9 +168,12 @@ const makeUnsupportedTextGeneration = (): ProviderTextGeneration => { }; }; +const EMPTY_SLUG_SET: ReadonlySet = new Set(); + function mergeLearnedModelOptions( models: ReadonlyArray, learned: ReadonlyArray, + reasoningDisabledModelSlugs: ReadonlySet = EMPTY_SLUG_SET, ): ReadonlyArray { if (learned.length === 0) return models; const learnedBySlug = new Map( @@ -182,13 +187,15 @@ function mergeLearnedModelOptions( if (previousDescriptors.length === 0) return model; const currentDescriptors = model.capabilities?.optionDescriptors ?? []; const currentIds = new Set(currentDescriptors.map((descriptor) => descriptor.id)); - const hasAdvertisedReasoning = currentDescriptors.some( - (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", - ); + const hasExplicitReasoningState = + reasoningDisabledModelSlugs.has(model.slug) || + currentDescriptors.some( + (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", + ); const extra = previousDescriptors.filter( (descriptor) => !currentIds.has(descriptor.id) && - (!hasAdvertisedReasoning || + (!hasExplicitReasoningState || descriptor.type !== "select" || descriptor.role !== "reasoning"), ); @@ -567,6 +574,7 @@ interface DetailedAcpRegistryProviderStatus { readonly provider: ServerProvider; readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; + readonly reasoningDisabledModelSlugs: ReadonlySet; } const checkAcpRegistryProviderStatusDetailed = Effect.fn( @@ -588,6 +596,7 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( provider, probedModelCount: 0, probedModelsFromModelSelect: false, + reasoningDisabledModelSlugs: EMPTY_SLUG_SET, }); if (!input.settings.enabled) { return withoutProbe(yield* buildInitialAcpRegistrySnapshot(input)); @@ -641,6 +650,11 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( }), probedModelCount: probed.success.probe.models.length, probedModelsFromModelSelect: probed.success.modelsFromModelSelect === true, + reasoningDisabledModelSlugs: new Set( + probed.success.probe.models + .filter((model) => model.reasoningEffort === null) + .map((model) => model.id), + ), }; }); @@ -793,10 +807,17 @@ export const AcpRegistryDriver: ProviderDriver>([]); + const clearAcceptedModels = Ref.set(acceptedModels, []); const lastObservedLiveRevision = yield* Ref.make(0); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, - options?: { readonly recordLiveRevision?: boolean }, + options?: { + readonly recordLiveRevision?: boolean; + readonly fallbackToAcceptedModels?: boolean; + }, ) { if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); const provider = @@ -806,8 +827,14 @@ export const AcpRegistryDriver: ProviderDriver + options?.fallbackToAcceptedModels === true && target.enabled && target.installed + ? Ref.get(acceptedModels).pipe( + Effect.map((models) => (models.length > 0 ? { ...target, models } : target)), + ) + : Effect.succeed(target); return yield* Option.isNone(runtimeCoordinator) - ? Effect.succeed(provider) + ? applyAcceptedModelsFallback(provider) : Effect.all({ commands: runtimeCoordinator.value.getAvailableCommands(instanceId), liveConfiguration: @@ -819,17 +846,22 @@ export const AcpRegistryDriver: ProviderDriver { - const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(liveConfiguration.configuration, { - onNone: () => Effect.succeed(withCommands), - onSome: (configuration) => applyLiveConfiguration(withCommands, configuration), - }).pipe( + Effect.flatMap(({ commands, liveConfiguration, authAction }) => + applyAcceptedModelsFallback( + applyAcpRegistryAvailableCommands(provider, commands), + ).pipe( + Effect.flatMap((withBaseModels) => + Option.match(liveConfiguration.configuration, { + onNone: () => Effect.succeed(withBaseModels), + onSome: (configuration) => + applyLiveConfiguration(withBaseModels, configuration), + }), + ), Effect.map((withConfiguration) => applyAcpRegistryUrlAuthAction(withConfiguration, authAction), ), - ); - }), + ), + ), ); }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. @@ -845,7 +877,12 @@ export const AcpRegistryDriver: ProviderDriver withLiveRuntimeState(provider, { recordLiveRevision: true })), + Effect.flatMap((provider) => + withLiveRuntimeState(provider, { + recordLiveRevision: true, + fallbackToAcceptedModels: true, + }), + ), ); const enrichProvider = checkAcpRegistryProviderStatusDetailed( { @@ -891,6 +928,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( Effect.gen(function* () { @@ -962,10 +1002,15 @@ export const AcpRegistryDriver: ProviderDriver 0, onSome: (configuration) => configuration.models.length, }); + const liveModelsFromModelSelect = Option.match(liveSnapshot.configuration, { + onNone: () => false, + onSome: (configuration) => configuration.modelsFromModelSelect === true, + }); const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ probedModelCount, probedModelsFromModelSelect, liveModelCount: previousLiveModels, + liveModelsFromModelSelect, }); // A fresh non-provisional probe supersedes any live session catalog observed before it started. const cleared = probeSupersedesLiveCatalog @@ -977,7 +1022,11 @@ export const AcpRegistryDriver: ProviderDriver { - const merged = mergeLearnedModelOptions(provider.models, learned); + const merged = mergeLearnedModelOptions( + provider.models, + learned, + reasoningDisabledModelSlugs, + ); return [merged, cleared ? merged : learned] as const; }); resolved = models === provider.models ? provider : { ...provider, models }; @@ -996,10 +1045,17 @@ export const AcpRegistryDriver: ProviderDriver applyLiveConfiguration(current, configuration)), + Effect.tap((next) => + next.status === "ready" ? Ref.set(acceptedModels, next.models) : Effect.void, + ), Effect.tap(() => Clock.currentTimeMillis.pipe( Effect.flatMap((now) => @@ -1114,7 +1173,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( invalidateEnrichmentCache.pipe( + Effect.andThen(clearLearnedModels), + Effect.andThen(clearAcceptedModels), Effect.andThen( Option.isSome(runtimeCoordinator) ? Effect.all( From 9c0941edf65645d62977ea08eb77cdcfd303fe53 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 07:20:11 +0000 Subject: [PATCH 03/35] fix(acp-registry): guard accepted catalog against provisional probes and clear under semaphore --- .../src/server/driver.test.ts | 59 +++++++- .../src/server/driver.ts | 132 +++++++++++++----- 2 files changed, 151 insertions(+), 40 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 77cfb20cecd05..922f41c48226f 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -995,8 +995,48 @@ createInterface({ input: process.stdin }).on("line", (line) => { result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, }); } else if (method === "session/new") { - const rawModels = JSON.parse(readFileSync(process.argv[2], "utf8")); - const availableModels = rawModels.map((entry) => + const payload = JSON.parse(readFileSync(process.argv[2], "utf8")); + if (!Array.isArray(payload) && typeof payload.provisional === "string") { + send({ + id, + result: { + sessionId: "probe-session", + models: { + currentModelId: payload.provisional, + availableModels: [{ modelId: payload.provisional, name: payload.provisional }], + }, + configOptions: [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: payload.provisional, + options: [ + { value: payload.provisional, name: payload.provisional }, + { value: "transient-placeholder", name: "transient-placeholder" }, + ], + }, + ], + }, + }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "config_option_update", configOptions: [] }, + }, + }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + return; + } + const availableModels = payload.map((entry) => typeof entry === "string" ? { modelId: entry, name: entry } : entry, ); const hasMeta = availableModels.some((entry) => entry._meta !== undefined); @@ -1431,6 +1471,21 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); + // Once the live entry has been cleared, a later provisional post-TTL probe must not + // regress the settled accepted catalog to a placeholder model. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify({ provisional: "placeholder" }), + ); + yield* TestClock.adjust("16 minutes"); + const afterProvisional = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterProvisional)).models.map((model) => model.slug), + ).toEqual(["new-model", "old-model", "other-model"]); + // Readiness must keep the last accepted catalog when enrichment is skipped during foreground startup, // and drop that fallback once caches are invalidated. const startupEntered = yield* Deferred.make(); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index e42f7282b8e94..a6e4ccf4afdea 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -85,6 +85,18 @@ interface AcpRegistryEnrichmentCache { } | null; } +interface AcceptedAcpRegistryCatalog { + readonly models: ReadonlyArray; + readonly builtInModelCount: number; + readonly modelsFromModelSelect: boolean; +} + +const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { + models: [], + builtInModelCount: 0, + modelsFromModelSelect: false, +}; + export function acpRegistryProbeSupersedesLiveCatalog(input: { readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; @@ -807,10 +819,11 @@ export const AcpRegistryDriver: ProviderDriver>([]); - const clearAcceptedModels = Ref.set(acceptedModels, []); + // Readiness checks do not read enrichmentCache, and post-TTL probes may see no live entry + // once an earlier probe cleared it; keep the last accepted catalog separately so skipped + // enrichment or provisional probes do not regress the snapshot. + const acceptedCatalog = yield* Ref.make(EMPTY_ACCEPTED_CATALOG); + const clearAcceptedCatalog = Ref.set(acceptedCatalog, EMPTY_ACCEPTED_CATALOG); const lastObservedLiveRevision = yield* Ref.make(0); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, @@ -829,8 +842,10 @@ export const AcpRegistryDriver: ProviderDriver options?.fallbackToAcceptedModels === true && target.enabled && target.installed - ? Ref.get(acceptedModels).pipe( - Effect.map((models) => (models.length > 0 ? { ...target, models } : target)), + ? Ref.get(acceptedCatalog).pipe( + Effect.map((accepted) => + accepted.models.length > 0 ? { ...target, models: accepted.models } : target, + ), ) : Effect.succeed(target); return yield* Option.isNone(runtimeCoordinator) @@ -998,19 +1013,22 @@ export const AcpRegistryDriver: ProviderDriver 0, - onSome: (configuration) => configuration.models.length, - }); - const liveModelsFromModelSelect = Option.match(liveSnapshot.configuration, { - onNone: () => false, - onSome: (configuration) => configuration.modelsFromModelSelect === true, + const accepted = yield* Ref.get(acceptedCatalog); + const incumbent = Option.match(liveSnapshot.configuration, { + onNone: () => ({ + modelCount: accepted.builtInModelCount, + modelsFromModelSelect: accepted.modelsFromModelSelect, + }), + onSome: (configuration) => ({ + modelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, + }), }); const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ probedModelCount, probedModelsFromModelSelect, - liveModelCount: previousLiveModels, - liveModelsFromModelSelect, + liveModelCount: incumbent.modelCount, + liveModelsFromModelSelect: incumbent.modelsFromModelSelect, }); // A fresh non-provisional probe supersedes any live session catalog observed before it started. const cleared = probeSupersedesLiveCatalog @@ -1021,15 +1039,23 @@ export const AcpRegistryDriver: ProviderDriver { - const merged = mergeLearnedModelOptions( - provider.models, - learned, - reasoningDisabledModelSlugs, - ); - return [merged, cleared ? merged : learned] as const; - }); - resolved = models === provider.models ? provider : { ...provider, models }; + if ( + !probeSupersedesLiveCatalog && + Option.isNone(liveSnapshot.configuration) && + accepted.models.length > 0 + ) { + resolved = { ...provider, models: accepted.models }; + } else { + const models = yield* Ref.modify(learnedModels, (learned) => { + const merged = mergeLearnedModelOptions( + provider.models, + learned, + reasoningDisabledModelSlugs, + ); + return [merged, cleared ? merged : learned] as const; + }); + resolved = models === provider.models ? provider : { ...provider, models }; + } const published = yield* withLiveRuntimeState(resolved); if ( cleared || @@ -1045,17 +1071,17 @@ export const AcpRegistryDriver: ProviderDriver applyLiveConfiguration(current, configuration)), Effect.tap((next) => - next.status === "ready" ? Ref.set(acceptedModels, next.models) : Effect.void, + next.status === "ready" + ? Ref.update(acceptedCatalog, (previous) => { + const liveUsed = + configuration.models.length > 1 || + (configuration.models.length === 1 && + (configuration.modelsFromModelSelect === true || + previous.builtInModelCount <= 1)); + return liveUsed + ? { + models: next.models, + builtInModelCount: configuration.models.length, + modelsFromModelSelect: + configuration.modelsFromModelSelect === true, + } + : { + ...previous, + models: next.models, + }; + }) + : Effect.void, ), Effect.tap(() => Clock.currentTimeMillis.pipe( @@ -1173,7 +1218,16 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 07:45:50 +0000 Subject: [PATCH 04/35] fix(acp-registry): compare provisional probes against retained catalog and drop cleared watcher callbacks --- .../AcpRegistryRuntimeCoordinator.test.ts | 21 ++- .../server/AcpRegistryRuntimeCoordinator.ts | 36 +++- .../src/server/driver.test.ts | 159 +++++++++++++++++- .../src/server/driver.ts | 117 +++++++------ 4 files changed, 262 insertions(+), 71 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 0da589ef1ee8b..f1cf4a1c10562 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -275,15 +275,15 @@ describe("AcpRegistryRuntimeCoordinator", () => { const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(first.revision).toBeGreaterThan(0); - // Watching past the already-observed revision skips the stale replay, then delivers newer updates. - const received: Array = []; + // Watching past the already-observed revision skips the stale replay, then delivers newer updates with their revision. + const received: Array = []; const secondSeen = yield* Deferred.make(); const watcher = yield* coordinator .watchLiveConfiguration( instanceId, - (configuration) => + (configuration, revision) => Effect.sync(() => { - received.push(configuration.currentModelId); + received.push([configuration.currentModelId, revision] as const); }).pipe(Effect.andThen(Deferred.succeed(secondSeen, undefined)), Effect.asVoid), { afterRevision: first.revision }, ) @@ -292,19 +292,24 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); yield* Deferred.await(secondSeen); yield* Fiber.interrupt(watcher); - expect(received).toEqual(["model-v2"]); + const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(received).toEqual([["model-v2", second.revision]]); - // An outdated revision cannot clear a newer live configuration. + // An outdated revision cannot clear a newer live configuration or advance clearedThroughRevision. expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, first.revision), ).toBe(false); expect(Option.isSome(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, + ).toBe(0); - const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision), ).toBe(true); - expect(Option.isNone(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + const afterClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(Option.isNone(afterClear.configuration)).toBe(true); + expect(afterClear.clearedThroughRevision).toBe(second.revision); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 016c67a1ae440..3615bcc4da896 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -36,11 +36,13 @@ interface LiveConfigurationEntry { interface LiveConfigurationState { readonly nextRevision: number; readonly entries: ReadonlyMap; + readonly clearedThroughRevision: ReadonlyMap; } export interface AcpRegistryLiveConfigurationSnapshot { readonly configuration: Option.Option; readonly revision: number; + readonly clearedThroughRevision: number; } interface UrlAuthActionUpdate { @@ -99,7 +101,10 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< ) => Effect.Effect; readonly watchLiveConfiguration: ( instanceId: ProviderInstanceId, - onUpdate: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + onUpdate: ( + configuration: AcpRegistryLiveConfiguration, + revision: number, + ) => Effect.Effect, options?: { readonly afterRevision?: number }, ) => Effect.Effect; readonly requestUrlAuthentication: ( @@ -130,6 +135,7 @@ const make = Effect.gen(function* () { const liveConfigurations = yield* Ref.make({ nextRevision: 0, entries: new Map(), + clearedThroughRevision: new Map(), }); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( @@ -232,10 +238,14 @@ const make = Effect.gen(function* () { const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = (instanceId) => Ref.update(liveConfigurations, (state) => { - if (!state.entries.has(instanceId)) return state; + const previousCleared = state.clearedThroughRevision.get(instanceId) ?? 0; + const nextCleared = Math.max(previousCleared, state.nextRevision); + if (!state.entries.has(instanceId) && nextCleared === previousCleared) return state; const entries = new Map(state.entries); entries.delete(instanceId); - return { ...state, entries }; + const clearedThroughRevision = new Map(state.clearedThroughRevision); + clearedThroughRevision.set(instanceId, nextCleared); + return { ...state, entries, clearedThroughRevision }; }); const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = @@ -243,11 +253,18 @@ const make = Effect.gen(function* () { function* (instanceId, revision) { return yield* Ref.modify(liveConfigurations, (state) => { const current = state.entries.get(instanceId); - if (current === undefined) return [true, state] as const; - if (current.revision !== revision) return [false, state] as const; + if (current !== undefined && current.revision !== revision) + return [false, state] as const; + const previousCleared = state.clearedThroughRevision.get(instanceId) ?? 0; + const nextCleared = Math.max(previousCleared, revision); + if (current === undefined && nextCleared === previousCleared) { + return [true, state] as const; + } const entries = new Map(state.entries); entries.delete(instanceId); - return [true, { ...state, entries }] as const; + const clearedThroughRevision = new Map(state.clearedThroughRevision); + clearedThroughRevision.set(instanceId, nextCleared); + return [true, { ...state, entries, clearedThroughRevision }] as const; }); }, ); @@ -258,7 +275,7 @@ const make = Effect.gen(function* () { const revision = state.nextRevision + 1; const entries = new Map(state.entries); entries.set(instanceId, { configuration, revision }); - return [revision, { nextRevision: revision, entries }] as const; + return [revision, { ...state, nextRevision: revision, entries }] as const; }).pipe( Effect.flatMap((revision) => PubSub.publish(liveConfigurationUpdates, { @@ -278,6 +295,7 @@ const make = Effect.gen(function* () { return { configuration: Option.fromNullishOr(entry?.configuration), revision: entry?.revision ?? state.nextRevision, + clearedThroughRevision: state.clearedThroughRevision.get(instanceId) ?? 0, }; }, ); @@ -300,14 +318,14 @@ const make = Effect.gen(function* () { (afterRevision === undefined || current.revision > afterRevision) ) { deliveredRevision = current.revision; - yield* onUpdate(current.configuration); + yield* onUpdate(current.configuration, current.revision); } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), Stream.runForEach((update) => { if (update.revision <= deliveredRevision) return Effect.void; deliveredRevision = update.revision; - return onUpdate(update.configuration); + return onUpdate(update.configuration, update.revision); }), ); }), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 922f41c48226f..643340d06cd5a 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1471,8 +1471,14 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); - // Once the live entry has been cleared, a later provisional post-TTL probe must not - // regress the settled accepted catalog to a placeholder model. + // Once the live entry has been cleared, a later provisional post-TTL probe—even after an + // intervening provisional live update—must not regress the settled accepted catalog. + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], + currentModelId: "live-placeholder", + configOptions: [], + modelsFromModelSelect: false, + }); yield* fileSystem.writeFileString( modelsPath, JSON.stringify({ provisional: "placeholder" }), @@ -1611,4 +1617,153 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual(Option.some("entitled-model")); }), ); + + it.effect( + "skips a delayed live-watcher callback after a fresh probe supersedes its revision", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-stale-watcher-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const allowProbe = yield* Deferred.make(); + const staleCallbackEntered = yield* Deferred.make(); + const releaseStaleCallback = yield* Deferred.make(); + const staleCallbackDone = yield* Deferred.make(); + const secondWatcherSubscribed = yield* Deferred.make(); + let postTtlLiveReads = 0; + let armed = false; + let trackNextWatcher = false; + + const gatedCoordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...coordinator, + getLiveConfigurationWithRevision: (instanceId) => + Effect.gen(function* () { + if (armed) { + postTtlLiveReads += 1; + // 1st read is checkProvider; 2nd read is enrichProviderCached capturing probeStartLiveRevision. + if (postTtlLiveReads === 2) { + armed = false; + yield* Deferred.await(allowProbe); + } + } + return yield* coordinator.getLiveConfigurationWithRevision(instanceId); + }), + watchLiveConfiguration: (instanceId, onUpdate, options) => + Effect.gen(function* () { + if (trackNextWatcher) { + trackNextWatcher = false; + yield* Deferred.succeed(secondWatcherSubscribed, undefined); + } + return yield* coordinator.watchLiveConfiguration( + instanceId, + (configuration, revision) => + configuration.currentModelId === "stale-live-model" + ? Deferred.succeed(staleCallbackEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseStaleCallback)), + Effect.andThen(onUpdate(configuration, revision)), + Effect.andThen(Deferred.succeed(staleCallbackDone, undefined)), + Effect.asVoid, + ) + : onUpdate(configuration, revision), + options, + ); + }), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + gatedCoordinator, + ), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.succeed({ + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["old-model", "other-model", "new-model"]), + ); + yield* TestClock.adjust("16 minutes"); + armed = true; + trackNextWatcher = true; + + const probed = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); + yield* instance.snapshot.refresh; + yield* Deferred.await(secondWatcherSubscribed); + + // Publish a live configuration whose watcher callback pauses before acquiring the snapshot semaphore. + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "old-model", name: "old-model", description: null }, + { id: "stale-live-model", name: "stale-live-model", description: null }, + ], + currentModelId: "stale-live-model", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Deferred.await(staleCallbackEntered); + + // Let the fresh probe observe and clear that revision, publishing the newer catalog. + yield* Deferred.succeed(allowProbe, undefined); + expect( + Option.getOrThrow(yield* Fiber.join(probed)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model", "new-model"]); + + // Releasing the delayed watcher callback must not overwrite the snapshot, cache, or accepted catalog. + yield* Deferred.succeed(releaseStaleCallback, undefined); + yield* Deferred.await(staleCallbackDone); + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["unexpected-reprobe", "other-model"]), + ); + const cached = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(cached)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model", "new-model"]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index a6e4ccf4afdea..1db19ddb3c597 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -97,6 +97,17 @@ const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { modelsFromModelSelect: false, }; +function liveConfigurationReplacesAcceptedCatalog( + configuration: AcpRegistryLiveConfiguration, + accepted: AcceptedAcpRegistryCatalog, +): boolean { + return ( + configuration.models.length > 1 || + (configuration.models.length === 1 && + (configuration.modelsFromModelSelect === true || accepted.builtInModelCount <= 1)) + ); +} + export function acpRegistryProbeSupersedesLiveCatalog(input: { readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; @@ -1012,18 +1023,24 @@ export const AcpRegistryDriver: ProviderDriver ({ - modelCount: accepted.builtInModelCount, - modelsFromModelSelect: accepted.modelsFromModelSelect, - }), - onSome: (configuration) => ({ - modelCount: configuration.models.length, - modelsFromModelSelect: configuration.modelsFromModelSelect === true, - }), + const liveCatalogUsed = Option.match(liveSnapshot.configuration, { + onNone: () => false, + onSome: (configuration) => + liveConfigurationReplacesAcceptedCatalog(configuration, accepted), }); + const incumbent = + liveCatalogUsed && Option.isSome(liveSnapshot.configuration) + ? { + modelCount: liveSnapshot.configuration.value.models.length, + modelsFromModelSelect: + liveSnapshot.configuration.value.modelsFromModelSelect === true, + } + : { + modelCount: accepted.builtInModelCount, + modelsFromModelSelect: accepted.modelsFromModelSelect, + }; const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ probedModelCount, probedModelsFromModelSelect, @@ -1041,7 +1058,7 @@ export const AcpRegistryDriver: ProviderDriver 0 ) { resolved = { ...provider, models: accepted.models }; @@ -1108,48 +1125,44 @@ export const AcpRegistryDriver: ProviderDriver runtimeCoordinator.value.watchLiveConfiguration( instanceId, - (configuration) => + (configuration, revision) => liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => applyLiveConfiguration(current, configuration)), - Effect.tap((next) => - next.status === "ready" - ? Ref.update(acceptedCatalog, (previous) => { - const liveUsed = - configuration.models.length > 1 || - (configuration.models.length === 1 && - (configuration.modelsFromModelSelect === true || - previous.builtInModelCount <= 1)); - return liveUsed - ? { - models: next.models, - builtInModelCount: configuration.models.length, - modelsFromModelSelect: - configuration.modelsFromModelSelect === true, - } - : { - ...previous, - models: next.models, - }; - }) - : Effect.void, - ), - Effect.tap(() => - Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => - Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - }), - ), - ), - ), - ), - Effect.flatMap(publishSnapshot), - ), + Effect.gen(function* () { + const currentLive = + yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId); + if ( + Option.isNone(currentLive.configuration) || + revision <= currentLive.clearedThroughRevision + ) { + return; + } + const current = yield* getSnapshot; + const next = yield* applyLiveConfiguration(current, configuration); + if (next.status === "ready") { + yield* Ref.update(acceptedCatalog, (previous) => + liveConfigurationReplacesAcceptedCatalog(configuration, previous) + ? { + models: next.models, + builtInModelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, + } + : { + ...previous, + models: next.models, + }, + ); + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + }), + ); + yield* publishSnapshot(next); + }), ), { afterRevision }, ), From 92ac0edc30eaf04eb6128d0b6c5690347b89c14c Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 08:11:34 +0000 Subject: [PATCH 05/35] fix(acp-registry): preserve explicit singleton catalogs, provisional retry TTL, and accepted models on transient errors --- .../src/server/driver.test.ts | 198 +++++++++++++++++- .../src/server/driver.ts | 101 ++++++--- 2 files changed, 269 insertions(+), 30 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 643340d06cd5a..820efa933b7a6 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -784,6 +784,36 @@ describe("acpRegistrySnapshotReadiness", () => { expect(entitled.models.map((m) => m.slug)).toEqual(["gmodel"]); expect(entitled.models.find((m) => m.slug === "gmodel")?.isDefault).toBe(true); + const afterProvisional = applyAcpRegistryLiveConfiguration( + entitled, + { + models: [{ id: "placeholder", name: "Placeholder", description: null }], + currentModelId: "placeholder", + configOptions: [], + modelsFromModelSelect: false, + }, + [], + entitled.models, + { preserveSingleModelCatalog: true }, + ); + expect(afterProvisional.models.map((m) => m.slug)).toEqual(["gmodel"]); + expect(afterProvisional.models.find((m) => m.slug === "gmodel")?.isDefault).toBe(true); + + const replacedExplicit = applyAcpRegistryLiveConfiguration( + entitled, + { + models: [{ id: "hmodel", name: "Haiku-Only", description: null }], + currentModelId: "hmodel", + configOptions: [], + modelsFromModelSelect: true, + }, + [], + entitled.models, + { preserveSingleModelCatalog: true }, + ); + expect(replacedExplicit.models.map((m) => m.slug)).toEqual(["hmodel"]); + expect(replacedExplicit.models.find((m) => m.slug === "hmodel")?.isDefault).toBe(true); + const narrowed = applyAcpRegistryLiveConfiguration( provider, { @@ -831,6 +861,31 @@ describe("acpRegistryEnrichmentCache", () => { expect(replayed).toBe(cache); expect(replayed.entry?.expiresAt).toBe(1_000); + + const explicitSingletonCache = { + generation: 1, + entry: { + provider: providerWithModels( + [{ id: "gmodel", name: "GPT-Pro", description: null }], + "gmodel", + ), + expiresAt: 1_000, + }, + }; + const provisionalUpdate = updateAcpRegistryEnrichmentCache({ + cache: explicitSingletonCache, + configuration: { + models: [{ id: "placeholder", name: "Placeholder", description: null }], + currentModelId: "placeholder", + configOptions: [], + modelsFromModelSelect: false, + }, + customModels: [], + now: 2_000, + preserveSingleModelCatalog: true, + }); + expect(provisionalUpdate).toBe(explicitSingletonCache); + expect(provisionalUpdate.entry?.provider.models.map((m) => m.slug)).toEqual(["gmodel"]); }); it("updates the cache and promotes the expiry when live configuration discovers a catalog", () => { @@ -1036,6 +1091,13 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); return; } + if (payload && !Array.isArray(payload) && typeof payload.fail === "string") { + send({ + id, + error: { code: payload.code ?? -32603, message: payload.fail }, + }); + return; + } const availableModels = payload.map((entry) => typeof entry === "string" ? { modelId: entry, name: entry } : entry, ); @@ -1492,6 +1554,56 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(afterProvisional)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); + // A provisional probe must still use the short retry TTL even when it retains a multi-model catalog. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), + ); + yield* TestClock.adjust("1 minute"); + const afterProvisionalRetry = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterProvisionalRetry)).models.map( + (model) => model.slug, + ), + ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); + + // A transient discovery failure after TTL expiry must surface warning status without + // dropping the accepted catalog to synthetic default, and must stay uncached for retry. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify({ fail: "Temporary discovery outage" }), + ); + yield* TestClock.adjust("16 minutes"); + const failedProbe = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const warned = Option.getOrThrow(yield* Fiber.join(failedProbe)); + expect(warned.status).toBe("warning"); + expect(warned.models.map((model) => model.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + "settled-model", + ]); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), + ); + const recovered = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(recovered)).models.map((model) => model.slug), + ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); + // Readiness must keep the last accepted catalog when enrichment is skipped during foreground startup, // and drop that fallback once caches are invalidated. const startupEntered = yield* Deferred.make(); @@ -1511,6 +1623,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "new-model", "old-model", "other-model", + "settled-model", ]); yield* instance.invalidateCaches ?? Effect.void; @@ -1615,6 +1728,55 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (config) => config.currentModelId, ), ).toEqual(Option.some("entitled-model")); + + // A subsequent provisional single-model live update must not replace the explicit singleton + // catalog or downgrade its provenance. + const provisionalProcessed = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "entitled-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], + currentModelId: "live-placeholder", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelsFromModelSelect: false, + }); + expect( + Option.getOrThrow(yield* Fiber.join(provisionalProcessed)).models.map( + (model) => model.slug, + ), + ).toEqual(["entitled-model"]); + + yield* fileSystem.writeFileString(modelsPath, JSON.stringify({ provisional: "placeholder" })); + yield* TestClock.adjust("16 minutes"); + const afterProvisionalProbe = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterProvisionalProbe)).models.map( + (model) => model.slug, + ), + ).toEqual(["entitled-model"]); }), ); @@ -1636,6 +1798,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const staleCallbackEntered = yield* Deferred.make(); const releaseStaleCallback = yield* Deferred.make(); const staleCallbackDone = yield* Deferred.make(); + const newerCallbackEntered = yield* Deferred.make(); + const releaseNewerCallback = yield* Deferred.make(); + const newerCallbackDone = yield* Deferred.make(); const secondWatcherSubscribed = yield* Deferred.make(); let postTtlLiveReads = 0; let armed = false; @@ -1672,7 +1837,14 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.andThen(Deferred.succeed(staleCallbackDone, undefined)), Effect.asVoid, ) - : onUpdate(configuration, revision), + : configuration.currentModelId === "newer-live-model" + ? Deferred.succeed(newerCallbackEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseNewerCallback)), + Effect.andThen(onUpdate(configuration, revision)), + Effect.andThen(Deferred.succeed(newerCallbackDone, undefined)), + Effect.asVoid, + ) + : onUpdate(configuration, revision), options, ); }), @@ -1746,6 +1918,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(probed)).models.map((model) => model.slug), ).toEqual(["old-model", "other-model", "new-model"]); + // Publish a newer live revision while the stale callback is still paused so currentLive is + // Option.some(newer) when the stale callback resumes, specifically exercising the + // clearedThroughRevision watermark. + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "old-model", name: "old-model", description: null }, + { id: "newer-live-model", name: "newer-live-model", description: null }, + ], + currentModelId: "newer-live-model", + configOptions: [], + modelsFromModelSelect: true, + }); + // Releasing the delayed watcher callback must not overwrite the snapshot, cache, or accepted catalog. yield* Deferred.succeed(releaseStaleCallback, undefined); yield* Deferred.await(staleCallbackDone); @@ -1755,6 +1940,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "new-model", ]); + // The newer live revision queued behind it must still be applied. + yield* Deferred.await(newerCallbackEntered); + yield* Deferred.succeed(releaseNewerCallback, undefined); + yield* Deferred.await(newerCallbackDone); + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "old-model", + "newer-live-model", + ]); + yield* fileSystem.writeFileString( modelsPath, JSON.stringify(["unexpected-reprobe", "other-model"]), @@ -1763,7 +1957,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; expect( Option.getOrThrow(yield* Fiber.join(cached)).models.map((model) => model.slug), - ).toEqual(["old-model", "other-model", "new-model"]); + ).toEqual(["old-model", "newer-live-model"]); }), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 1db19ddb3c597..8ec1d10cdd095 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -104,7 +104,8 @@ function liveConfigurationReplacesAcceptedCatalog( return ( configuration.models.length > 1 || (configuration.models.length === 1 && - (configuration.modelsFromModelSelect === true || accepted.builtInModelCount <= 1)) + (configuration.modelsFromModelSelect === true || + (accepted.builtInModelCount <= 1 && !accepted.modelsFromModelSelect))) ); } @@ -140,8 +141,9 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly configuration: AcpRegistryLiveConfiguration; readonly customModels: ReadonlyArray; readonly now: number; + readonly preserveSingleModelCatalog?: boolean; }): AcpRegistryEnrichmentCache { - const { cache, configuration, customModels, now } = input; + const { cache, configuration, customModels, now, preserveSingleModelCatalog } = input; if (cache.entry === null) { // No probe has landed yet, but the live session published its // configuration to the snapshot. Advance the cache epoch so a probe that @@ -152,6 +154,8 @@ export function updateAcpRegistryEnrichmentCache(input: { cache.entry.provider, configuration, customModels, + cache.entry.provider.models, + preserveSingleModelCatalog === undefined ? undefined : { preserveSingleModelCatalog }, ); if (Equal.equals(provider, cache.entry.provider)) return cache; return { @@ -435,19 +439,19 @@ export function applyAcpRegistryLiveConfiguration( configuration: AcpRegistryLiveConfiguration, customModels: ReadonlyArray, previousModels: ReadonlyArray = provider.models, + options?: { readonly preserveSingleModelCatalog?: boolean }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; // session/load may omit models (Kimi returns `{}`); keep the probed list // and apply any live option descriptors to it. const probedModels = provider.models.filter((model) => !model.isCustom); // A cold-start session can report one placeholder model before its catalog - // settles, while the probe may already have observed the full catalog. A - // single model enumerated by an explicit select is not that fallback but - // the agent's deliberate statement, so it wins over the probe catalog. + // settles, whereas an explicit single-model select is deliberate and wins. const liveCatalogIsProvisional = configuration.models.length === 1 && !configuration.modelsFromModelSelect && - probedModels.length > 1; + (probedModels.length > 1 || + (options?.preserveSingleModelCatalog === true && probedModels.length === 1)); const useLiveCatalog = configuration.models.length > 1 || (configuration.models.length === 1 && !liveCatalogIsProvisional); @@ -816,31 +820,45 @@ export const AcpRegistryDriver: ProviderDriver>([]); - const applyLiveConfiguration = ( - provider: ServerProvider, - configuration: AcpRegistryLiveConfiguration, - ) => - Ref.modify(learnedModels, (learned) => { - const next = applyAcpRegistryLiveConfiguration( - provider, - configuration, - effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - ); - return [next, next.models === provider.models ? learned : next.models]; - }); const clearLearnedModels = Ref.set(learnedModels, []); // Readiness checks do not read enrichmentCache, and post-TTL probes may see no live entry // once an earlier probe cleared it; keep the last accepted catalog separately so skipped // enrichment or provisional probes do not regress the snapshot. const acceptedCatalog = yield* Ref.make(EMPTY_ACCEPTED_CATALOG); const clearAcceptedCatalog = Ref.set(acceptedCatalog, EMPTY_ACCEPTED_CATALOG); + const applyLiveConfiguration = ( + provider: ServerProvider, + configuration: AcpRegistryLiveConfiguration, + options?: { readonly preserveSingleModelCatalog?: boolean }, + ) => + (options?.preserveSingleModelCatalog !== undefined + ? Effect.succeed(options.preserveSingleModelCatalog) + : Ref.get(acceptedCatalog).pipe( + Effect.map( + (accepted) => accepted.builtInModelCount === 1 && accepted.modelsFromModelSelect, + ), + ) + ).pipe( + Effect.flatMap((preserveSingleModelCatalog) => + Ref.modify(learnedModels, (learned) => { + const next = applyAcpRegistryLiveConfiguration( + provider, + configuration, + effectiveConfig.customModels, + learned.length > 0 ? learned : provider.models, + { preserveSingleModelCatalog }, + ); + return [next, next.models === provider.models ? learned : next.models]; + }), + ), + ); const lastObservedLiveRevision = yield* Ref.make(0); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, options?: { readonly recordLiveRevision?: boolean; readonly fallbackToAcceptedModels?: boolean; + readonly preserveSingleModelCatalog?: boolean; }, ) { if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); @@ -880,7 +898,13 @@ export const AcpRegistryDriver: ProviderDriver Effect.succeed(withBaseModels), onSome: (configuration) => - applyLiveConfiguration(withBaseModels, configuration), + applyLiveConfiguration( + withBaseModels, + configuration, + options?.preserveSingleModelCatalog === undefined + ? undefined + : { preserveSingleModelCatalog: options.preserveSingleModelCatalog }, + ), }), ), Effect.map((withConfiguration) => @@ -1073,7 +1097,14 @@ export const AcpRegistryDriver: ProviderDriver liveConfigurationReplacesAcceptedCatalog(configuration, previous) @@ -1146,10 +1188,12 @@ export const AcpRegistryDriver: ProviderDriver 0 + ? { + ...previous, + models: next.models, + } + : previous, ); } const now = yield* Clock.currentTimeMillis; @@ -1159,6 +1203,7 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 08:27:16 +0000 Subject: [PATCH 06/35] fix(acp-registry): keep provisional model-specific options off retained models --- .../src/server/driver.test.ts | 101 +++++++++++++++--- .../src/server/driver.ts | 46 +++++--- 2 files changed, 123 insertions(+), 24 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 820efa933b7a6..095df149cfafa 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -771,12 +771,41 @@ describe("acpRegistrySnapshotReadiness", () => { "auto", ); + const entitledEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; + const placeholderEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + currentValue: "on", + options: [ + { id: "off", label: "Off" }, + { id: "on", label: "On" }, + ], + }; + const sharedMode = { + id: "mode", + label: "Mode", + type: "select" as const, + currentValue: "code", + options: [{ id: "code", label: "Code" }], + }; + const entitled = applyAcpRegistryLiveConfiguration( provider, { models: [{ id: "gmodel", name: "GPT-Pro", description: null }], currentModelId: "gmodel", - configOptions: [], + configOptions: [entitledEffort], + modelOptionIds: ["effort"], modelsFromModelSelect: true, }, [], @@ -789,7 +818,8 @@ describe("acpRegistrySnapshotReadiness", () => { { models: [{ id: "placeholder", name: "Placeholder", description: null }], currentModelId: "placeholder", - configOptions: [], + configOptions: [placeholderEffort, sharedMode], + modelOptionIds: ["effort"], modelsFromModelSelect: false, }, [], @@ -798,6 +828,24 @@ describe("acpRegistrySnapshotReadiness", () => { ); expect(afterProvisional.models.map((m) => m.slug)).toEqual(["gmodel"]); expect(afterProvisional.models.find((m) => m.slug === "gmodel")?.isDefault).toBe(true); + expect( + afterProvisional.models.find((m) => m.slug === "gmodel")?.capabilities?.optionDescriptors, + ).toEqual([sharedMode, entitledEffort]); + + const afterProvisionalModelOnly = applyAcpRegistryLiveConfiguration( + entitled, + { + models: [{ id: "placeholder", name: "Placeholder", description: null }], + currentModelId: "placeholder", + configOptions: [placeholderEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + entitled.models, + { preserveSingleModelCatalog: true }, + ); + expect(afterProvisionalModelOnly.models).toBe(entitled.models); const replacedExplicit = applyAcpRegistryLiveConfiguration( entitled, @@ -1710,7 +1758,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [{ id: "entitled-model", name: "Entitled", description: null }], currentModelId: "entitled-model", - configOptions: [], + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], modelsFromModelSelect: true, }); yield* Fiber.join(liveApplied); @@ -1730,13 +1790,13 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual(Option.some("entitled-model")); // A subsequent provisional single-model live update must not replace the explicit singleton - // catalog or downgrade its provenance. + // catalog, overwrite its model-specific options, or downgrade its provenance. const provisionalProcessed = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.models .find((model) => model.slug === "entitled-model") - ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === true, + ?.capabilities?.optionDescriptors?.some((option) => option.id === "mode") === true, ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), @@ -1745,24 +1805,41 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], currentModelId: "live-placeholder", configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "code", + options: [{ id: "code", label: "Code" }], + }, { id: "effort", label: "Effort", type: "select", - currentValue: "high", + currentValue: "on", options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, + { id: "off", label: "Off" }, + { id: "on", label: "On" }, ], }, ], + modelOptionIds: ["effort"], modelsFromModelSelect: false, }); + const retainedAfterProvisional = Option.getOrThrow(yield* Fiber.join(provisionalProcessed)); + expect(retainedAfterProvisional.models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); expect( - Option.getOrThrow(yield* Fiber.join(provisionalProcessed)).models.map( - (model) => model.slug, - ), - ).toEqual(["entitled-model"]); + retainedAfterProvisional.models + .find((model) => model.slug === "entitled-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort"), + ).toMatchObject({ + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); yield* fileSystem.writeFileString(modelsPath, JSON.stringify({ provisional: "placeholder" })); yield* TestClock.adjust("16 minutes"); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 8ec1d10cdd095..15d3e0bfd1099 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -455,11 +455,26 @@ export function applyAcpRegistryLiveConfiguration( const useLiveCatalog = configuration.models.length > 1 || (configuration.models.length === 1 && !liveCatalogIsProvisional); - const selectedProbedModelId = + const liveCurrentModelInProbed = configuration.currentModelId !== null && - probedModels.some((model) => model.slug === configuration.currentModelId) - ? configuration.currentModelId - : (probedModels.find((model) => model.isDefault)?.slug ?? null); + probedModels.some((model) => model.slug === configuration.currentModelId); + const selectedProbedModelId = liveCurrentModelInProbed + ? configuration.currentModelId + : (probedModels.find((model) => model.isDefault)?.slug ?? null); + // When retaining the probed catalog for a live session running an absent + // model (e.g. a cold-start placeholder), keep only shared options and leave + // each retained model's own learned options untouched. + const dropUnmatchedModelOptions = + !useLiveCatalog && configuration.currentModelId !== null && !liveCurrentModelInProbed; + const unmatchedModelOptionIds = dropUnmatchedModelOptions + ? new Set(configuration.modelOptionIds ?? []) + : EMPTY_SLUG_SET; + const effectiveConfigOptions = + unmatchedModelOptionIds.size === 0 + ? configuration.configOptions + : configuration.configOptions.filter( + (descriptor) => !unmatchedModelOptionIds.has(descriptor.id), + ); const discovery = useLiveCatalog ? configuration : { @@ -469,19 +484,26 @@ export function applyAcpRegistryLiveConfiguration( name: model.name, description: null, })), - currentModelId: selectedProbedModelId, + currentModelId: dropUnmatchedModelOptions + ? configuration.currentModelId + : selectedProbedModelId, + configOptions: effectiveConfigOptions, }; + const nextModels = + !useLiveCatalog && effectiveConfigOptions.length === 0 + ? withAcpRegistryDefaultModel(provider.models, selectedProbedModelId) + : modelsFromDiscovery( + discovery, + customModels, + previousModels.filter((model) => !model.isCustom), + ); return { ...snapshot, status: provider.enabled ? "ready" : provider.status, models: - !useLiveCatalog && configuration.configOptions.length === 0 - ? withAcpRegistryDefaultModel(provider.models, selectedProbedModelId) - : modelsFromDiscovery( - discovery, - customModels, - previousModels.filter((model) => !model.isCustom), - ), + dropUnmatchedModelOptions && effectiveConfigOptions.length > 0 + ? withAcpRegistryDefaultModel(nextModels, selectedProbedModelId) + : nextModels, }; } From 7bfb9b05f0057f7c1ee0b4e47f94297f8603fc2a Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 09:07:10 +0000 Subject: [PATCH 07/35] fix(acp-registry): fix signed-out catalog flips, long-lived session replays, learned option leaks, and commit atomicity --- .../Adapters/AcpAdapterV2.test.ts | 29 +- .../AcpRegistryRuntimeCoordinator.test.ts | 5 + .../server/AcpRegistryRuntimeCoordinator.ts | 102 ++-- .../src/server/adapter.ts | 9 +- .../src/server/driver.test.ts | 292 +++++++++- .../src/server/driver.ts | 543 +++++++++++------- .../provider-acp-registry/src/server/probe.ts | 10 +- packages/provider-acp/src/server/adapter.ts | 64 ++- 8 files changed, 753 insertions(+), 301 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 348c2f38b0190..9cb489ba59548 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5153,7 +5153,10 @@ describe("AcpAdapterV2", () => { const protocolEvents = yield* Queue.unbounded(); const adoptionHandled = yield* Deferred.make(); const adopted = yield* Deferred.make(); - const publishedConfigurations: Array> = []; + const publishedConfigurations: Array<{ + readonly configOptions: ReadonlyArray; + readonly includeCatalog: boolean | undefined; + }> = []; let publications = 0; let acpRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] | undefined; const instanceId = ProviderInstanceId.make("acp-test-late-session-load-selection"); @@ -5169,9 +5172,16 @@ describe("AcpAdapterV2", () => { : Effect.void, // Holds openSession's own publication until the adapter has seen the // late response, so adoption overlaps session configuration. - onSessionConfigurationUpdate: (configOptions) => + onSessionConfigurationUpdate: (configOptions, _modeState, _modelState, updateOptions) => (publications++ === 0 ? Deferred.await(adoptionHandled) : Effect.void).pipe( - Effect.andThen(Effect.sync(() => publishedConfigurations.push(configOptions))), + Effect.andThen( + Effect.sync(() => + publishedConfigurations.push({ + configOptions, + includeCatalog: updateOptions?.includeCatalog, + }), + ), + ), Effect.andThen( configOptions.some((option) => option.category === "model") ? Deferred.succeed(adopted, undefined) @@ -5241,9 +5251,20 @@ describe("AcpAdapterV2", () => { "the selected model was only applied to the provisional setup, which offered no model", ); assert.isTrue( - publishedConfigurations.at(-1)?.some((option) => option.category === "model"), + publishedConfigurations.at(-1)?.configOptions.some((option) => option.category === "model"), "the provisional catalog was published over the late session/load one", ); + const modelPublications = publishedConfigurations.filter((entry) => + entry.configOptions.some((option) => option.category === "model"), + ); + assert.isTrue( + modelPublications[0]?.includeCatalog, + "adoption must publish the newly observed session catalog", + ); + assert.isFalse( + modelPublications.at(-1)?.includeCatalog, + "subsequent turn reconfiguration with an unchanged catalog must not re-advertise it", + ); }).pipe(Effect.provide(layerTest), Effect.scoped), ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index f1cf4a1c10562..8b47db692c5f6 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -310,6 +310,11 @@ describe("AcpRegistryRuntimeCoordinator", () => { const afterClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(Option.isNone(afterClear.configuration)).toBe(true); expect(afterClear.clearedThroughRevision).toBe(second.revision); + + // Publications on another instance must not advance this instance's revision or watermark. + const otherInstanceId = ProviderInstanceId.make("acpRegistry_kimi"); + yield* coordinator.publishLiveConfiguration(otherInstanceId, configFor("kimi-v1")); + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual(afterClear); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 3615bcc4da896..363d228ade4d6 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -28,23 +28,18 @@ interface LiveConfigurationUpdate { readonly revision: number; } -interface LiveConfigurationEntry { - readonly configuration: AcpRegistryLiveConfiguration; - readonly revision: number; -} - -interface LiveConfigurationState { - readonly nextRevision: number; - readonly entries: ReadonlyMap; - readonly clearedThroughRevision: ReadonlyMap; -} - export interface AcpRegistryLiveConfigurationSnapshot { readonly configuration: Option.Option; readonly revision: number; readonly clearedThroughRevision: number; } +const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { + configuration: Option.none(), + revision: 0, + clearedThroughRevision: 0, +}; + interface UrlAuthActionUpdate { readonly instanceId: ProviderInstanceId; readonly action: AcpRegistryUrlAuthAction | null; @@ -132,11 +127,9 @@ const make = Effect.gen(function* () { new Map(), ); const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurations = yield* Ref.make({ - nextRevision: 0, - entries: new Map(), - clearedThroughRevision: new Map(), - }); + const liveConfigurations = yield* Ref.make< + ReadonlyMap + >(new Map()); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -238,33 +231,46 @@ const make = Effect.gen(function* () { const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = (instanceId) => Ref.update(liveConfigurations, (state) => { - const previousCleared = state.clearedThroughRevision.get(instanceId) ?? 0; - const nextCleared = Math.max(previousCleared, state.nextRevision); - if (!state.entries.has(instanceId) && nextCleared === previousCleared) return state; - const entries = new Map(state.entries); - entries.delete(instanceId); - const clearedThroughRevision = new Map(state.clearedThroughRevision); - clearedThroughRevision.set(instanceId, nextCleared); - return { ...state, entries, clearedThroughRevision }; + const current = state.get(instanceId); + if (current === undefined) return state; + const nextCleared = Math.max(current.clearedThroughRevision, current.revision); + if ( + Option.isNone(current.configuration) && + nextCleared === current.clearedThroughRevision + ) { + return state; + } + const next = new Map(state); + next.set(instanceId, { + configuration: Option.none(), + revision: current.revision, + clearedThroughRevision: nextCleared, + }); + return next; }); const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( function* (instanceId, revision) { return yield* Ref.modify(liveConfigurations, (state) => { - const current = state.entries.get(instanceId); - if (current !== undefined && current.revision !== revision) + const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + if (Option.isSome(current.configuration) && current.revision !== revision) { return [false, state] as const; - const previousCleared = state.clearedThroughRevision.get(instanceId) ?? 0; - const nextCleared = Math.max(previousCleared, revision); - if (current === undefined && nextCleared === previousCleared) { + } + const nextCleared = Math.max(current.clearedThroughRevision, revision); + if ( + Option.isNone(current.configuration) && + nextCleared === current.clearedThroughRevision + ) { return [true, state] as const; } - const entries = new Map(state.entries); - entries.delete(instanceId); - const clearedThroughRevision = new Map(state.clearedThroughRevision); - clearedThroughRevision.set(instanceId, nextCleared); - return [true, { ...state, entries, clearedThroughRevision }] as const; + const next = new Map(state); + next.set(instanceId, { + configuration: Option.none(), + revision: Math.max(current.revision, revision), + clearedThroughRevision: nextCleared, + }); + return [true, next] as const; }); }, ); @@ -272,10 +278,15 @@ const make = Effect.gen(function* () { const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => Ref.modify(liveConfigurations, (state) => { - const revision = state.nextRevision + 1; - const entries = new Map(state.entries); - entries.set(instanceId, { configuration, revision }); - return [revision, { ...state, nextRevision: revision, entries }] as const; + const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + const revision = current.revision + 1; + const next = new Map(state); + next.set(instanceId, { + configuration: Option.some(configuration), + revision, + clearedThroughRevision: current.clearedThroughRevision, + }); + return [revision, next] as const; }).pipe( Effect.flatMap((revision) => PubSub.publish(liveConfigurationUpdates, { @@ -290,13 +301,9 @@ const make = Effect.gen(function* () { const getLiveConfigurationWithRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationWithRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfigurationWithRevision")( function* (instanceId) { - const state = yield* Ref.get(liveConfigurations); - const entry = state.entries.get(instanceId); - return { - configuration: Option.fromNullishOr(entry?.configuration), - revision: entry?.revision ?? state.nextRevision, - clearedThroughRevision: state.clearedThroughRevision.get(instanceId) ?? 0, - }; + return ( + (yield* Ref.get(liveConfigurations)).get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT + ); }, ); @@ -311,14 +318,15 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const afterRevision = options?.afterRevision; const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); - const current = (yield* Ref.get(liveConfigurations)).entries.get(instanceId); + const current = (yield* Ref.get(liveConfigurations)).get(instanceId); let deliveredRevision = afterRevision ?? 0; if ( current !== undefined && + Option.isSome(current.configuration) && (afterRevision === undefined || current.revision > afterRevision) ) { deliveredRevision = current.revision; - yield* onUpdate(current.configuration, current.revision); + yield* onUpdate(current.configuration.value, current.revision); } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..95a327b272f5d 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -374,10 +374,15 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), - onSessionConfigurationUpdate: (configOptions, modeState, modelState) => + onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => runtimeCoordinator.publishLiveConfiguration( options.instanceId, - normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState), + normalizeAcpRegistryLiveConfiguration( + configOptions, + modeState, + modelState, + updateOptions, + ), ), onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 095df149cfafa..695c30338ffa2 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -934,6 +934,45 @@ describe("acpRegistryEnrichmentCache", () => { }); expect(provisionalUpdate).toBe(explicitSingletonCache); expect(provisionalUpdate.entry?.provider.models.map((m) => m.slug)).toEqual(["gmodel"]); + + const optionsOnly = normalizeAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + ], + undefined, + { + currentModelId: "auto", + availableModels: [ + { modelId: "auto", name: "Auto" }, + { modelId: "qmodel", name: "Qwen" }, + ], + }, + { includeCatalog: false }, + ); + expect(optionsOnly.models).toEqual([]); + expect(optionsOnly.currentModelId).toBe("auto"); + expect(optionsOnly.modelsFromModelSelect).toBe(false); + expect(optionsOnly.modelOptionIds).toEqual(["effort"]); + const afterOptionsOnly = updateAcpRegistryEnrichmentCache({ + cache, + configuration: optionsOnly, + customModels: [], + now: 2_000, + }); + expect(afterOptionsOnly.generation).toBe(1); + expect(afterOptionsOnly.entry?.expiresAt).toBe(1_000); + expect( + afterOptionsOnly.entry?.provider.models + .find((m) => m.slug === "auto") + ?.capabilities?.optionDescriptors?.map((option) => option.id), + ).toEqual(["effort"]); }); it("updates the cache and promotes the expiry when live configuration discovers a catalog", () => { @@ -955,9 +994,23 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.generation).toBe(2); }); - it("advances the cache epoch when a live update arrives before any probe lands", () => { + it("advances the cache epoch when a live catalog arrives before any probe lands", () => { const cache = { generation: 4, entry: null }; + expect( + updateAcpRegistryEnrichmentCache({ + cache, + configuration: { + models: [], + currentModelId: "auto", + configOptions: [], + modelsFromModelSelect: false, + }, + customModels: [], + now: 5_000, + }), + ).toBe(cache); + const updated = updateAcpRegistryEnrichmentCache({ cache, configuration: settledConfiguration, @@ -1483,7 +1536,11 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), ).toEqual(["old-model", "other-model"]); - const sessionWithEffort = (currentModelId: string) => + const sessionWithOptions = ( + currentModelId: string, + effortValue: "low" | "high" = "high", + options?: { readonly includeCatalog?: boolean; readonly includeLegacy?: boolean }, + ) => normalizeAcpRegistryLiveConfiguration( [ { @@ -1491,12 +1548,24 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { name: "Effort", category: "thought_level", type: "select", - currentValue: "high", + currentValue: effortValue, options: [ { value: "low", name: "Low" }, { value: "high", name: "High" }, ], }, + ...(options?.includeLegacy === true + ? [ + { + id: "legacy", + name: "Legacy", + category: "other" as const, + type: "select" as const, + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ] + : []), ], undefined, { @@ -1506,6 +1575,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { { modelId: "other-model", name: "other-model" }, ], }, + options?.includeCatalog === undefined + ? undefined + : { includeCatalog: options.includeCatalog }, ); const learnedEffort = yield* instance.snapshot.streamChanges.pipe( Stream.filter( @@ -1524,15 +1596,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - sessionWithEffort("other-model"), + sessionWithOptions("other-model", "high", { includeLegacy: true }), ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - sessionWithEffort("old-model"), + sessionWithOptions("old-model", "high", { includeLegacy: true }), ); yield* Fiber.join(learnedEffort); - // Upstream adds a model and explicitly disables reasoning on other-model; TTL expires without manual invalidation. + // Upstream adds a model, removes the shared legacy option, and disables reasoning on other-model. yield* fileSystem.writeFileString( modelsPath, JSON.stringify([ @@ -1567,6 +1639,32 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((model) => model.slug === "other-model") ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], ).toEqual([]); + expect( + updated.models + .find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], + ).toEqual(["effort"]); + + // A mid-session option update from a long-lived session (includeCatalog: false) must keep + // the newly probed models intact while updating the active model's learned options. + const effortUpdated = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithOptions("old-model", "low", { includeCatalog: false }), + ); + expect( + Option.getOrThrow(yield* Fiber.join(effortUpdated)).models.map((model) => model.slug), + ).toEqual(["new-model", "old-model", "other-model"]); // Subsequent cached refresh must keep the cached catalog instead of re-probing or reverting to old session state. yield* fileSystem.writeFileString( @@ -1581,6 +1679,80 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); + // When a later post-TTL probe runs directly on old-model without effort, learned effort is dropped. + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "new-model"])); + yield* TestClock.adjust("16 minutes"); + const droppedOnCurrent = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const currentObserved = Option.getOrThrow(yield* Fiber.join(droppedOnCurrent)); + expect(currentObserved.models.map((model) => model.slug)).toEqual([ + "old-model", + "new-model", + ]); + expect( + currentObserved.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], + ).toEqual([]); + }), + ); + + it.effect( + "retains accepted models across provisional probes, transient errors, and foreground startup, and drops them on sign-out or invalidation", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-retention-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["new-model", "old-model", "other-model"]), + ); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.succeed({ + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), + ).toEqual(["new-model", "old-model", "other-model"]); + // Once the live entry has been cleared, a later provisional post-TTL probe—even after an // intervening provisional live update—must not regress the settled accepted catalog. yield* coordinator.publishLiveConfiguration(identity.instanceId, { @@ -1652,8 +1824,22 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(recovered)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); - // Readiness must keep the last accepted catalog when enrichment is skipped during foreground startup, - // and drop that fallback once caches are invalidated. + // An unauthenticated post-TTL probe must clear accepted models so subsequent readiness + // refreshes do not flip between the signed-in catalog and default. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify({ fail: "Sign in required", code: -32000 }), + ); + yield* TestClock.adjust("16 minutes"); + const signedOutProbe = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const signedOut = Option.getOrThrow(yield* Fiber.join(signedOutProbe)); + expect(signedOut.models.map((model) => model.slug)).toEqual(["default"]); + const startupEntered = yield* Deferred.make(); const releaseStartup = yield* Deferred.make(); const startup = yield* coordinator @@ -1666,6 +1852,36 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(startupEntered); + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "default", + ]); + yield* Deferred.succeed(releaseStartup, undefined); + yield* Fiber.join(startup); + + // Re-populate the catalog, then verify foreground startup keeps it and invalidation clears it. + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), + ); + const restored = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(restored); + + const startupEntered2 = yield* Deferred.make(); + const releaseStartup2 = yield* Deferred.make(); + const startup2 = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(startupEntered2, undefined).pipe( + Effect.andThen(Deferred.await(releaseStartup2)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(startupEntered2); + yield* instance.snapshot.refresh; expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ "new-model", @@ -1680,8 +1896,34 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "default", ]); - yield* Deferred.succeed(releaseStartup, undefined); - yield* Fiber.join(startup); + yield* Deferred.succeed(releaseStartup2, undefined); + yield* Fiber.join(startup2); + + const restoredForAuthInvalidate = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(restoredForAuthInvalidate); + + const startupEntered3 = yield* Deferred.make(); + const releaseStartup3 = yield* Deferred.make(); + const startup3 = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(startupEntered3, undefined).pipe( + Effect.andThen(Deferred.await(releaseStartup3)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(startupEntered3); + + yield* instance.auth?.invalidate ?? Effect.void; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "default", + ]); + + yield* Deferred.succeed(releaseStartup3, undefined); + yield* Fiber.join(startup3); }), ); @@ -1879,7 +2121,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const releaseNewerCallback = yield* Deferred.make(); const newerCallbackDone = yield* Deferred.make(); const secondWatcherSubscribed = yield* Deferred.make(); - let postTtlLiveReads = 0; + let checkProviderInspected = false; + let skipNextLiveRead = false; let armed = false; let trackNextWatcher = false; @@ -1889,9 +2132,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { getLiveConfigurationWithRevision: (instanceId) => Effect.gen(function* () { if (armed) { - postTtlLiveReads += 1; - // 1st read is checkProvider; 2nd read is enrichProviderCached capturing probeStartLiveRevision. - if (postTtlLiveReads === 2) { + if (skipNextLiveRead) { + skipNextLiveRead = false; + } else { armed = false; yield* Deferred.await(allowProbe); } @@ -1927,6 +2170,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), }; + const readyInspection = { + status: "ready" as const, + agentId: "test-agent", + version: "1.0.0", + distribution: "npx" as const, + }; const instance = yield* AcpRegistryDriver.create({ instanceId: identity.instanceId, displayName: identity.displayName, @@ -1939,12 +2188,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { gatedCoordinator, ), Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", - }), + ...catalogWithInspection(readyInspection), + inspect: () => + Effect.sync(() => { + if (armed && !checkProviderInspected) { + checkProviderInspected = true; + skipNextLiveRead = true; + } + return readyInspection; + }), resolve: () => Effect.succeed({ distribution: "npx" as const, diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 15d3e0bfd1099..f30c2c9fd892c 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -6,6 +6,7 @@ import { type AcpRegistryOperationError, type AcpRegistryProbeModel, type CustomModelSetting, + type ProviderOptionDescriptor, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; @@ -97,6 +98,13 @@ const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { modelsFromModelSelect: false, }; +function isExplicitSingletonCatalog(catalog: { + readonly builtInModelCount: number; + readonly modelsFromModelSelect: boolean; +}): boolean { + return catalog.builtInModelCount === 1 && catalog.modelsFromModelSelect; +} + function liveConfigurationReplacesAcceptedCatalog( configuration: AcpRegistryLiveConfiguration, accepted: AcceptedAcpRegistryCatalog, @@ -121,6 +129,8 @@ export function acpRegistryProbeSupersedesLiveCatalog(input: { if (input.probedModelsFromModelSelect) return true; return input.liveModelCount === 1 && !input.liveModelsFromModelSelect; } + // Empty disposable probes (e.g. cold-start or pre-catalog agents) keep the + // accepted catalog and retry on the 30s provisional TTL instead of clearing it. return false; } @@ -141,33 +151,38 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly configuration: AcpRegistryLiveConfiguration; readonly customModels: ReadonlyArray; readonly now: number; - readonly preserveSingleModelCatalog?: boolean; + readonly preserveSingleModelCatalog?: boolean | undefined; }): AcpRegistryEnrichmentCache { const { cache, configuration, customModels, now, preserveSingleModelCatalog } = input; if (cache.entry === null) { - // No probe has landed yet, but the live session published its - // configuration to the snapshot. Advance the cache epoch so a probe that - // was still in flight cannot overwrite that newer state when it lands. - return { ...cache, generation: cache.generation + 1 }; + // Only advance the cache epoch when the live session discovered a catalog + // so an options-only update cannot discard an in-flight initial probe. + return configuration.models.length > 0 ? { ...cache, generation: cache.generation + 1 } : cache; } const provider = applyAcpRegistryLiveConfiguration( cache.entry.provider, configuration, customModels, - cache.entry.provider.models, - preserveSingleModelCatalog === undefined ? undefined : { preserveSingleModelCatalog }, + undefined, + { preserveSingleModelCatalog }, ); if (Equal.equals(provider, cache.entry.provider)) return cache; + const previousBuiltIn = cache.entry.provider.models.filter((model) => !model.isCustom); + const nextBuiltIn = provider.models.filter((model) => !model.isCustom); + const catalogChanged = + configuration.models.length > 0 && + (previousBuiltIn.length !== nextBuiltIn.length || + nextBuiltIn.some((model, index) => model.slug !== previousBuiltIn[index]?.slug)); return { ...cache, - // The live session advanced the provider past what an in-flight probe - // started from; bump the epoch so the probe discards its stale result - // instead of overwriting this entry and publishing it. - generation: cache.generation + 1, + // Only bump the epoch and extend TTL when the live session changed the + // catalog; mid-session option tweaks must neither cancel an in-flight + // post-TTL probe nor starve the periodic refresh deadline. + generation: catalogChanged ? cache.generation + 1 : cache.generation, entry: { ...cache.entry, provider, - expiresAt: now + acpRegistryProbeTtlMs(provider), + expiresAt: catalogChanged ? now + acpRegistryProbeTtlMs(provider) : cache.entry.expiresAt, }, }; } @@ -197,18 +212,84 @@ const makeUnsupportedTextGeneration = (): ProviderTextGeneration => { const EMPTY_SLUG_SET: ReadonlySet = new Set(); +function isModelSpecificDescriptor( + descriptor: ProviderOptionDescriptor, + modelOptionIds: ReadonlySet, +): boolean { + return ( + modelOptionIds.has(descriptor.id) || + (descriptor.type === "select" && descriptor.role === "reasoning") + ); +} + +function modelWithSpecificOptions( + model: ServerProviderModel, + descriptors: ReadonlyArray, +): ServerProviderModel { + return { + ...model, + capabilities: + descriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: descriptors }), + }; +} + +function updateLearnedModelsFromLive( + learned: ReadonlyArray, + nextModels: ReadonlyArray, + configuration: AcpRegistryLiveConfiguration, +): ReadonlyArray { + const modelOptionIds = new Set(configuration.modelOptionIds ?? []); + const learnedBySlug = new Map( + learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), + ); + const configuredById = new Map(configuration.models.map((model) => [model.id, model] as const)); + let changed = false; + for (const model of nextModels) { + if (model.isCustom) continue; + const isCurrentModel = + configuration.currentModelId !== null && model.slug === configuration.currentModelId; + const hasAdvertisedReasoning = configuredById.get(model.slug)?.reasoningEffort !== undefined; + if (!isCurrentModel && !hasAdvertisedReasoning) continue; + const specific = (model.capabilities?.optionDescriptors ?? []).filter((descriptor) => + isModelSpecificDescriptor(descriptor, modelOptionIds), + ); + const previous = learnedBySlug.get(model.slug); + if (specific.length === 0) { + if (previous !== undefined) { + learnedBySlug.delete(model.slug); + changed = true; + } + continue; + } + const updated = modelWithSpecificOptions(model, specific); + if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { + learnedBySlug.set(model.slug, updated); + changed = true; + } + } + return changed ? Array.from(learnedBySlug.values()) : learned; +} + function mergeLearnedModelOptions( models: ReadonlyArray, learned: ReadonlyArray, - reasoningDisabledModelSlugs: ReadonlySet = EMPTY_SLUG_SET, + options?: { + readonly currentModelId?: string | null; + readonly reasoningDisabledModelSlugs?: ReadonlySet; + }, ): ReadonlyArray { if (learned.length === 0) return models; + const currentModelId = options?.currentModelId ?? null; + const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; const learnedBySlug = new Map( learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), ); let changed = false; const merged = models.map((model) => { - if (model.isCustom) return model; + // The probe already observed its currentModelId in full; do not restore dropped options onto it. + if (model.isCustom || (currentModelId !== null && model.slug === currentModelId)) return model; const previousDescriptors = learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; if (previousDescriptors.length === 0) return model; @@ -238,6 +319,47 @@ function mergeLearnedModelOptions( return changed ? merged : models; } +function updateLearnedModelsFromProbe( + learned: ReadonlyArray, + probedModels: ReadonlyArray, + options: { + readonly currentModelId: string | null; + readonly modelOptionIds: ReadonlySet; + readonly reasoningDisabledModelSlugs: ReadonlySet; + }, +): ReadonlyArray { + const learnedBySlug = new Map( + learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), + ); + const next: Array = []; + for (const model of probedModels) { + if (model.isCustom) continue; + if (options.currentModelId !== null && model.slug === options.currentModelId) { + const specific = (model.capabilities?.optionDescriptors ?? []).filter((descriptor) => + isModelSpecificDescriptor(descriptor, options.modelOptionIds), + ); + if (specific.length > 0) next.push(modelWithSpecificOptions(model, specific)); + continue; + } + const previousDescriptors = + learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; + const probedReasoning = (model.capabilities?.optionDescriptors ?? []).filter( + (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", + ); + const hasExplicitReasoningState = + options.reasoningDisabledModelSlugs.has(model.slug) || probedReasoning.length > 0; + const kept = previousDescriptors.filter( + (descriptor) => + !hasExplicitReasoningState || + descriptor.type !== "select" || + descriptor.role !== "reasoning", + ); + const combined = [...probedReasoning, ...kept]; + if (combined.length > 0) next.push(modelWithSpecificOptions(model, combined)); + } + return next; +} + function modelsFromDiscovery( discovery: | Pick< @@ -439,7 +561,7 @@ export function applyAcpRegistryLiveConfiguration( configuration: AcpRegistryLiveConfiguration, customModels: ReadonlyArray, previousModels: ReadonlyArray = provider.models, - options?: { readonly preserveSingleModelCatalog?: boolean }, + options?: { readonly preserveSingleModelCatalog?: boolean | undefined }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; // session/load may omit models (Kimi returns `{}`); keep the probed list @@ -623,6 +745,8 @@ interface DetailedAcpRegistryProviderStatus { readonly provider: ServerProvider; readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; + readonly probedCurrentModelId: string | null; + readonly probedModelOptionIds: ReadonlySet; readonly reasoningDisabledModelSlugs: ReadonlySet; } @@ -645,6 +769,8 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( provider, probedModelCount: 0, probedModelsFromModelSelect: false, + probedCurrentModelId: null, + probedModelOptionIds: EMPTY_SLUG_SET, reasoningDisabledModelSlugs: EMPTY_SLUG_SET, }); if (!input.settings.enabled) { @@ -699,6 +825,8 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( }), probedModelCount: probed.success.probe.models.length, probedModelsFromModelSelect: probed.success.modelsFromModelSelect === true, + probedCurrentModelId: probed.success.probe.currentModelId, + probedModelOptionIds: new Set(probed.success.probe.modelOptionIds ?? []), reasoningDisabledModelSlugs: new Set( probed.success.probe.models .filter((model) => model.reasoningEffort === null) @@ -851,15 +979,11 @@ export const AcpRegistryDriver: ProviderDriver (options?.preserveSingleModelCatalog !== undefined ? Effect.succeed(options.preserveSingleModelCatalog) - : Ref.get(acceptedCatalog).pipe( - Effect.map( - (accepted) => accepted.builtInModelCount === 1 && accepted.modelsFromModelSelect, - ), - ) + : Ref.get(acceptedCatalog).pipe(Effect.map(isExplicitSingletonCatalog)) ).pipe( Effect.flatMap((preserveSingleModelCatalog) => Ref.modify(learnedModels, (learned) => { @@ -870,7 +994,7 @@ export const AcpRegistryDriver: ProviderDriver 0 ? learned : provider.models, { preserveSingleModelCatalog }, ); - return [next, next.models === provider.models ? learned : next.models]; + return [next, updateLearnedModelsFromLive(learned, next.models, configuration)]; }), ), ); @@ -880,7 +1004,7 @@ export const AcpRegistryDriver: ProviderDriver Effect.succeed(withBaseModels), onSome: (configuration) => - applyLiveConfiguration( - withBaseModels, - configuration, - options?.preserveSingleModelCatalog === undefined - ? undefined - : { preserveSingleModelCatalog: options.preserveSingleModelCatalog }, - ), + applyLiveConfiguration(withBaseModels, configuration, { + preserveSingleModelCatalog: options?.preserveSingleModelCatalog, + }), }), ), Effect.map((withConfiguration) => @@ -1000,6 +1120,8 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( - Effect.gen(function* () { - const current = yield* Ref.get(enrichmentCache); - if (current.generation !== generation) return; - let resolved = provider; - if (fresh && provider.status === "ready") { - const liveSnapshot = Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( - instanceId, - ) - : { configuration: Option.none(), revision: 0, clearedThroughRevision: 0 }; - const accepted = yield* Ref.get(acceptedCatalog); - const liveCatalogUsed = Option.match(liveSnapshot.configuration, { - onNone: () => false, - onSome: (configuration) => - liveConfigurationReplacesAcceptedCatalog(configuration, accepted), - }); - const incumbent = - liveCatalogUsed && Option.isSome(liveSnapshot.configuration) - ? { - modelCount: liveSnapshot.configuration.value.models.length, - modelsFromModelSelect: - liveSnapshot.configuration.value.modelsFromModelSelect === true, - } - : { - modelCount: accepted.builtInModelCount, - modelsFromModelSelect: accepted.modelsFromModelSelect, - }; - const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ - probedModelCount, - probedModelsFromModelSelect, - liveModelCount: incumbent.modelCount, - liveModelsFromModelSelect: incumbent.modelsFromModelSelect, - }); - // A fresh non-provisional probe supersedes any live session catalog observed before it started. - const cleared = probeSupersedesLiveCatalog - ? Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + Effect.uninterruptible( + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + if (current.generation !== generation) return; + let resolved = provider; + if (fresh && provider.status === "ready") { + const liveSnapshot = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( instanceId, - probeStartLiveRevision, ) - : true - : false; - if ( - !probeSupersedesLiveCatalog && - !liveCatalogUsed && - accepted.models.length > 0 - ) { - resolved = { ...provider, models: accepted.models }; - } else { - const models = yield* Ref.modify(learnedModels, (learned) => { - const merged = mergeLearnedModelOptions( - provider.models, - learned, - reasoningDisabledModelSlugs, - ); - return [merged, cleared ? merged : learned] as const; + : { + configuration: Option.none(), + revision: 0, + clearedThroughRevision: 0, + }; + const accepted = yield* Ref.get(acceptedCatalog); + const liveCatalogUsed = Option.match(liveSnapshot.configuration, { + onNone: () => false, + onSome: (configuration) => + liveConfigurationReplacesAcceptedCatalog(configuration, accepted), }); - resolved = models === provider.models ? provider : { ...provider, models }; - } - const published = yield* withLiveRuntimeState( - resolved, - probeSupersedesLiveCatalog && - probedModelCount === 1 && - probedModelsFromModelSelect - ? { preserveSingleModelCatalog: true } - : undefined, - ); - if ( - cleared || - (!probeSupersedesLiveCatalog && - liveSnapshot.revision === probeStartLiveRevision) - ) { - const completedAt = yield* Clock.currentTimeMillis; - yield* Ref.set(enrichmentCache, { - ...current, - entry: { - provider: resolved, - expiresAt: completedAt + acpRegistryProbeTtlMs(provider), - }, + const incumbent = + liveCatalogUsed && Option.isSome(liveSnapshot.configuration) + ? { + modelCount: liveSnapshot.configuration.value.models.length, + modelsFromModelSelect: + liveSnapshot.configuration.value.modelsFromModelSelect === true, + } + : { + modelCount: accepted.builtInModelCount, + modelsFromModelSelect: accepted.modelsFromModelSelect, + }; + const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount, + probedModelsFromModelSelect, + liveModelCount: incumbent.modelCount, + liveModelsFromModelSelect: incumbent.modelsFromModelSelect, }); - } - if (cleared && published.status === "ready") { - yield* Ref.set(acceptedCatalog, { - models: published.models, - builtInModelCount: probedModelCount, - modelsFromModelSelect: probedModelsFromModelSelect, + // A fresh non-provisional probe supersedes any live session catalog observed before it started. + const cleared = probeSupersedesLiveCatalog + ? Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + ) + : true + : false; + if ( + !probeSupersedesLiveCatalog && + !liveCatalogUsed && + accepted.models.length > 0 + ) { + resolved = { ...provider, models: accepted.models }; + } else { + const models = yield* Ref.modify(learnedModels, (learned) => { + const merged = mergeLearnedModelOptions(provider.models, learned, { + currentModelId: probedCurrentModelId, + reasoningDisabledModelSlugs, + }); + const nextLearned = cleared + ? updateLearnedModelsFromProbe(learned, provider.models, { + currentModelId: probedCurrentModelId, + modelOptionIds: probedModelOptionIds, + reasoningDisabledModelSlugs, + }) + : learned; + return [merged, nextLearned] as const; + }); + resolved = + models === provider.models ? provider : { ...provider, models }; + } + const published = yield* withLiveRuntimeState(resolved, { + preserveSingleModelCatalog: + probeSupersedesLiveCatalog && + isExplicitSingletonCatalog({ + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + }) + ? true + : undefined, }); + if ( + cleared || + (!probeSupersedesLiveCatalog && + liveSnapshot.revision === probeStartLiveRevision) + ) { + const completedAt = yield* Clock.currentTimeMillis; + yield* Ref.set(enrichmentCache, { + ...current, + entry: { + provider: resolved, + expiresAt: completedAt + acpRegistryProbeTtlMs(provider), + }, + }); + } + if (cleared) { + yield* Ref.set(acceptedCatalog, { + models: resolved.models, + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + }); + } + yield* publishSnapshot(published); + return; } - yield* publishSnapshot(published); - return; - } - yield* withLiveRuntimeState(resolved, { - fallbackToAcceptedModels: - fresh && - resolved.status !== "ready" && - resolved.auth.status !== "unauthenticated", - }).pipe(Effect.flatMap(publishSnapshot)); - }), + if (fresh && resolved.auth.status === "unauthenticated") { + yield* Ref.set(enrichmentCache, { ...current, entry: null }); + yield* clearLearnedModels; + yield* clearAcceptedCatalog; + if (Option.isSome(runtimeCoordinator)) { + yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + ); + } + } + yield* withLiveRuntimeState(resolved, { + fallbackToAcceptedModels: + fresh && + resolved.status !== "ready" && + resolved.auth.status !== "unauthenticated", + }).pipe(Effect.flatMap(publishSnapshot)); + }), + ), ), }), ), @@ -1185,51 +1337,53 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( - Effect.gen(function* () { - const currentLive = - yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId); - if ( - Option.isNone(currentLive.configuration) || - revision <= currentLive.clearedThroughRevision - ) { - return; - } - const current = yield* getSnapshot; - const acceptedBefore = yield* Ref.get(acceptedCatalog); - const preserveSingleModelCatalog = - acceptedBefore.builtInModelCount === 1 && - acceptedBefore.modelsFromModelSelect; - const next = yield* applyLiveConfiguration(current, configuration, { - preserveSingleModelCatalog, - }); - if (next.status === "ready") { - yield* Ref.update(acceptedCatalog, (previous) => - liveConfigurationReplacesAcceptedCatalog(configuration, previous) - ? { - models: next.models, - builtInModelCount: configuration.models.length, - modelsFromModelSelect: configuration.modelsFromModelSelect === true, - } - : previous.models.length > 0 + Effect.uninterruptible( + Effect.gen(function* () { + const currentLive = + yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( + instanceId, + ); + if ( + Option.isNone(currentLive.configuration) || + revision <= currentLive.clearedThroughRevision + ) { + return; + } + const current = yield* getSnapshot; + const acceptedBefore = yield* Ref.get(acceptedCatalog); + const preserveSingleModelCatalog = isExplicitSingletonCatalog(acceptedBefore); + const next = yield* applyLiveConfiguration(current, configuration, { + preserveSingleModelCatalog, + }); + if (next.status === "ready") { + yield* Ref.update(acceptedCatalog, (previous) => + liveConfigurationReplacesAcceptedCatalog(configuration, previous) ? { - ...previous, models: next.models, + builtInModelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, } - : previous, + : previous.models.length > 0 + ? { + ...previous, + models: next.models, + } + : previous, + ); + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + preserveSingleModelCatalog, + }), ); - } - const now = yield* Clock.currentTimeMillis; - yield* Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - preserveSingleModelCatalog, - }), - ); - yield* publishSnapshot(next); - }), + yield* publishSnapshot(next); + }), + ), ), { afterRevision }, ), @@ -1292,22 +1446,29 @@ export const AcpRegistryDriver: ProviderDriver + liveSnapshotSemaphore.withPermit( + Effect.uninterruptible( invalidateEnrichmentCache.pipe( Effect.andThen(clearLearnedModels), Effect.andThen(clearAcceptedCatalog), + Effect.andThen( + Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value + .clearLiveConfiguration(instanceId) + .pipe( + Effect.andThen( + options?.clearCommands === true + ? runtimeCoordinator.value.clearAvailableCommands(instanceId) + : Effect.void, + ), + ) + : Effect.void, + ), ), ), - ), - ); + ); + const clearLiveState = clearCachedState({ clearCommands: true }); const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({ instanceId, settings: effectiveConfig, @@ -1352,19 +1513,7 @@ export const AcpRegistryDriver: ProviderDriver controller.refreshMethods ?? Effect.void)), }, - invalidateCaches: (Option.isSome(runtimeCoordinator) - ? runtimeCoordinator.value.clearLiveConfiguration(instanceId) - : Effect.void - ).pipe( - Effect.andThen( - liveSnapshotSemaphore.withPermit( - invalidateEnrichmentCache.pipe( - Effect.andThen(clearLearnedModels), - Effect.andThen(clearAcceptedCatalog), - ), - ), - ), - ), + invalidateCaches: clearCachedState(), orchestrationAdapter, textGeneration: makeUnsupportedTextGeneration(), acpSessionManagement: { @@ -1431,25 +1580,7 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), - Effect.tap(() => - liveSnapshotSemaphore.withPermit( - invalidateEnrichmentCache.pipe( - Effect.andThen(clearLearnedModels), - Effect.andThen(clearAcceptedCatalog), - Effect.andThen( - Option.isSome(runtimeCoordinator) - ? Effect.all( - [ - runtimeCoordinator.value.clearAvailableCommands(instanceId), - runtimeCoordinator.value.clearLiveConfiguration(instanceId), - ], - { concurrency: "unbounded", discard: true }, - ) - : Effect.void, - ), - ), - ), - ), + Effect.tap(() => clearLiveState), ); return Option.isSome(runtimeCoordinator) ? logout.pipe( diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 0d5cc21d9f581..12514532b8413 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -219,7 +219,9 @@ export function normalizeAcpRegistryLiveConfiguration( configOptions: ReadonlyArray, modeState?: Parameters[0]["modeState"], modelState?: EffectAcpSchema.SessionModelState | null, + options?: { readonly includeCatalog?: boolean }, ): AcpRegistryLiveConfiguration { + const includeCatalog = options?.includeCatalog !== false; const modelOption = findModelConfigOption(configOptions); const currentModelId = modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId; @@ -242,7 +244,7 @@ export function normalizeAcpRegistryLiveConfiguration( const effortOption = configOptions.find((option) => option.category === "thought_level") ?? configOptions.find(isAcpThoughtLevelOption); - const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => { + const advertisedModels = normalizeModels(candidates, boundedCurrentModelId).map((model) => { const reasoningEffort = advertisedReasoningEffort( effortOption, modelState?.availableModels.find((info) => info.modelId === model.id)?._meta, @@ -256,15 +258,15 @@ export function normalizeAcpRegistryLiveConfiguration( .map((option) => option.id), ); return { - models, - currentModelId: models.some((model) => model.id === boundedCurrentModelId) + models: includeCatalog ? advertisedModels : [], + currentModelId: advertisedModels.some((model) => model.id === boundedCurrentModelId) ? boundedCurrentModelId : null, configOptions: descriptors, modelOptionIds: descriptors .filter((descriptor) => modelOptionIds.has(descriptor.id)) .map((descriptor) => descriptor.id), - modelsFromModelSelect: modelOption !== undefined, + modelsFromModelSelect: includeCatalog && modelOption !== undefined, }; } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..e8d6fa2ee13f3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -433,6 +433,7 @@ export interface AcpAdapterV2Flavor { configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, modelState: EffectAcpSchema.SessionModelState | null | undefined, + options?: { readonly includeCatalog?: boolean }, ) => Effect.Effect; readonly onUrlElicitation?: (input: { readonly elicitationId: string; @@ -2283,6 +2284,36 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); + // Track the model catalog last published for the active session so mid-session + // option updates do not re-advertise a frozen catalog over a newer periodic probe. + const lastPublishedCatalogKey = yield* Ref.make(null); + const sessionCatalogKey = ( + configOptions: ReadonlyArray, + modelState: EffectAcpSchema.SessionModelState | null | undefined, + ): string => { + const modelOption = findModelConfigOption(configOptions); + if (modelOption?.type === "select") { + return `select:${flattenSelectChoices(modelOption.options) + .map((choice) => choice.value) + .join("\0")}`; + } + return `models:${(modelState?.availableModels ?? []).map((model) => model.modelId).join("\0")}`; + }; + const publishSessionConfiguration = Effect.fnUntraced(function* ( + configOptions: ReadonlyArray, + modeState: AcpSessionModeState | undefined, + modelState: EffectAcpSchema.SessionModelState | null | undefined, + ) { + if (flavor.onSessionConfigurationUpdate === undefined) return; + const catalogKey = sessionCatalogKey(configOptions, modelState); + const includeCatalog = yield* Ref.modify(lastPublishedCatalogKey, (previous) => [ + previous !== catalogKey, + catalogKey, + ]); + yield* flavor.onSessionConfigurationUpdate(configOptions, modeState, modelState, { + includeCatalog, + }); + }); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { @@ -2301,6 +2332,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rootForegroundWork = undefined; agentRequests.clear(); nativeChildren.clear(); + yield* Ref.set(lastPublishedCatalogKey, null); yield* Ref.set(activeSessionSetup, setup); }); const activeSelection = yield* Ref.make(null); @@ -7083,12 +7115,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( notification.update.sessionUpdate === "config_option_update" || notification.update.sessionUpdate === "current_mode_update" ) { - yield* ( - flavor.onSessionConfigurationUpdate?.( - yield* runtime.getConfigOptions, - yield* runtime.getModeState, - (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, - ) ?? Effect.void + yield* publishSessionConfiguration( + yield* runtime.getConfigOptions, + yield* runtime.getModeState, + (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, ); } const normalized = flavor.normalizeSessionUpdate?.(notification) ?? notification; @@ -7204,6 +7234,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (current === null || current.sessionId !== result.sessionId) { return; } + yield* Ref.set(lastPublishedCatalogKey, null); yield* Ref.set(activeSessionSetup, result); // The selection was configured against the provisional setup's // options, so the next turn re-applies it against the real ones. @@ -7219,12 +7250,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeBuildConfigurationBySessionId.delete(result.sessionId); } yield* refreshModelSwitchCapability; - yield* ( - flavor.onSessionConfigurationUpdate?.( - yield* targetRuntime.getConfigOptions, - yield* targetRuntime.getModeState, - result.sessionSetupResult.models, - ) ?? Effect.void + yield* publishSessionConfiguration( + yield* targetRuntime.getConfigOptions, + yield* targetRuntime.getModeState, + result.sessionSetupResult.models, ); }); @@ -8358,12 +8387,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* validateModelSelection(modelSelection); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); - yield* ( - flavor.onSessionConfigurationUpdate?.( - yield* runtime.getConfigOptions, - yield* runtime.getModeState, - (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, - ) ?? Effect.void + yield* publishSessionConfiguration( + yield* runtime.getConfigOptions, + yield* runtime.getModeState, + (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, ); }); @@ -9029,6 +9056,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* restartAcpRuntime(threadId); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); + yield* Ref.set(lastPublishedCatalogKey, null); yield* Ref.set(activeSessionSetup, null); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); From 4e55289aa03b9f121b752ec2c8a7eb09f06fa332 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 09:33:43 +0000 Subject: [PATCH 08/35] fix(acp-registry): track catalog revisions, cache winning reconciliation catalog, preserve warnings, and serialize readiness --- .../AcpRegistryRuntimeCoordinator.test.ts | 23 ++ .../server/AcpRegistryRuntimeCoordinator.ts | 28 +- .../src/server/driver.test.ts | 292 ++++++++++++++- .../src/server/driver.ts | 335 ++++++++++-------- packages/provider-acp/src/server/adapter.ts | 54 +-- 5 files changed, 541 insertions(+), 191 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 8b47db692c5f6..69ebab4a2420d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -315,6 +315,29 @@ describe("AcpRegistryRuntimeCoordinator", () => { const otherInstanceId = ProviderInstanceId.make("acpRegistry_kimi"); yield* coordinator.publishLiveConfiguration(otherInstanceId, configFor("kimi-v1")); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual(afterClear); + + // Options-only updates advance revision without advancing catalogRevision, so a + // catalog-scoped clear still succeeds while preserving the newer options-only entry. + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v3")); + const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-v3", + configOptions: [], + modelsFromModelSelect: false, + }); + const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(optionsSnap.revision).toBe(catalogSnap.revision + 1); + expect(optionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, catalogSnap.revision, { + catalogRevision: catalogSnap.catalogRevision, + }), + ).toBe(true); + const afterOptionsPreserved = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(Option.isSome(afterOptionsPreserved.configuration)).toBe(true); + expect(afterOptionsPreserved.clearedThroughRevision).toBe(catalogSnap.revision); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 363d228ade4d6..b8e90a016acd9 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -31,12 +31,14 @@ interface LiveConfigurationUpdate { export interface AcpRegistryLiveConfigurationSnapshot { readonly configuration: Option.Option; readonly revision: number; + readonly catalogRevision: number; readonly clearedThroughRevision: number; } const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { configuration: Option.none(), revision: 0, + catalogRevision: 0, clearedThroughRevision: 0, }; @@ -83,6 +85,7 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly clearLiveConfigurationIfRevision: ( instanceId: ProviderInstanceId, revision: number, + options?: { readonly catalogRevision?: number }, ) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, @@ -244,6 +247,7 @@ const make = Effect.gen(function* () { next.set(instanceId, { configuration: Option.none(), revision: current.revision, + catalogRevision: current.catalogRevision, clearedThroughRevision: nextCleared, }); return next; @@ -251,10 +255,28 @@ const make = Effect.gen(function* () { const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( - function* (instanceId, revision) { + function* (instanceId, revision, options) { return yield* Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; if (Option.isSome(current.configuration) && current.revision !== revision) { + // If only an options-only live update arrived after revision, keep those newer + // options while advancing clearedThroughRevision so the probe catalog can commit. + if ( + options?.catalogRevision !== undefined && + current.catalogRevision === options.catalogRevision && + current.configuration.value.models.length === 0 + ) { + const nextCleared = Math.max(current.clearedThroughRevision, revision); + if (nextCleared === current.clearedThroughRevision) { + return [true, state] as const; + } + const next = new Map(state); + next.set(instanceId, { + ...current, + clearedThroughRevision: nextCleared, + }); + return [true, next] as const; + } return [false, state] as const; } const nextCleared = Math.max(current.clearedThroughRevision, revision); @@ -268,6 +290,7 @@ const make = Effect.gen(function* () { next.set(instanceId, { configuration: Option.none(), revision: Math.max(current.revision, revision), + catalogRevision: Math.max(current.catalogRevision, options?.catalogRevision ?? 0), clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -280,10 +303,13 @@ const make = Effect.gen(function* () { Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; const revision = current.revision + 1; + const catalogRevision = + configuration.models.length > 0 ? current.catalogRevision + 1 : current.catalogRevision; const next = new Map(state); next.set(instanceId, { configuration: Option.some(configuration), revision, + catalogRevision, clearedThroughRevision: current.clearedThroughRevision, }); return [revision, next] as const; diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 695c30338ffa2..5b9c88851f8d2 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -417,6 +417,20 @@ describe("acpRegistrySnapshotReadiness", () => { ], [], ]); + + // An explicit supportsReasoningEffort: false on the current model strips the session effort selector too. + const currentDisabled = applyAcpRegistryLiveConfiguration( + provider, + normalizeAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "glm", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }), + [], + ).models.map((model) => model.capabilities?.optionDescriptors ?? []); + expect(currentDisabled).toEqual([[], []]); }); it("keeps each Mistral Vibe model's own thinking levels", () => { @@ -1753,14 +1767,27 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); - // Once the live entry has been cleared, a later provisional post-TTL probe—even after an - // intervening provisional live update—must not regress the settled accepted catalog. + // When a settled live catalog beats a provisional probe, the enrichment cache must store + // the winning live catalog (not the rejected provisional probe) so a subsequent options-only + // update and cached refresh within the 30s retry TTL do not regress to the placeholder. + const liveCatalogApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.map((m) => m.slug).join() === "live-a,live-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], - currentModelId: "live-placeholder", + models: [ + { id: "live-a", name: "Live A", description: null }, + { id: "live-b", name: "Live B", description: null }, + ], + currentModelId: "live-a", configOptions: [], - modelsFromModelSelect: false, + modelsFromModelSelect: true, }); + yield* Fiber.join(liveCatalogApplied); + yield* fileSystem.writeFileString( modelsPath, JSON.stringify({ provisional: "placeholder" }), @@ -1772,7 +1799,23 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; expect( Option.getOrThrow(yield* Fiber.join(afterProvisional)).models.map((model) => model.slug), - ).toEqual(["new-model", "old-model", "other-model"]); + ).toEqual(["live-a", "live-b"]); + + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "live-a", + configOptions: [], + modelsFromModelSelect: false, + }); + const cachedWithinRetryTtl = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(cachedWithinRetryTtl)).models.map( + (model) => model.slug, + ), + ).toEqual(["live-a", "live-b"]); // A provisional probe must still use the short retry TTL even when it retains a multi-model catalog. yield* fileSystem.writeFileString( @@ -1790,8 +1833,39 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ), ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); - // A transient discovery failure after TTL expiry must surface warning status without - // dropping the accepted catalog to synthetic default, and must stay uncached for retry. + // A transient discovery failure after TTL expiry must preserve its warning/message even + // when an options-only live configuration exists, while keeping accepted models and live options. + const optionsBeforeFailure = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(optionsBeforeFailure); + yield* fileSystem.writeFileString( modelsPath, JSON.stringify({ fail: "Temporary discovery outage" }), @@ -1805,12 +1879,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; const warned = Option.getOrThrow(yield* Fiber.join(failedProbe)); expect(warned.status).toBe("warning"); + expect(warned.message).toBeTruthy(); expect(warned.models.map((model) => model.slug)).toEqual([ "new-model", "old-model", "other-model", "settled-model", ]); + expect( + warned.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue, + ).toBe("low"); yield* fileSystem.writeFileString( modelsPath, @@ -1941,8 +2022,27 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const secondProbeEntered = yield* Deferred.make(); const releaseSecondProbe = yield* Deferred.make(); - const secondProbeClosed = yield* Deferred.make(); - let resolves = 0; + const secondProbeSettled = yield* Deferred.make(); + let gateNextResolve = false; + let secondProbeReleased = false; + + const observedCoordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...coordinator, + runBackgroundProbe: (agentId, effect) => + Effect.suspend(() => { + const armedBefore = gateNextResolve; + return coordinator + .runBackgroundProbe(agentId, effect) + .pipe( + Effect.tap(() => + armedBefore && secondProbeReleased + ? Deferred.succeed(secondProbeSettled, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ); + }), + }; const instance = yield* AcpRegistryDriver.create({ instanceId: identity.instanceId, @@ -1951,6 +2051,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { environment: [], config: decodeSettings({ agentId: "test-agent" }), }).pipe( + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + observedCoordinator, + ), Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { ...catalogWithInspection({ status: "ready", @@ -1960,13 +2064,11 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), resolve: () => Effect.gen(function* () { - resolves += 1; - if (resolves === 2) { - yield* Effect.addFinalizer(() => - Deferred.succeed(secondProbeClosed, undefined).pipe(Effect.asVoid), - ); + if (gateNextResolve) { + gateNextResolve = false; yield* Deferred.succeed(secondProbeEntered, undefined); yield* Deferred.await(releaseSecondProbe); + secondProbeReleased = true; } return { distribution: "npx" as const, @@ -1989,6 +2091,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { JSON.stringify(["old-model", "other-model", "stale-probe-model"]), ); yield* TestClock.adjust("16 minutes"); + gateNextResolve = true; yield* instance.snapshot.refresh; yield* Deferred.await(secondProbeEntered); @@ -2018,9 +2121,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Fiber.join(liveApplied); yield* Deferred.succeed(releaseSecondProbe, undefined); - yield* Deferred.await(secondProbeClosed); - // Follow-up refresh waits for the semaphore/probe settlement and must preserve the live catalog. - yield* instance.snapshot.refresh; + // Wait for the competing probe's commit-or-discard step to settle before asserting or refreshing. + yield* Deferred.await(secondProbeSettled); expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ "entitled-model", ]); @@ -2030,6 +2132,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (config) => config.currentModelId, ), ).toEqual(Option.some("entitled-model")); + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); // A subsequent provisional single-model live update must not replace the explicit singleton // catalog, overwrite its model-specific options, or downgrade its provenance. @@ -2099,6 +2205,156 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); + it.effect( + "commits a fresh post-TTL catalog when only an options-only live update arrives in flight", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-inflight-options-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const secondProbeEntered = yield* Deferred.make(); + const releaseSecondProbe = yield* Deferred.make(); + let gateNextResolve = false; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.gen(function* () { + if (gateNextResolve) { + gateNextResolve = false; + yield* Deferred.succeed(secondProbeEntered, undefined); + yield* Deferred.await(releaseSecondProbe); + } + return { + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }), + ); + + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["old-model", "other-model", "new-model"]), + ); + yield* TestClock.adjust("16 minutes"); + gateNextResolve = true; + yield* instance.snapshot.refresh; + yield* Deferred.await(secondProbeEntered); + + const optionsApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(optionsApplied); + + const committed = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.succeed(releaseSecondProbe, undefined); + const updated = Option.getOrThrow(yield* Fiber.join(committed)); + expect(updated.models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + expect( + updated.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue, + ).toBe("low"); + + // Verify the fresh catalog was saved to acceptedCatalog (survives skipped readiness) and cache. + const startupEntered = yield* Deferred.make(); + const releaseStartup = yield* Deferred.make(); + const startup = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(startupEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseStartup)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(startupEntered); + + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + yield* Deferred.succeed(releaseStartup, undefined); + yield* Fiber.join(startup); + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["unexpected-reprobe", "other-model"]), + ); + const cached = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(cached)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model", "new-model"]); + }), + ); + it.effect( "skips a delayed live-watcher callback after a fresh probe supersedes its revision", () => diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index f30c2c9fd892c..ae67bf2e9c398 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -383,7 +383,15 @@ function modelsFromDiscovery( ); const sharedIds = new Set(shared.map((descriptor) => descriptor.id)); const capabilitiesFor = ({ id: slug, reasoningEffort }: AcpRegistryProbeModel) => { - if (slug === discovery?.currentModelId) return capabilities; + if (slug === discovery?.currentModelId) { + if (reasoningEffort !== null) return capabilities; + const filtered = (discovery?.configOptions ?? []).filter( + (descriptor) => descriptor.type !== "select" || descriptor.role !== "reasoning", + ); + return filtered.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: filtered }); + } // The levels a model advertises replace the ones an earlier session reported. const own = ( previousModels.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? [] @@ -999,12 +1007,14 @@ export const AcpRegistryDriver: ProviderDriver applyLiveConfiguration(withBaseModels, configuration, { preserveSingleModelCatalog: options?.preserveSingleModelCatalog, - }), + }).pipe( + Effect.map((applied) => + options?.preserveStatus === true + ? { + ...applied, + status: withBaseModels.status, + ...(withBaseModels.message === undefined + ? {} + : { message: withBaseModels.message }), + } + : applied, + ), + ), }), ), Effect.map((withConfiguration) => @@ -1070,10 +1092,12 @@ export const AcpRegistryDriver: ProviderDriver - withLiveRuntimeState(provider, { - recordLiveRevision: true, - fallbackToAcceptedModels: true, - }), + liveSnapshotSemaphore.withPermit( + withLiveRuntimeState(provider, { + recordLiveRevision: true, + fallbackToAcceptedModels: true, + }), + ), ), ); const enrichProvider = checkAcpRegistryProviderStatusDetailed( @@ -1093,7 +1117,6 @@ export const AcpRegistryDriver: ProviderDriver ({ generation: current.generation + 1, entry: null, @@ -1118,6 +1141,7 @@ export const AcpRegistryDriver: ProviderDriver Effect.void, - onSome: ({ - provider, - generation, - fresh, - probeStartLiveRevision, - probedModelCount, - probedModelsFromModelSelect, - probedCurrentModelId, - probedModelOptionIds, - reasoningDisabledModelSlugs, - }) => - liveSnapshotSemaphore.withPermit( - Effect.uninterruptible( - Effect.gen(function* () { - const current = yield* Ref.get(enrichmentCache); - if (current.generation !== generation) return; - let resolved = provider; - if (fresh && provider.status === "ready") { - const liveSnapshot = Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( - instanceId, - ) + ({ + provider, + generation, + fresh, + probeStartLiveRevision, + probeStartCatalogRevision, + probedModelCount, + probedModelsFromModelSelect, + probedCurrentModelId, + probedModelOptionIds, + reasoningDisabledModelSlugs, + }) => + liveSnapshotSemaphore.withPermit( + Effect.uninterruptible( + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + if (current.generation !== generation) return; + let resolved = provider; + if (fresh && provider.status === "ready") { + const liveSnapshot = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( + instanceId, + ) + : { + configuration: Option.none(), + revision: 0, + catalogRevision: 0, + clearedThroughRevision: 0, + }; + const accepted = yield* Ref.get(acceptedCatalog); + const liveCatalogUsed = Option.match(liveSnapshot.configuration, { + onNone: () => false, + onSome: (configuration) => + liveConfigurationReplacesAcceptedCatalog(configuration, accepted), + }); + const incumbent = + liveCatalogUsed && Option.isSome(liveSnapshot.configuration) + ? { + modelCount: liveSnapshot.configuration.value.models.length, + modelsFromModelSelect: + liveSnapshot.configuration.value.modelsFromModelSelect === true, + } : { - configuration: Option.none(), - revision: 0, - clearedThroughRevision: 0, + modelCount: accepted.builtInModelCount, + modelsFromModelSelect: accepted.modelsFromModelSelect, }; - const accepted = yield* Ref.get(acceptedCatalog); - const liveCatalogUsed = Option.match(liveSnapshot.configuration, { - onNone: () => false, - onSome: (configuration) => - liveConfigurationReplacesAcceptedCatalog(configuration, accepted), - }); - const incumbent = - liveCatalogUsed && Option.isSome(liveSnapshot.configuration) - ? { - modelCount: liveSnapshot.configuration.value.models.length, - modelsFromModelSelect: - liveSnapshot.configuration.value.modelsFromModelSelect === true, - } - : { - modelCount: accepted.builtInModelCount, - modelsFromModelSelect: accepted.modelsFromModelSelect, - }; - const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ - probedModelCount, - probedModelsFromModelSelect, - liveModelCount: incumbent.modelCount, - liveModelsFromModelSelect: incumbent.modelsFromModelSelect, - }); - // A fresh non-provisional probe supersedes any live session catalog observed before it started. - const cleared = probeSupersedesLiveCatalog - ? Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( - instanceId, - probeStartLiveRevision, - ) - : true - : false; - if ( - !probeSupersedesLiveCatalog && - !liveCatalogUsed && - accepted.models.length > 0 - ) { - resolved = { ...provider, models: accepted.models }; - } else { - const models = yield* Ref.modify(learnedModels, (learned) => { - const merged = mergeLearnedModelOptions(provider.models, learned, { - currentModelId: probedCurrentModelId, - reasoningDisabledModelSlugs, - }); - const nextLearned = cleared - ? updateLearnedModelsFromProbe(learned, provider.models, { - currentModelId: probedCurrentModelId, - modelOptionIds: probedModelOptionIds, - reasoningDisabledModelSlugs, - }) - : learned; - return [merged, nextLearned] as const; + const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount, + probedModelsFromModelSelect, + liveModelCount: incumbent.modelCount, + liveModelsFromModelSelect: incumbent.modelsFromModelSelect, + }); + // A fresh non-provisional probe supersedes any live session catalog observed before it started. + const cleared = probeSupersedesLiveCatalog + ? Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + { catalogRevision: probeStartCatalogRevision }, + ) + : true + : false; + if ( + !probeSupersedesLiveCatalog && + !liveCatalogUsed && + accepted.models.length > 0 + ) { + resolved = { ...provider, models: accepted.models }; + } else { + const models = yield* Ref.modify(learnedModels, (learned) => { + const merged = mergeLearnedModelOptions(provider.models, learned, { + currentModelId: probedCurrentModelId, + reasoningDisabledModelSlugs, }); - resolved = - models === provider.models ? provider : { ...provider, models }; - } - const published = yield* withLiveRuntimeState(resolved, { - preserveSingleModelCatalog: - probeSupersedesLiveCatalog && - isExplicitSingletonCatalog({ - builtInModelCount: probedModelCount, - modelsFromModelSelect: probedModelsFromModelSelect, - }) - ? true - : undefined, + const nextLearned = cleared + ? updateLearnedModelsFromProbe(learned, provider.models, { + currentModelId: probedCurrentModelId, + modelOptionIds: probedModelOptionIds, + reasoningDisabledModelSlugs, + }) + : learned; + return [merged, nextLearned] as const; }); - if ( - cleared || - (!probeSupersedesLiveCatalog && - liveSnapshot.revision === probeStartLiveRevision) - ) { - const completedAt = yield* Clock.currentTimeMillis; - yield* Ref.set(enrichmentCache, { - ...current, - entry: { - provider: resolved, - expiresAt: completedAt + acpRegistryProbeTtlMs(provider), - }, - }); - } - if (cleared) { - yield* Ref.set(acceptedCatalog, { - models: resolved.models, + resolved = models === provider.models ? provider : { ...provider, models }; + } + const published = yield* withLiveRuntimeState(resolved, { + preserveSingleModelCatalog: + probeSupersedesLiveCatalog && + isExplicitSingletonCatalog({ builtInModelCount: probedModelCount, modelsFromModelSelect: probedModelsFromModelSelect, - }); - } - yield* publishSnapshot(published); - return; + }) + ? true + : undefined, + }); + if ( + cleared || + (!probeSupersedesLiveCatalog && + liveSnapshot.catalogRevision === probeStartCatalogRevision) + ) { + const completedAt = yield* Clock.currentTimeMillis; + yield* Ref.set(enrichmentCache, { + ...current, + entry: { + // Cache the catalog that won reconciliation (not a rejected provisional probe) + // while keeping the retry TTL computed from the fresh probe result. + provider: !probeSupersedesLiveCatalog + ? { ...resolved, models: published.models } + : resolved, + expiresAt: completedAt + acpRegistryProbeTtlMs(provider), + }, + }); } - if (fresh && resolved.auth.status === "unauthenticated") { - yield* Ref.set(enrichmentCache, { ...current, entry: null }); - yield* clearLearnedModels; - yield* clearAcceptedCatalog; - if (Option.isSome(runtimeCoordinator)) { - yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( - instanceId, - probeStartLiveRevision, - ); - } + if (cleared) { + yield* Ref.set(acceptedCatalog, { + models: resolved.models, + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + }); } - yield* withLiveRuntimeState(resolved, { - fallbackToAcceptedModels: - fresh && - resolved.status !== "ready" && - resolved.auth.status !== "unauthenticated", - }).pipe(Effect.flatMap(publishSnapshot)); - }), - ), + yield* publishSnapshot(published); + return; + } + if (fresh && resolved.auth.status === "unauthenticated") { + yield* Ref.set(enrichmentCache, { ...current, entry: null }); + yield* clearLearnedModels; + yield* clearAcceptedCatalog; + if (Option.isSome(runtimeCoordinator)) { + yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + ); + } + } + const preserveTransientFailure = + fresh && + resolved.status !== "ready" && + resolved.auth.status !== "unauthenticated"; + yield* withLiveRuntimeState(resolved, { + fallbackToAcceptedModels: preserveTransientFailure, + preserveStatus: preserveTransientFailure, + }).pipe(Effect.flatMap(publishSnapshot)); + }), ), - }), + ), ), ); + const publishEnrichment = ( + Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value.runBackgroundProbe( + effectiveConfig.source === "local" + ? `local:${instanceId}` + : effectiveConfig.agentId, + probeAndCommit, + ) + : probeAndCommit + ).pipe(Effect.asVoid); if (Option.isNone(runtimeCoordinator)) return publishEnrichment; const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e8d6fa2ee13f3..96b92098fca69 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2293,27 +2293,41 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ): string => { const modelOption = findModelConfigOption(configOptions); if (modelOption?.type === "select") { - return `select:${flattenSelectChoices(modelOption.options) - .map((choice) => choice.value) - .join("\0")}`; - } - return `models:${(modelState?.availableModels ?? []).map((model) => model.modelId).join("\0")}`; - }; - const publishSessionConfiguration = Effect.fnUntraced(function* ( - configOptions: ReadonlyArray, - modeState: AcpSessionModeState | undefined, - modelState: EffectAcpSchema.SessionModelState | null | undefined, - ) { - if (flavor.onSessionConfigurationUpdate === undefined) return; - const catalogKey = sessionCatalogKey(configOptions, modelState); - const includeCatalog = yield* Ref.modify(lastPublishedCatalogKey, (previous) => [ - previous !== catalogKey, - catalogKey, + return JSON.stringify([ + "select", + flattenSelectChoices(modelOption.options).map((choice) => [ + choice.value, + choice.name, + choice.description ?? null, + ]), + ]); + } + return JSON.stringify([ + "models", + (modelState?.availableModels ?? []).map((model) => [ + model.modelId, + model.name, + model.description ?? null, + ]), ]); - yield* flavor.onSessionConfigurationUpdate(configOptions, modeState, modelState, { - includeCatalog, - }); - }); + }; + const publishSessionConfiguration = Effect.fn("AcpAdapterV2.publishSessionConfiguration")( + function* ( + configOptions: ReadonlyArray, + modeState: AcpSessionModeState | undefined, + modelState: EffectAcpSchema.SessionModelState | null | undefined, + ) { + if (flavor.onSessionConfigurationUpdate === undefined) return; + const catalogKey = sessionCatalogKey(configOptions, modelState); + const includeCatalog = yield* Ref.modify(lastPublishedCatalogKey, (previous) => [ + previous !== catalogKey, + catalogKey, + ]); + yield* flavor.onSessionConfigurationUpdate(configOptions, modeState, modelState, { + includeCatalog, + }); + }, + ); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { From 0f3070499f13aac933a48add67262c50ae5716fe Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 10:29:15 +0000 Subject: [PATCH 09/35] fix(acp-registry): harden live options, reasoning disable, and catalog dedupe --- .../Adapters/AcpAdapterV2.test.ts | 116 ++ .../AcpRegistryRuntimeCoordinator.test.ts | 76 +- .../server/AcpRegistryRuntimeCoordinator.ts | 85 +- .../src/server/driver.test.ts | 1309 ++++++++++------- .../src/server/driver.ts | 613 +++++--- .../provider-acp-registry/src/server/probe.ts | 23 +- packages/provider-acp/src/server/adapter.ts | 89 +- .../src/server/sessionConfig.test.ts | 61 +- .../provider-acp/src/server/sessionConfig.ts | 64 +- 9 files changed, 1651 insertions(+), 785 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 9cb489ba59548..c8f89885bf69a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5268,6 +5268,122 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect( + "deduplicates unchanged config_option_update catalogs and re-advertises on changed choices or new sessions", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let activeConfigOptions: ReadonlyArray | undefined; + const publications: Array<{ readonly includeCatalog: boolean | undefined }> = []; + const instanceId = ProviderInstanceId.make("acp-test-catalog-dedupe"); + const makeModelSelect = ( + currentValue: string, + choices: ReadonlyArray<{ readonly value: string; readonly name: string }>, + ): ReadonlyArray => [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue, + options: [...choices], + }, + ]; + const initialChoices = [ + { value: "default", name: "Default" }, + { value: "composer-2", name: "Composer 2" }, + ] as const; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + onSessionConfigurationUpdate: ( + _configOptions, + _modeState, + _modelState, + updateOptions, + ) => + Effect.sync(() => { + publications.push({ includeCatalog: updateOptions?.includeCatalog }); + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + getConfigOptions: + activeConfigOptions === undefined + ? runtime.getConfigOptions + : Effect.sync(() => activeConfigOptions!), + handleSessionUpdate: (next) => + Effect.sync(() => { + sessionUpdate = next; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))), + }), + }), + }, + selfInvocation, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const open = (suffix: string) => + adapter.openSession({ + threadId: ThreadId.make(`thread-acp-catalog-dedupe-${suffix}`), + providerSessionId: ProviderSessionId.make(`provider-session-acp-dedupe-${suffix}`), + modelSelection: { instanceId, model: "default" }, + runtimePolicy, + }); + + activeConfigOptions = makeModelSelect("default", initialChoices); + yield* open("first"); + assert.deepEqual( + publications.map((entry) => entry.includeCatalog), + [true], + "initial session setup publishes its catalog", + ); + + // config_option_update with unchanged model choices sets includeCatalog: false. + activeConfigOptions = makeModelSelect("composer-2", initialChoices); + yield* sessionUpdate!({ + sessionId: "mock-session-1", + update: { sessionUpdate: "config_option_update", configOptions: [] }, + }); + assert.deepEqual( + publications.map((entry) => entry.includeCatalog), + [true, false], + ); + + // config_option_update with changed model choices sets includeCatalog: true. + activeConfigOptions = makeModelSelect("composer-2", [ + ...initialChoices, + { value: "composer-3", name: "Composer 3" }, + ]); + yield* sessionUpdate!({ + sessionId: "mock-session-1", + update: { sessionUpdate: "config_option_update", configOptions: [] }, + }); + assert.deepEqual( + publications.map((entry) => entry.includeCatalog), + [true, false, true], + ); + + // Opening a new session resets the deduplication key even when choices match. + yield* open("second"); + assert.deepEqual( + publications.map((entry) => entry.includeCatalog), + [true, false, true, true], + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + // Adoption either reaches the adapter after openSession configured the // provisional setup, or before it, so openSession configures the adopted one. it.live.each([false, true])( diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 69ebab4a2420d..1a592a3560cd3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -316,19 +316,40 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(otherInstanceId, configFor("kimi-v1")); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual(afterClear); - // Options-only updates advance revision without advancing catalogRevision, so a - // catalog-scoped clear still succeeds while preserving the newer options-only entry. + // Options-only updates preserve any unsuperseded catalog in stored state while keeping + // catalogRevision unchanged, and a catalog-scoped clear strips only the catalog while + // preserving the newer options descriptor. + const effortOption = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v3")); const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - yield* coordinator.publishLiveConfiguration(instanceId, { + const optionsOnlyConfig = { models: [], currentModelId: "model-v3", - configOptions: [], + configOptions: [effortOption], + modelOptionIds: ["effort"], modelsFromModelSelect: false, - }); + }; + yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyConfig); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(optionsSnap.revision).toBe(catalogSnap.revision + 1); expect(optionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); + expect(optionsSnap.configuration).toEqual( + Option.some({ + ...optionsOnlyConfig, + models: configFor("model-v3").models, + modelsFromModelSelect: true, + }), + ); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, catalogSnap.revision, { catalogRevision: catalogSnap.catalogRevision, @@ -336,8 +357,49 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); const afterOptionsPreserved = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(Option.isSome(afterOptionsPreserved.configuration)).toBe(true); - expect(afterOptionsPreserved.clearedThroughRevision).toBe(catalogSnap.revision); + expect(afterOptionsPreserved).toEqual({ + ...optionsSnap, + configuration: Option.some(optionsOnlyConfig), + clearedThroughRevision: catalogSnap.revision, + }); + + // A catalog-scoped clear with clearOptions: true wipes both catalog and options + // (used by authoritative unauthenticated probes) and advances clearedThroughRevision. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, catalogSnap.revision, { + catalogRevision: catalogSnap.catalogRevision, + clearOptions: true, + }), + ).toBe(true); + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ + ...optionsSnap, + configuration: Option.none(), + clearedThroughRevision: optionsSnap.revision, + }); + + // A catalog-scoped clear at the exact catalog revision strips models while keeping options. + yield* coordinator.publishLiveConfiguration(instanceId, { + ...configFor("model-v4"), + configOptions: [effortOption], + modelOptionIds: ["effort"], + }); + const v4Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v4Snap.revision, { + catalogRevision: v4Snap.catalogRevision, + }), + ).toBe(true); + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ + ...v4Snap, + configuration: Option.some({ + models: [], + currentModelId: "model-v4", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }), + clearedThroughRevision: v4Snap.revision, + }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index b8e90a016acd9..47d870ab98872 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -8,6 +8,7 @@ import * as Deferred from "effect/Deferred"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; @@ -35,7 +36,7 @@ export interface AcpRegistryLiveConfigurationSnapshot { readonly clearedThroughRevision: number; } -const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { +export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { configuration: Option.none(), revision: 0, catalogRevision: 0, @@ -85,7 +86,13 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly clearLiveConfigurationIfRevision: ( instanceId: ProviderInstanceId, revision: number, - options?: { readonly catalogRevision?: number }, + options?: { + readonly catalogRevision?: number; + readonly clearOptions?: boolean; + readonly retainPreProbeConfiguration?: ( + configuration: AcpRegistryLiveConfiguration, + ) => Option.Option; + }, ) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, @@ -258,39 +265,47 @@ const make = Effect.gen(function* () { function* (instanceId, revision, options) { return yield* Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; - if (Option.isSome(current.configuration) && current.revision !== revision) { - // If only an options-only live update arrived after revision, keep those newer - // options while advancing clearedThroughRevision so the probe catalog can commit. - if ( - options?.catalogRevision !== undefined && - current.catalogRevision === options.catalogRevision && - current.configuration.value.models.length === 0 - ) { - const nextCleared = Math.max(current.clearedThroughRevision, revision); - if (nextCleared === current.clearedThroughRevision) { - return [true, state] as const; - } - const next = new Map(state); - next.set(instanceId, { - ...current, - clearedThroughRevision: nextCleared, - }); - return [true, next] as const; + const catalogScoped = options?.catalogRevision !== undefined; + if (catalogScoped) { + if (current.catalogRevision !== options.catalogRevision) { + return [false, state] as const; } + } else if (Option.isSome(current.configuration) && current.revision !== revision) { return [false, state] as const; } - const nextCleared = Math.max(current.clearedThroughRevision, revision); + const clearAll = !catalogScoped || options.clearOptions === true; + const nextCleared = clearAll + ? Math.max(current.clearedThroughRevision, current.revision, revision) + : Math.max(current.clearedThroughRevision, revision); + const nextConfiguration: Option.Option = clearAll + ? Option.none() + : Option.flatMap(current.configuration, (configuration) => { + const withoutCatalog: AcpRegistryLiveConfiguration = { + ...configuration, + models: [], + modelsFromModelSelect: false, + }; + if (current.revision > revision) { + // Preserve options-only updates that landed while the probe ran. + return Option.some(withoutCatalog); + } + if (options.retainPreProbeConfiguration !== undefined) { + return options.retainPreProbeConfiguration(withoutCatalog); + } + return withoutCatalog.configOptions.length > 0 + ? Option.some(withoutCatalog) + : Option.none(); + }); if ( - Option.isNone(current.configuration) && + Equal.equals(current.configuration, nextConfiguration) && nextCleared === current.clearedThroughRevision ) { return [true, state] as const; } const next = new Map(state); next.set(instanceId, { - configuration: Option.none(), - revision: Math.max(current.revision, revision), - catalogRevision: Math.max(current.catalogRevision, options?.catalogRevision ?? 0), + ...current, + configuration: nextConfiguration, clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -303,11 +318,25 @@ const make = Effect.gen(function* () { Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; const revision = current.revision + 1; - const catalogRevision = - configuration.models.length > 0 ? current.catalogRevision + 1 : current.catalogRevision; + const hasCatalog = configuration.models.length > 0; + const catalogRevision = hasCatalog ? current.catalogRevision + 1 : current.catalogRevision; + // Keep any unsuperseded session catalog in coordinator state across options-only + // updates so readiness checks before acceptedCatalog settles do not regress to default. + const storedConfiguration: AcpRegistryLiveConfiguration = + !hasCatalog && + Option.isSome(current.configuration) && + current.configuration.value.models.length > 0 + ? { + ...configuration, + models: current.configuration.value.models, + ...(current.configuration.value.modelsFromModelSelect === undefined + ? {} + : { modelsFromModelSelect: current.configuration.value.modelsFromModelSelect }), + } + : configuration; const next = new Map(state); next.set(instanceId, { - configuration: Option.some(configuration), + configuration: Option.some(storedConfiguration), revision, catalogRevision, clearedThroughRevision: current.clearedThroughRevision, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 5b9c88851f8d2..1b01fea744fc9 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -34,6 +34,7 @@ import { checkAcpRegistryProviderReadiness, checkAcpRegistryProviderStatus, isAcpRegistryCacheValid, + retainAcpRegistryLiveOptionsAfterProbe, updateAcpRegistryEnrichmentCache, } from "./driver.ts"; import { @@ -431,6 +432,97 @@ describe("acpRegistrySnapshotReadiness", () => { [], ).models.map((model) => model.capabilities?.optionDescriptors ?? []); expect(currentDisabled).toEqual([[], []]); + + // Options-only updates (includeCatalog: false) must also strip effort on a reasoning-disabled current model. + const optionsOnlyDisabled = normalizeAcpRegistryLiveConfiguration( + [effort], + undefined, + { + currentModelId: "glm", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }, + { includeCatalog: false }, + ); + expect(optionsOnlyDisabled.configOptions).toEqual([]); + expect(optionsOnlyDisabled.modelOptionIds).toEqual([]); + expect(optionsOnlyDisabled.reasoningDisabledModelIds).toEqual(["glm"]); + const providerWithEffortOnGlm = applyAcpRegistryLiveConfiguration( + provider, + normalizeAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "glm", + availableModels: [ + { modelId: "glm", name: "GLM" }, + { modelId: "opus", name: "Opus" }, + ], + }), + [], + ); + expect( + applyAcpRegistryLiveConfiguration( + providerWithEffortOnGlm, + optionsOnlyDisabled, + [], + ).models.map((model) => model.capabilities?.optionDescriptors ?? []), + ).toEqual([[], []]); + + // Explicit probe-level reasoningDisabledModelSlugs keeps effort off a disabled model during + // an options-only overlay while preserving unrelated options and allowing enabled models. + const modeDescriptor = { + id: "mode", + label: "Mode", + type: "select" as const, + currentValue: "plan", + options: [ + { id: "code", label: "Code" }, + { id: "plan", label: "Plan" }, + ], + }; + const effortDescriptor = { ...liveOptions[0]!, role: "reasoning" as const }; + const overlaidDisabled = applyAcpRegistryLiveConfiguration( + providerWithModels( + [ + { id: "glm", name: "GLM", description: null }, + { id: "opus", name: "Opus", description: null }, + ], + "glm", + ), + { + models: [], + currentModelId: "glm", + configOptions: [modeDescriptor, effortDescriptor], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + undefined, + { reasoningDisabledModelSlugs: new Set(["glm"]) }, + ); + expect( + overlaidDisabled.models.map((model) => + (model.capabilities?.optionDescriptors ?? []).map((descriptor) => descriptor.id), + ), + ).toEqual([["mode"], ["mode"]]); + const overlaidEnabled = applyAcpRegistryLiveConfiguration( + overlaidDisabled, + { + models: [], + currentModelId: "opus", + configOptions: [modeDescriptor, effortDescriptor], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + undefined, + { reasoningDisabledModelSlugs: new Set(["glm"]) }, + ); + expect( + overlaidEnabled.models.map((model) => + (model.capabilities?.optionDescriptors ?? []).map((descriptor) => descriptor.id), + ), + ).toEqual([["mode"], ["mode", "effort"]]); }); it("keeps each Mistral Vibe model's own thinking levels", () => { @@ -1102,6 +1194,106 @@ describe("acpRegistryEnrichmentCache", () => { }), ).toBe(true); }); + it("retains valid live option values across a superseding probe while dropping removed or disabled options", () => { + const mode = (currentValue: "ask" | "code") => ({ + id: "mode", + label: "Mode", + type: "select" as const, + currentValue, + options: [ + { id: "ask", label: "Ask" }, + { id: "code", label: "Code" }, + ], + }); + const effort = (currentValue: "low" | "high") => ({ + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue, + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); + const legacy = { + id: "legacy", + label: "Legacy", + type: "select" as const, + currentValue: "on", + options: [{ id: "on", label: "On" }], + }; + const fast = { id: "fast", label: "Fast", type: "boolean" as const, currentValue: false }; + + const retained = retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [mode("code"), legacy, effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null }, + ], + currentModelId: "new-model", + configOptions: [mode("ask"), fast, effort("high")], + modelOptionIds: new Set(["effort"]), + }, + ); + expect(retained).toEqual( + Option.some({ + models: [], + currentModelId: "old-model", + configOptions: [mode("code"), fast, effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }), + ); + + // Drops reasoning when the probe disables it and returns none when no live option survives. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [legacy, effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null, reasoningEffort: null }, + ], + currentModelId: "new-model", + configOptions: [effort("high")], + modelOptionIds: new Set(["effort"]), + }, + ), + ).toEqual(Option.none()); + + // Drops model-specific options when the probe ran directly on that model without them. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [{ id: "old-model", name: "old-model", description: null }], + currentModelId: "old-model", + configOptions: [], + modelOptionIds: new Set(), + }, + ), + ).toEqual(Option.none()); + }); }); describe("acpRegistryAdvertisesModelCatalog", () => { @@ -1162,7 +1354,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { if (method === "initialize") { send({ id, - result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, + result: { protocolVersion: 1, agentCapabilities: { providers: {} }, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, }); } else if (method === "session/new") { const payload = JSON.parse(readFileSync(process.argv[2], "utf8")); @@ -1213,10 +1405,29 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); return; } - const availableModels = payload.map((entry) => + const entries = Array.isArray(payload) ? payload : payload.models; + const availableModels = entries.map((entry) => typeof entry === "string" ? { modelId: entry, name: entry } : entry, ); const hasMeta = availableModels.some((entry) => entry._meta !== undefined); + const configOptions = + !Array.isArray(payload) && Array.isArray(payload.configOptions) + ? payload.configOptions + : hasMeta + ? [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ] + : undefined; send({ id, result: { @@ -1225,23 +1436,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { currentModelId: availableModels[0]?.modelId, availableModels, }, - ...(hasMeta - ? { - configOptions: [ - { - id: "effort", - name: "Effort", - category: "thought_level", - type: "select", - currentValue: "high", - options: [ - { value: "low", name: "Low" }, - { value: "high", name: "High" }, - ], - }, - ], - } - : {}), + ...(configOptions === undefined ? {} : { configOptions }), }, }); send({ @@ -1499,48 +1694,99 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }); it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { - it.effect( - "picks up new models on a post-TTL refresh instead of reverting to an earlier session's catalog", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "acp-driver-periodic-", - }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const readyInspection = { + status: "ready" as const, + agentId: "test-agent", + version: "1.0.0", + distribution: "npx" as const, + }; - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", - }), - resolve: () => - Effect.succeed({ + const setupPeriodicDriver = (options: { + readonly prefix: string; + readonly initialModels: unknown; + readonly wrapCoordinator?: ( + coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"], + ) => AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"]; + readonly inspect?: () => AcpRegistrySupport.AcpRegistryInspection; + readonly onResolve?: () => Effect.Effect; + }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: options.prefix }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(options.initialModels)); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const effectiveCoordinator = + options.wrapCoordinator === undefined ? coordinator : options.wrapCoordinator(coordinator); + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + effectiveCoordinator, + ), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection(readyInspection), + inspect: () => Effect.sync(() => (options.inspect ? options.inspect() : readyInspection)), + resolve: () => + (options.onResolve ? options.onResolve() : Effect.void).pipe( + Effect.as({ distribution: "npx" as const, spawn: { command: process.execPath, args: [agentPath, modelsPath] }, }), - }), + ), + }), + ); + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, ); - - const waitForEnriched = () => - instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, + const writeModels = (payload: unknown) => + fileSystem.writeFileString(modelsPath, JSON.stringify(payload)); + const withBlockedForegroundStartup = (body: Effect.Effect) => + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const startup = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release))), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(entered); + const result = yield* body.pipe( + Effect.ensuring( + Deferred.succeed(release, undefined).pipe(Effect.andThen(Fiber.join(startup))), + ), ); + return result; + }); + return { + directory, + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + }; + }); + + it.effect( + "picks up new models on a post-TTL refresh, preserves surviving live option values, and drops removed or disabled options", + () => + Effect.gen(function* () { + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-periodic-", + initialModels: ["old-model", "other-model"], + }); const initial = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -1598,8 +1844,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (snapshot) => snapshot.models .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === - true && + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low" && snapshot.models .find((model) => model.slug === "other-model") ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === @@ -1614,23 +1860,20 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - sessionWithOptions("old-model", "high", { includeLegacy: true }), + sessionWithOptions("old-model", "low", { includeLegacy: true }), ); yield* Fiber.join(learnedEffort); // Upstream adds a model, removes the shared legacy option, and disables reasoning on other-model. - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify([ - "new-model", - "old-model", - { - modelId: "other-model", - name: "other-model", - _meta: { supportsReasoningEffort: false }, - }, - ]), - ); + yield* writeModels([ + "new-model", + "old-model", + { + modelId: "other-model", + name: "other-model", + _meta: { supportsReasoningEffort: false }, + }, + ]); yield* TestClock.adjust("16 minutes"); const postTtl = yield* waitForEnriched().pipe( @@ -1643,11 +1886,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "old-model", "other-model", ]); + // old-model keeps its live effort value (low) while legacy is dropped and other-model has no effort. expect( updated.models .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.map((option) => option.id), - ).toEqual(["effort"]); + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([["effort", "low"]]); expect( updated.models .find((model) => model.slug === "other-model") @@ -1658,33 +1902,36 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((model) => model.slug === "new-model") ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], ).toEqual(["effort"]); + // Coordinator retains live option values (with models stripped) for Copilot unsetOptionDefaults. + expect( + Option.map(yield* coordinator.getLiveConfiguration(identity.instanceId), (config) => ({ + models: config.models, + effort: config.configOptions.find((option) => option.id === "effort")?.currentValue, + })), + ).toEqual(Option.some({ models: [], effort: "low" })); - // A mid-session option update from a long-lived session (includeCatalog: false) must keep - // the newly probed models intact while updating the active model's learned options. + // A mid-session option update (includeCatalog: false) keeps the newly probed catalog intact. const effortUpdated = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.models .find((model) => model.slug === "old-model") ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") - ?.currentValue === "low", + ?.currentValue === "high", ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - sessionWithOptions("old-model", "low", { includeCatalog: false }), + sessionWithOptions("old-model", "high", { includeCatalog: false }), ); expect( Option.getOrThrow(yield* Fiber.join(effortUpdated)).models.map((model) => model.slug), ).toEqual(["new-model", "old-model", "other-model"]); - // Subsequent cached refresh must keep the cached catalog instead of re-probing or reverting to old session state. - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["unexpected-reprobe", "other-model"]), - ); + // Cached refresh must reuse the cached catalog without re-probing. + yield* writeModels(["unexpected-reprobe", "other-model"]); const nextCached = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); @@ -1694,7 +1941,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual(["new-model", "old-model", "other-model"]); // When a later post-TTL probe runs directly on old-model without effort, learned effort is dropped. - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "new-model"])); + yield* writeModels(["old-model", "new-model"]); yield* TestClock.adjust("16 minutes"); const droppedOnCurrent = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -1714,62 +1961,20 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); it.effect( - "retains accepted models across provisional probes, transient errors, and foreground startup, and drops them on sign-out or invalidation", + "retains accepted models across provisional probes while retrying on the short provisional TTL", () => Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "acp-driver-retention-", + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-provisional-", + initialModels: ["new-model", "old-model", "other-model"], }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["new-model", "old-model", "other-model"]), - ); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", - }), - resolve: () => - Effect.succeed({ - distribution: "npx" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, - }), - }), - ); - - const waitForEnriched = () => - instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - ); const initial = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - expect( - Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), - ).toEqual(["new-model", "old-model", "other-model"]); + yield* Fiber.join(initial); - // When a settled live catalog beats a provisional probe, the enrichment cache must store - // the winning live catalog (not the rejected provisional probe) so a subsequent options-only - // update and cached refresh within the 30s retry TTL do not regress to the placeholder. const liveCatalogApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.models.map((m) => m.slug).join() === "live-a,live-b", @@ -1788,10 +1993,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }); yield* Fiber.join(liveCatalogApplied); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify({ provisional: "placeholder" }), - ); + yield* writeModels({ provisional: "placeholder" }); yield* TestClock.adjust("16 minutes"); const afterProvisional = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -1807,6 +2009,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { configOptions: [], modelsFromModelSelect: false, }); + // Switch fixture to a winning multi-model catalog so a cache miss would diverge from live-a/live-b. + yield* writeModels(["unexpected-reprobe", "other-model"]); const cachedWithinRetryTtl = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); @@ -1817,11 +2021,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ), ).toEqual(["live-a", "live-b"]); - // A provisional probe must still use the short retry TTL even when it retains a multi-model catalog. - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), - ); + // After the 30s provisional retry TTL expires, refresh re-probes and adopts the settled catalog. + yield* writeModels(["new-model", "old-model", "other-model", "settled-model"]); yield* TestClock.adjust("1 minute"); const afterProvisionalRetry = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -1832,16 +2033,68 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (model) => model.slug, ), ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); + }), + ); - // A transient discovery failure after TTL expiry must preserve its warning/message even - // when an options-only live configuration exists, while keeping accepted models and live options. - const optionsBeforeFailure = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") - ?.currentValue === "low", + it.effect( + "preserves transient discovery warnings across options-only updates and ignores live updates when not installed", + () => + Effect.gen(function* () { + let inspectHandler = (): AcpRegistrySupport.AcpRegistryInspection => readyInspection; + const uninstalledLiveProcessed = yield* Deferred.make(); + let trackNextLiveUpdate = false; + const { + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-warning-", + initialModels: ["new-model", "old-model", "other-model"], + inspect: () => inspectHandler(), + wrapCoordinator: (base) => ({ + ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + onUpdate(configuration, revision).pipe( + Effect.tap(() => + trackNextLiveUpdate + ? Deferred.succeed(uninstalledLiveProcessed, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + options, + ), + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + const effortOption = (currentValue: "low" | "high") => ({ + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue, + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); + const optionsBeforeFailure = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low", ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), @@ -1849,27 +2102,13 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [], currentModelId: "old-model", - configOptions: [ - { - id: "effort", - label: "Effort", - type: "select", - currentValue: "low", - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], - }, - ], + configOptions: [effortOption("low")], modelOptionIds: ["effort"], modelsFromModelSelect: false, }); yield* Fiber.join(optionsBeforeFailure); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify({ fail: "Temporary discovery outage" }), - ); + yield* writeModels({ fail: "Temporary discovery outage" }); yield* TestClock.adjust("16 minutes"); const failedProbe = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.status === "warning"), @@ -1884,7 +2123,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "new-model", "old-model", "other-model", - "settled-model", ]); expect( warned.models @@ -1893,176 +2131,275 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.currentValue, ).toBe("low"); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), + // A subsequent options-only update must keep the transient warning status and message. + const updatedWhileWarned = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), ); - const recovered = yield* waitForEnriched().pipe( + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const stillWarned = Option.getOrThrow(yield* Fiber.join(updatedWhileWarned)); + expect(stillWarned.status).toBe("warning"); + expect(stillWarned.message).toBe(warned.message); + + // If re-inspection during enrichment reports the agent is not installed while the + // live watcher is still running, a live options-only update must neither flip status + // to ready nor overwrite acceptedCatalog with default. + const notFoundInspection: AcpRegistrySupport.AcpRegistryInspection = { + status: "not_found", + agentId: "test-agent", + }; + yield* TestClock.adjust("16 minutes"); + const uninstalled = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => !snapshot.installed), + Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + // First inspect is checkProvider (ready, so watcher stays active); second is enrichProvider (not_found). + let inspectCalls = 0; + inspectHandler = () => (++inspectCalls === 1 ? readyInspection : notFoundInspection); yield* instance.snapshot.refresh; - expect( - Option.getOrThrow(yield* Fiber.join(recovered)).models.map((model) => model.slug), - ).toEqual(["new-model", "old-model", "other-model", "settled-model"]); + const uninstalledSnap = Option.getOrThrow(yield* Fiber.join(uninstalled)); + expect(uninstalledSnap.installed).toBe(false); + expect(uninstalledSnap.status).toBe("error"); - // An unauthenticated post-TTL probe must clear accepted models so subsequent readiness - // refreshes do not flip between the signed-in catalog and default. - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify({ fail: "Sign in required", code: -32000 }), + // Publish an options-only update while the watcher is active on the uninstalled snapshot. + trackNextLiveUpdate = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [effortOption("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Deferred.await(uninstalledLiveProcessed); + trackNextLiveUpdate = false; + const afterUninstalledLive = yield* instance.snapshot.getSnapshot; + expect(afterUninstalledLive.installed).toBe(false); + expect(afterUninstalledLive.status).toBe("error"); + + // Direct readiness refresh while not_found also stays error/uninstalled despite live config. + inspectHandler = () => notFoundInspection; + yield* instance.snapshot.refresh; + const directNotFound = yield* instance.snapshot.getSnapshot; + expect(directNotFound.installed).toBe(false); + expect(directNotFound.status).toBe("error"); + + // Once installed again, acceptedCatalog still has the multi-model list during foreground startup. + inspectHandler = () => readyInspection; + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); + }), + ); + }), + ); + + it.effect( + "clears accepted state on unauthenticated probes (even with concurrent options updates), invalidation, and provider disable", + () => + Effect.gen(function* () { + const probeEntered = yield* Deferred.make(); + const releaseProbe = yield* Deferred.make(); + let gateNextResolve = false; + const { + directory, + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-clear-", + initialModels: ["new-model", "old-model", "other-model"], + onResolve: () => + Effect.gen(function* () { + if (gateNextResolve) { + gateNextResolve = false; + yield* Deferred.succeed(probeEntered, undefined); + yield* Deferred.await(releaseProbe); + } + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Unauthenticated post-TTL probe racing an options-only live update must still keep + // status: warning, auth: unauthenticated, sign-in message, and models: ["default"]. + yield* writeModels({ fail: "Sign in required", code: -32000 }); yield* TestClock.adjust("16 minutes"); + gateNextResolve = true; const signedOutProbe = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - const signedOut = Option.getOrThrow(yield* Fiber.join(signedOutProbe)); - expect(signedOut.models.map((model) => model.slug)).toEqual(["default"]); + yield* Deferred.await(probeEntered); - const startupEntered = yield* Deferred.make(); - const releaseStartup = yield* Deferred.make(); - const startup = yield* coordinator - .withForegroundStartup( - "test-agent", - Deferred.succeed(startupEntered, undefined).pipe( - Effect.andThen(Deferred.await(releaseStartup)), - ), - ) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* Deferred.await(startupEntered); + const optionsDuringAuthProbe = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "effort") === + true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(optionsDuringAuthProbe); - yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "default", - ]); - yield* Deferred.succeed(releaseStartup, undefined); - yield* Fiber.join(startup); + yield* Deferred.succeed(releaseProbe, undefined); + const signedOut = Option.getOrThrow(yield* Fiber.join(signedOutProbe)); + expect(signedOut.status).toBe("warning"); + expect(signedOut.auth.status).toBe("unauthenticated"); + expect(signedOut.message).toBeTruthy(); + expect(signedOut.models.map((model) => model.slug)).toEqual(["default"]); + expect(Option.isNone(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); - // Re-populate the catalog, then verify foreground startup keeps it and invalidation clears it. - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["new-model", "old-model", "other-model", "settled-model"]), + // Subsequent readiness refresh during foreground startup stays on default instead of flipping back. + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "default", + ]); + }), ); + + // Re-populate the catalog, then verify disableProvider clears acceptedCatalog so a + // provisional probe afterward does not stick to the disabled provider's models. + yield* writeModels(["new-model", "old-model", "other-model"]); const restored = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; yield* Fiber.join(restored); - const startupEntered2 = yield* Deferred.make(); - const releaseStartup2 = yield* Deferred.make(); - const startup2 = yield* coordinator - .withForegroundStartup( - "test-agent", - Deferred.succeed(startupEntered2, undefined).pipe( - Effect.andThen(Deferred.await(releaseStartup2)), - ), - ) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* Deferred.await(startupEntered2); - + yield* instance.acpSessionManagement!.disableProvider({ + cwd: directory, + providerId: "old-provider", + }); + yield* writeModels({ provisional: "placeholder" }); + const afterDisable = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "new-model", - "old-model", - "other-model", - "settled-model", - ]); + expect( + Option.getOrThrow(yield* Fiber.join(afterDisable)).models.map((model) => model.slug), + ).toEqual(["placeholder"]); - yield* instance.invalidateCaches ?? Effect.void; + // Re-populate, then verify invalidateCaches and auth.invalidate clear acceptedCatalog. + yield* writeModels(["new-model", "old-model", "other-model"]); + yield* TestClock.adjust("1 minute"); + const restored2 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "default", - ]); - - yield* Deferred.succeed(releaseStartup2, undefined); - yield* Fiber.join(startup2); + yield* Fiber.join(restored2); + + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "default", + ]); + }), + ); const restoredForAuthInvalidate = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; yield* Fiber.join(restoredForAuthInvalidate); - - const startupEntered3 = yield* Deferred.make(); - const releaseStartup3 = yield* Deferred.make(); - const startup3 = yield* coordinator - .withForegroundStartup( - "test-agent", - Deferred.succeed(startupEntered3, undefined).pipe( - Effect.andThen(Deferred.await(releaseStartup3)), - ), - ) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* Deferred.await(startupEntered3); - - yield* instance.auth?.invalidate ?? Effect.void; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "default", - ]); - - yield* Deferred.succeed(releaseStartup3, undefined); - yield* Fiber.join(startup3); + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.auth?.invalidate ?? Effect.void; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "default", + ]); + }), + ); }), ); - it.effect("keeps a live session catalog published while a post-TTL probe is in flight", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "acp-driver-inflight-", - }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const secondProbeEntered = yield* Deferred.make(); - const releaseSecondProbe = yield* Deferred.make(); - const secondProbeSettled = yield* Deferred.make(); - let gateNextResolve = false; - let secondProbeReleased = false; + it.effect( + "keeps a live session catalog published while a post-TTL probe is in flight and preserves explicit singleton provenance", + () => + Effect.gen(function* () { + const secondProbeEntered = yield* Deferred.make(); + const releaseSecondProbe = yield* Deferred.make(); + const secondProbeEnteredCommit = yield* Deferred.make(); + let gateNextResolve = false; + let secondProbeReleased = false; - const observedCoordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = - { - ...coordinator, - runBackgroundProbe: (agentId, effect) => - Effect.suspend(() => { - const armedBefore = gateNextResolve; - return coordinator - .runBackgroundProbe(agentId, effect) + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-inflight-", + initialModels: ["old-model", "other-model"], + wrapCoordinator: (base) => ({ + ...base, + getLiveConfigurationWithRevision: (instanceId) => + base + .getLiveConfigurationWithRevision(instanceId) .pipe( Effect.tap(() => - armedBefore && secondProbeReleased - ? Deferred.succeed(secondProbeSettled, undefined).pipe(Effect.asVoid) + secondProbeReleased + ? Deferred.succeed(secondProbeEnteredCommit, undefined).pipe(Effect.asVoid) : Effect.void, ), - ); - }), - }; - - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService( - AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, - observedCoordinator, - ), - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", + ), }), - resolve: () => + onResolve: () => Effect.gen(function* () { if (gateNextResolve) { gateNextResolve = false; @@ -2070,193 +2407,173 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.await(releaseSecondProbe); secondProbeReleased = true; } - return { - distribution: "npx" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, - }; }), - }), - ); + }); - const initial = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - yield* Fiber.join(initial); + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["old-model", "other-model", "stale-probe-model"]), - ); - yield* TestClock.adjust("16 minutes"); - gateNextResolve = true; - yield* instance.snapshot.refresh; - yield* Deferred.await(secondProbeEntered); + yield* writeModels(["old-model", "other-model", "stale-probe-model"]); + yield* TestClock.adjust("16 minutes"); + gateNextResolve = true; + yield* instance.snapshot.refresh; + yield* Deferred.await(secondProbeEntered); - const liveApplied = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.models.map((m) => m.slug).join() === "entitled-model"), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [{ id: "entitled-model", name: "Entitled", description: null }], - currentModelId: "entitled-model", - configOptions: [ - { - id: "effort", - label: "Effort", - type: "select", - currentValue: "high", - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], - }, - ], - modelOptionIds: ["effort"], - modelsFromModelSelect: true, - }); - yield* Fiber.join(liveApplied); + const liveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.map((m) => m.slug).join() === "entitled-model", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "entitled-model", name: "Entitled", description: null }], + currentModelId: "entitled-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + yield* Fiber.join(liveApplied); - yield* Deferred.succeed(releaseSecondProbe, undefined); - // Wait for the competing probe's commit-or-discard step to settle before asserting or refreshing. - yield* Deferred.await(secondProbeSettled); - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "entitled-model", - ]); - expect( - Option.map( - yield* coordinator.getLiveConfiguration(identity.instanceId), - (config) => config.currentModelId, - ), - ).toEqual(Option.some("entitled-model")); - yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "entitled-model", - ]); + yield* Deferred.succeed(releaseSecondProbe, undefined); + // Wait for the competing probe to enter commit (holding liveSnapshotSemaphore), then + // wait for a semaphore-serialized command publication so commit has fully released it. + yield* Deferred.await(secondProbeEnteredCommit); + const commitReleased = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "commit-settled"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "commit-settled" }], + skills: [], + }); + yield* Fiber.join(commitReleased); - // A subsequent provisional single-model live update must not replace the explicit singleton - // catalog, overwrite its model-specific options, or downgrade its provenance. - const provisionalProcessed = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((model) => model.slug === "entitled-model") - ?.capabilities?.optionDescriptors?.some((option) => option.id === "mode") === true, - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], - currentModelId: "live-placeholder", - configOptions: [ - { - id: "mode", - label: "Mode", - type: "select", - currentValue: "code", - options: [{ id: "code", label: "Code" }], - }, - { - id: "effort", - label: "Effort", - type: "select", - currentValue: "on", - options: [ - { id: "off", label: "Off" }, - { id: "on", label: "On" }, - ], - }, - ], - modelOptionIds: ["effort"], - modelsFromModelSelect: false, - }); - const retainedAfterProvisional = Option.getOrThrow(yield* Fiber.join(provisionalProcessed)); - expect(retainedAfterProvisional.models.map((model) => model.slug)).toEqual([ - "entitled-model", - ]); - expect( - retainedAfterProvisional.models - .find((model) => model.slug === "entitled-model") - ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort"), - ).toMatchObject({ - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], - }); + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); + expect( + Option.map( + yield* coordinator.getLiveConfiguration(identity.instanceId), + (config) => config.currentModelId, + ), + ).toEqual(Option.some("entitled-model")); + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify({ provisional: "placeholder" })); - yield* TestClock.adjust("16 minutes"); - const afterProvisionalProbe = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - expect( - Option.getOrThrow(yield* Fiber.join(afterProvisionalProbe)).models.map( - (model) => model.slug, - ), - ).toEqual(["entitled-model"]); - }), + // A subsequent provisional single-model live update must not replace the explicit singleton + // catalog, overwrite its model-specific options, or downgrade its provenance. + const provisionalProcessed = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "entitled-model") + ?.capabilities?.optionDescriptors?.some((option) => option.id === "mode") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "live-placeholder", name: "Live Placeholder", description: null }], + currentModelId: "live-placeholder", + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "code", + options: [{ id: "code", label: "Code" }], + }, + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "on", + options: [ + { id: "off", label: "Off" }, + { id: "on", label: "On" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const retainedAfterProvisional = Option.getOrThrow(yield* Fiber.join(provisionalProcessed)); + expect(retainedAfterProvisional.models.map((model) => model.slug)).toEqual([ + "entitled-model", + ]); + expect( + retainedAfterProvisional.models + .find((model) => model.slug === "entitled-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort"), + ).toMatchObject({ + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); + + yield* writeModels({ provisional: "placeholder" }); + yield* TestClock.adjust("16 minutes"); + const afterProvisionalProbe = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterProvisionalProbe)).models.map( + (model) => model.slug, + ), + ).toEqual(["entitled-model"]); + }), ); it.effect( - "commits a fresh post-TTL catalog when only an options-only live update arrives in flight", + "commits a fresh post-TTL catalog when only an options-only live update arrives in flight while enforcing disabled reasoning", () => Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "acp-driver-inflight-options-", - }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const secondProbeEntered = yield* Deferred.make(); const releaseSecondProbe = yield* Deferred.make(); let gateNextResolve = false; - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", + const { + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-inflight-options-", + initialModels: ["old-model", "other-model"], + onResolve: () => + Effect.gen(function* () { + if (gateNextResolve) { + gateNextResolve = false; + yield* Deferred.succeed(secondProbeEntered, undefined); + yield* Deferred.await(releaseSecondProbe); + } }), - resolve: () => - Effect.gen(function* () { - if (gateNextResolve) { - gateNextResolve = false; - yield* Deferred.succeed(secondProbeEntered, undefined); - yield* Deferred.await(releaseSecondProbe); - } - return { - distribution: "npx" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, - }; - }), - }), - ); - - const waitForEnriched = () => - instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - ); + }); const initial = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -2264,10 +2581,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(initial); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["old-model", "other-model", "new-model"]), - ); + // Fresh probe disables reasoning on old-model while adding new-model. + yield* writeModels([ + { modelId: "old-model", name: "old-model", _meta: { supportsReasoningEffort: false } }, + "other-model", + "new-model", + ]); yield* TestClock.adjust("16 minutes"); gateNextResolve = true; yield* instance.snapshot.refresh; @@ -2278,8 +2597,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (snapshot) => snapshot.models .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") - ?.currentValue === "low", + ?.capabilities?.optionDescriptors?.find((option) => option.id === "mode") + ?.currentValue === "plan", ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), @@ -2288,10 +2607,21 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { models: [], currentModelId: "old-model", configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [ + { id: "code", label: "Code" }, + { id: "plan", label: "Plan" }, + ], + }, { id: "effort", label: "Effort", type: "select", + role: "reasoning", currentValue: "low", options: [ { id: "low", label: "Low" }, @@ -2314,39 +2644,26 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "other-model", "new-model", ]); + // Unrelated live option (mode) stays applied while disabled reasoning (effort) stays stripped. expect( updated.models .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") - ?.currentValue, - ).toBe("low"); + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([["mode", "plan"]]); // Verify the fresh catalog was saved to acceptedCatalog (survives skipped readiness) and cache. - const startupEntered = yield* Deferred.make(); - const releaseStartup = yield* Deferred.make(); - const startup = yield* coordinator - .withForegroundStartup( - "test-agent", - Deferred.succeed(startupEntered, undefined).pipe( - Effect.andThen(Deferred.await(releaseStartup)), - ), - ) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* Deferred.await(startupEntered); - - yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ - "old-model", - "other-model", - "new-model", - ]); - yield* Deferred.succeed(releaseStartup, undefined); - yield* Fiber.join(startup); - - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify(["unexpected-reprobe", "other-model"]), + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + }), ); + + yield* writeModels(["unexpected-reprobe", "other-model"]); const cached = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); yield* instance.snapshot.refresh; expect( diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index ae67bf2e9c398..b6786144097c3 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -90,12 +90,16 @@ interface AcceptedAcpRegistryCatalog { readonly models: ReadonlyArray; readonly builtInModelCount: number; readonly modelsFromModelSelect: boolean; + readonly reasoningDisabledModelSlugs: ReadonlySet; } +const EMPTY_SLUG_SET: ReadonlySet = new Set(); + const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { models: [], builtInModelCount: 0, modelsFromModelSelect: false, + reasoningDisabledModelSlugs: EMPTY_SLUG_SET, }; function isExplicitSingletonCatalog(catalog: { @@ -152,8 +156,16 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly customModels: ReadonlyArray; readonly now: number; readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; }): AcpRegistryEnrichmentCache { - const { cache, configuration, customModels, now, preserveSingleModelCatalog } = input; + const { + cache, + configuration, + customModels, + now, + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + } = input; if (cache.entry === null) { // Only advance the cache epoch when the live session discovered a catalog // so an options-only update cannot discard an in-flight initial probe. @@ -164,7 +176,7 @@ export function updateAcpRegistryEnrichmentCache(input: { configuration, customModels, undefined, - { preserveSingleModelCatalog }, + { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, ); if (Equal.equals(provider, cache.entry.provider)) return cache; const previousBuiltIn = cache.entry.provider.models.filter((model) => !model.isCustom); @@ -210,8 +222,6 @@ const makeUnsupportedTextGeneration = (): ProviderTextGeneration => { }; }; -const EMPTY_SLUG_SET: ReadonlySet = new Set(); - function isModelSpecificDescriptor( descriptor: ProviderOptionDescriptor, modelOptionIds: ReadonlySet, @@ -239,6 +249,7 @@ function updateLearnedModelsFromLive( learned: ReadonlyArray, nextModels: ReadonlyArray, configuration: AcpRegistryLiveConfiguration, + disabledReasoningSlugs: ReadonlySet = EMPTY_SLUG_SET, ): ReadonlyArray { const modelOptionIds = new Set(configuration.modelOptionIds ?? []); const learnedBySlug = new Map( @@ -251,7 +262,8 @@ function updateLearnedModelsFromLive( const isCurrentModel = configuration.currentModelId !== null && model.slug === configuration.currentModelId; const hasAdvertisedReasoning = configuredById.get(model.slug)?.reasoningEffort !== undefined; - if (!isCurrentModel && !hasAdvertisedReasoning) continue; + const isReasoningDisabled = disabledReasoningSlugs.has(model.slug); + if (!isCurrentModel && !hasAdvertisedReasoning && !isReasoningDisabled) continue; const specific = (model.capabilities?.optionDescriptors ?? []).filter((descriptor) => isModelSpecificDescriptor(descriptor, modelOptionIds), ); @@ -272,6 +284,105 @@ function updateLearnedModelsFromLive( return changed ? Array.from(learnedBySlug.values()) : learned; } +function overlayLiveOptionValue( + probed: ProviderOptionDescriptor, + live: ProviderOptionDescriptor | undefined, +): ProviderOptionDescriptor { + if (live === undefined || live.type !== probed.type || live.currentValue === undefined) { + return probed; + } + if (probed.type === "boolean") { + return { ...probed, currentValue: live.currentValue as boolean }; + } + return probed.options.some((option) => option.id === live.currentValue) + ? { ...probed, currentValue: live.currentValue as string } + : probed; +} + +/** + * Keeps live session option values that still apply after a superseding probe replaces + * the catalog, while dropping removed shared options and dropped/disabled model options. + */ +export function retainAcpRegistryLiveOptionsAfterProbe( + live: AcpRegistryLiveConfiguration, + probe: { + readonly models: ReadonlyArray; + readonly currentModelId: string | null; + readonly configOptions: ReadonlyArray; + readonly modelOptionIds: ReadonlySet; + }, +): Option.Option { + if (live.configOptions.length === 0) return Option.none(); + const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); + const liveModelOptionIds = new Set(live.modelOptionIds ?? []); + const probedModelById = new Map(probe.models.map((model) => [model.id, model])); + const nextCurrentModelId = + live.currentModelId !== null && probedModelById.has(live.currentModelId) + ? live.currentModelId + : null; + const currentProbedModel = + nextCurrentModelId === null ? undefined : probedModelById.get(nextCurrentModelId); + + let preservedAnyLiveOption = false; + const sharedDescriptors: Array = []; + for (const descriptor of probe.configOptions) { + if (isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; + const liveMatch = liveById.get(descriptor.id); + if (liveMatch !== undefined) preservedAnyLiveOption = true; + sharedDescriptors.push(overlayLiveOptionValue(descriptor, liveMatch)); + } + const sharedIds = new Set(sharedDescriptors.map((descriptor) => descriptor.id)); + + const modelDescriptors: Array = []; + if (nextCurrentModelId !== null) { + const reasoningDisabled = currentProbedModel?.reasoningEffort === null; + if (nextCurrentModelId === probe.currentModelId) { + for (const descriptor of probe.configOptions) { + if (sharedIds.has(descriptor.id)) continue; + if (reasoningDisabled && descriptor.type === "select" && descriptor.role === "reasoning") { + continue; + } + const liveMatch = liveById.get(descriptor.id); + if (liveMatch !== undefined) preservedAnyLiveOption = true; + modelDescriptors.push(overlayLiveOptionValue(descriptor, liveMatch)); + } + } else { + const advertisedReasoning = currentProbedModel?.reasoningEffort; + let addedAdvertisedReasoning = false; + for (const descriptor of live.configOptions) { + if (sharedIds.has(descriptor.id)) continue; + if (!isModelSpecificDescriptor(descriptor, liveModelOptionIds)) continue; + if (descriptor.type === "select" && descriptor.role === "reasoning") { + if (reasoningDisabled) continue; + if (advertisedReasoning != null) { + if (!addedAdvertisedReasoning) { + modelDescriptors.push(overlayLiveOptionValue(advertisedReasoning, descriptor)); + addedAdvertisedReasoning = true; + preservedAnyLiveOption = true; + } + continue; + } + } + modelDescriptors.push(descriptor); + preservedAnyLiveOption = true; + } + if (advertisedReasoning != null && !addedAdvertisedReasoning) { + modelDescriptors.push(advertisedReasoning); + } + } + } + + const configOptions = [...sharedDescriptors, ...modelDescriptors]; + if (!preservedAnyLiveOption || configOptions.length === 0) return Option.none(); + return Option.some({ + models: [], + currentModelId: nextCurrentModelId, + configOptions, + modelOptionIds: modelDescriptors.map((descriptor) => descriptor.id), + modelsFromModelSelect: false, + }); +} + function mergeLearnedModelOptions( models: ReadonlyArray, learned: ReadonlyArray, @@ -564,12 +675,40 @@ export function applyAcpRegistryAvailableCommands( }); } +function stripReasoningForDisabledModels( + models: ReadonlyArray, + disabledReasoningSlugs: ReadonlySet, +): ReadonlyArray { + if (disabledReasoningSlugs.size === 0) return models; + let changed = false; + const next = models.map((model) => { + if (model.isCustom || !disabledReasoningSlugs.has(model.slug)) return model; + const descriptors = model.capabilities?.optionDescriptors ?? []; + const filtered = descriptors.filter( + (descriptor) => descriptor.type !== "select" || descriptor.role !== "reasoning", + ); + if (filtered.length === descriptors.length) return model; + changed = true; + return { + ...model, + capabilities: + filtered.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: filtered }), + }; + }); + return changed ? next : models; +} + export function applyAcpRegistryLiveConfiguration( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, customModels: ReadonlyArray, previousModels: ReadonlyArray = provider.models, - options?: { readonly preserveSingleModelCatalog?: boolean | undefined }, + options?: { + readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; // session/load may omit models (Kimi returns `{}`); keep the probed list @@ -585,6 +724,14 @@ export function applyAcpRegistryLiveConfiguration( const useLiveCatalog = configuration.models.length > 1 || (configuration.models.length === 1 && !liveCatalogIsProvisional); + const disabledReasoningSlugs: ReadonlySet = useLiveCatalog + ? EMPTY_SLUG_SET + : (configuration.reasoningDisabledModelIds?.length ?? 0) === 0 + ? (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET) + : new Set([ + ...(options?.reasoningDisabledModelSlugs ?? []), + ...(configuration.reasoningDisabledModelIds ?? []), + ]); const liveCurrentModelInProbed = configuration.currentModelId !== null && probedModels.some((model) => model.slug === configuration.currentModelId); @@ -613,6 +760,7 @@ export function applyAcpRegistryLiveConfiguration( id: model.slug, name: model.name, description: null, + ...(disabledReasoningSlugs.has(model.slug) ? { reasoningEffort: null } : {}), })), currentModelId: dropUnmatchedModelOptions ? configuration.currentModelId @@ -621,7 +769,10 @@ export function applyAcpRegistryLiveConfiguration( }; const nextModels = !useLiveCatalog && effectiveConfigOptions.length === 0 - ? withAcpRegistryDefaultModel(provider.models, selectedProbedModelId) + ? stripReasoningForDisabledModels( + withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), + disabledReasoningSlugs, + ) : modelsFromDiscovery( discovery, customModels, @@ -751,6 +902,8 @@ export function buildCheckedAcpRegistrySnapshot( interface DetailedAcpRegistryProviderStatus { readonly provider: ServerProvider; + readonly probedModels: ReadonlyArray; + readonly probedConfigOptions: ReadonlyArray; readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; readonly probedCurrentModelId: string | null; @@ -775,6 +928,8 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( const checkedAt = DateTime.formatIso(yield* DateTime.now); const withoutProbe = (provider: ServerProvider): DetailedAcpRegistryProviderStatus => ({ provider, + probedModels: [], + probedConfigOptions: [], probedModelCount: 0, probedModelsFromModelSelect: false, probedCurrentModelId: null, @@ -831,6 +986,8 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( inspection: inspected.success, probe: probed.success, }), + probedModels: probed.success.probe.models, + probedConfigOptions: probed.success.probe.configOptions, probedModelCount: probed.success.probe.models.length, probedModelsFromModelSelect: probed.success.modelsFromModelSelect === true, probedCurrentModelId: probed.success.probe.currentModelId, @@ -987,33 +1144,51 @@ export const AcpRegistryDriver: ProviderDriver | undefined; + }, ) => - (options?.preserveSingleModelCatalog !== undefined - ? Effect.succeed(options.preserveSingleModelCatalog) - : Ref.get(acceptedCatalog).pipe(Effect.map(isExplicitSingletonCatalog)) - ).pipe( - Effect.flatMap((preserveSingleModelCatalog) => - Ref.modify(learnedModels, (learned) => { + Ref.get(acceptedCatalog).pipe( + Effect.flatMap((accepted) => { + const preserveSingleModelCatalog = + options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); + const reasoningDisabledModelSlugs = + options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; + const disabledForLearning = + configuration.models.length > 0 + ? EMPTY_SLUG_SET + : (configuration.reasoningDisabledModelIds?.length ?? 0) === 0 + ? reasoningDisabledModelSlugs + : new Set([ + ...reasoningDisabledModelSlugs, + ...(configuration.reasoningDisabledModelIds ?? []), + ]); + return Ref.modify(learnedModels, (learned) => { const next = applyAcpRegistryLiveConfiguration( provider, configuration, effectiveConfig.customModels, learned.length > 0 ? learned : provider.models, - { preserveSingleModelCatalog }, + { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, ); - return [next, updateLearnedModelsFromLive(learned, next.models, configuration)]; - }), - ), + return [ + next, + updateLearnedModelsFromLive(learned, next.models, configuration, disabledForLearning), + ]; + }); + }), ); const lastObservedLiveRevision = yield* Ref.make(0); const liveSnapshotSemaphore = yield* Semaphore.make(1); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, options?: { + readonly applyLiveModels?: boolean; readonly recordLiveRevision?: boolean; readonly fallbackToAcceptedModels?: boolean; readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; readonly preserveStatus?: boolean; }, ) { @@ -1051,25 +1226,33 @@ export const AcpRegistryDriver: ProviderDriver - Option.match(liveConfiguration.configuration, { - onNone: () => Effect.succeed(withBaseModels), - onSome: (configuration) => - applyLiveConfiguration(withBaseModels, configuration, { - preserveSingleModelCatalog: options?.preserveSingleModelCatalog, - }).pipe( - Effect.map((applied) => - options?.preserveStatus === true - ? { - ...applied, - status: withBaseModels.status, - ...(withBaseModels.message === undefined - ? {} - : { message: withBaseModels.message }), - } - : applied, + Option.match( + options?.applyLiveModels === false || + !withBaseModels.enabled || + !withBaseModels.installed + ? Option.none() + : liveConfiguration.configuration, + { + onNone: () => Effect.succeed(withBaseModels), + onSome: (configuration) => + applyLiveConfiguration(withBaseModels, configuration, { + preserveSingleModelCatalog: options?.preserveSingleModelCatalog, + reasoningDisabledModelSlugs: options?.reasoningDisabledModelSlugs, + }).pipe( + Effect.map((applied) => + options?.preserveStatus === true + ? { + ...applied, + status: withBaseModels.status, + ...(withBaseModels.message === undefined + ? {} + : { message: withBaseModels.message }), + } + : applied, + ), ), - ), - }), + }, + ), ), Effect.map((withConfiguration) => applyAcpRegistryUrlAuthAction(withConfiguration, authAction), @@ -1142,6 +1325,8 @@ export const AcpRegistryDriver: ProviderDriver - liveSnapshotSemaphore.withPermit( - Effect.uninterruptible( - Effect.gen(function* () { - const current = yield* Ref.get(enrichmentCache); - if (current.generation !== generation) return; - let resolved = provider; - if (fresh && provider.status === "ready") { - const liveSnapshot = Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision( - instanceId, - ) - : { - configuration: Option.none(), - revision: 0, - catalogRevision: 0, - clearedThroughRevision: 0, - }; - const accepted = yield* Ref.get(acceptedCatalog); - const liveCatalogUsed = Option.match(liveSnapshot.configuration, { - onNone: () => false, - onSome: (configuration) => - liveConfigurationReplacesAcceptedCatalog(configuration, accepted), - }); - const incumbent = - liveCatalogUsed && Option.isSome(liveSnapshot.configuration) - ? { - modelCount: liveSnapshot.configuration.value.models.length, - modelsFromModelSelect: - liveSnapshot.configuration.value.modelsFromModelSelect === true, - } - : { - modelCount: accepted.builtInModelCount, - modelsFromModelSelect: accepted.modelsFromModelSelect, - }; - const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ - probedModelCount, - probedModelsFromModelSelect, - liveModelCount: incumbent.modelCount, - liveModelsFromModelSelect: incumbent.modelsFromModelSelect, + const commitEnrichment = ({ + provider, + generation, + fresh, + probeStartLiveRevision, + probeStartCatalogRevision, + probedModels, + probedConfigOptions, + probedModelCount, + probedModelsFromModelSelect, + probedCurrentModelId, + probedModelOptionIds, + reasoningDisabledModelSlugs, + }: Effect.Success>) => + Effect.uninterruptible( + liveSnapshotSemaphore.withPermit( + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + const liveSnapshot = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId) + : AcpRegistryRuntimeCoordinator.EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + if ( + current.generation !== generation || + (fresh && liveSnapshot.catalogRevision !== probeStartCatalogRevision) + ) { + return; + } + let resolved = provider; + if (fresh && provider.status === "ready") { + const accepted = yield* Ref.get(acceptedCatalog); + const liveCatalog = Option.filter(liveSnapshot.configuration, (configuration) => + liveConfigurationReplacesAcceptedCatalog(configuration, accepted), + ); + const incumbent = Option.match(liveCatalog, { + onSome: (configuration) => ({ + modelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, + }), + onNone: () => ({ + modelCount: accepted.builtInModelCount, + modelsFromModelSelect: accepted.modelsFromModelSelect, + }), + }); + const probeSupersedesLiveCatalog = acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount, + probedModelsFromModelSelect, + liveModelCount: incumbent.modelCount, + liveModelsFromModelSelect: incumbent.modelsFromModelSelect, + }); + // A fresh non-provisional probe supersedes any live session catalog observed before it started. + const cleared = probeSupersedesLiveCatalog + ? Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + { + catalogRevision: probeStartCatalogRevision, + retainPreProbeConfiguration: (live) => + retainAcpRegistryLiveOptionsAfterProbe(live, { + models: probedModels, + currentModelId: probedCurrentModelId, + configOptions: probedConfigOptions, + modelOptionIds: probedModelOptionIds, + }), + }, + ) + : true + : false; + if ( + !probeSupersedesLiveCatalog && + Option.isNone(liveCatalog) && + accepted.models.length > 0 + ) { + resolved = { ...provider, models: accepted.models }; + } else { + const models = yield* Ref.modify(learnedModels, (learned) => { + const merged = mergeLearnedModelOptions(provider.models, learned, { + currentModelId: probedCurrentModelId, + reasoningDisabledModelSlugs, }); - // A fresh non-provisional probe supersedes any live session catalog observed before it started. - const cleared = probeSupersedesLiveCatalog - ? Option.isSome(runtimeCoordinator) - ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( - instanceId, - probeStartLiveRevision, - { catalogRevision: probeStartCatalogRevision }, - ) - : true - : false; - if ( - !probeSupersedesLiveCatalog && - !liveCatalogUsed && - accepted.models.length > 0 - ) { - resolved = { ...provider, models: accepted.models }; - } else { - const models = yield* Ref.modify(learnedModels, (learned) => { - const merged = mergeLearnedModelOptions(provider.models, learned, { + const nextLearned = cleared + ? updateLearnedModelsFromProbe(learned, provider.models, { currentModelId: probedCurrentModelId, + modelOptionIds: probedModelOptionIds, reasoningDisabledModelSlugs, - }); - const nextLearned = cleared - ? updateLearnedModelsFromProbe(learned, provider.models, { - currentModelId: probedCurrentModelId, - modelOptionIds: probedModelOptionIds, - reasoningDisabledModelSlugs, - }) - : learned; - return [merged, nextLearned] as const; - }); - resolved = models === provider.models ? provider : { ...provider, models }; - } - const published = yield* withLiveRuntimeState(resolved, { - preserveSingleModelCatalog: - probeSupersedesLiveCatalog && - isExplicitSingletonCatalog({ - builtInModelCount: probedModelCount, - modelsFromModelSelect: probedModelsFromModelSelect, }) - ? true - : undefined, - }); - if ( - cleared || - (!probeSupersedesLiveCatalog && - liveSnapshot.catalogRevision === probeStartCatalogRevision) - ) { - const completedAt = yield* Clock.currentTimeMillis; - yield* Ref.set(enrichmentCache, { - ...current, - entry: { - // Cache the catalog that won reconciliation (not a rejected provisional probe) - // while keeping the retry TTL computed from the fresh probe result. - provider: !probeSupersedesLiveCatalog - ? { ...resolved, models: published.models } - : resolved, - expiresAt: completedAt + acpRegistryProbeTtlMs(provider), - }, - }); - } - if (cleared) { - yield* Ref.set(acceptedCatalog, { - models: resolved.models, - builtInModelCount: probedModelCount, - modelsFromModelSelect: probedModelsFromModelSelect, - }); - } - yield* publishSnapshot(published); - return; - } - if (fresh && resolved.auth.status === "unauthenticated") { - yield* Ref.set(enrichmentCache, { ...current, entry: null }); - yield* clearLearnedModels; - yield* clearAcceptedCatalog; - if (Option.isSome(runtimeCoordinator)) { - yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( - instanceId, - probeStartLiveRevision, - ); - } - } - const preserveTransientFailure = - fresh && - resolved.status !== "ready" && - resolved.auth.status !== "unauthenticated"; - yield* withLiveRuntimeState(resolved, { - fallbackToAcceptedModels: preserveTransientFailure, - preserveStatus: preserveTransientFailure, - }).pipe(Effect.flatMap(publishSnapshot)); - }), - ), - ), - ), - ); + : learned; + return [merged, nextLearned] as const; + }); + resolved = models === provider.models ? provider : { ...provider, models }; + } + const published = yield* withLiveRuntimeState(resolved, { + preserveSingleModelCatalog: + probeSupersedesLiveCatalog && + isExplicitSingletonCatalog({ + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + }) + ? true + : undefined, + reasoningDisabledModelSlugs: cleared ? reasoningDisabledModelSlugs : undefined, + }); + if (cleared || !probeSupersedesLiveCatalog) { + const completedAt = yield* Clock.currentTimeMillis; + yield* Ref.set(enrichmentCache, { + ...current, + entry: { + // Cache the winning catalog while keeping the retry TTL from the fresh probe. + provider: !probeSupersedesLiveCatalog + ? { ...resolved, models: published.models } + : resolved, + expiresAt: completedAt + acpRegistryProbeTtlMs(provider), + }, + }); + } + if (cleared) { + yield* Ref.set(acceptedCatalog, { + models: resolved.models, + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + reasoningDisabledModelSlugs, + }); + } + yield* publishSnapshot(published); + return; + } + const isUnauthenticated = fresh && resolved.auth.status === "unauthenticated"; + if (isUnauthenticated) { + yield* Ref.set(enrichmentCache, { ...current, entry: null }); + yield* clearLearnedModels; + yield* clearAcceptedCatalog; + if (Option.isSome(runtimeCoordinator)) { + yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + { catalogRevision: probeStartCatalogRevision, clearOptions: true }, + ); + } + } + const preserveTransientFailure = + fresh && resolved.status !== "ready" && !isUnauthenticated; + yield* withLiveRuntimeState(resolved, { + applyLiveModels: !isUnauthenticated, + fallbackToAcceptedModels: preserveTransientFailure, + preserveStatus: preserveTransientFailure, + }).pipe(Effect.flatMap(publishSnapshot)); + }), + ), + ); const publishEnrichment = ( Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( effectiveConfig.source === "local" ? `local:${instanceId}` : effectiveConfig.agentId, - probeAndCommit, + enrichProviderCached(snapshot), ) - : probeAndCommit - ).pipe(Effect.asVoid); + : enrichProviderCached(snapshot).pipe(Effect.asSome) + ).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.void, + onSome: commitEnrichment, + }), + ), + ); if (Option.isNone(runtimeCoordinator)) return publishEnrichment; const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( @@ -1381,23 +1575,59 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) + .map((model) => model.id), + ) + : (configuration.reasoningDisabledModelIds?.length ?? 0) > 0 + ? new Set([ + ...acceptedBefore.reasoningDisabledModelSlugs, + ...(configuration.reasoningDisabledModelIds ?? []), + ]) + : acceptedBefore.reasoningDisabledModelSlugs; + if (current.auth.status !== "unauthenticated" || replacesCatalog) { yield* Ref.update(acceptedCatalog, (previous) => - liveConfigurationReplacesAcceptedCatalog(configuration, previous) + replacesCatalog ? { models: next.models, builtInModelCount: configuration.models.length, modelsFromModelSelect: configuration.modelsFromModelSelect === true, + reasoningDisabledModelSlugs: nextReasoningDisabled, } - : previous.models.length > 0 + : current.status === "ready" && previous.models.length > 0 ? { ...previous, models: next.models, + reasoningDisabledModelSlugs: nextReasoningDisabled, } : previous, ); @@ -1410,6 +1640,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe(Effect.tap(() => clearCachedState())), disableProvider: ({ cwd, providerId }) => provideAcpManagementServices( disableAcpRegistryProvider({ @@ -1599,7 +1830,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe(Effect.tap(() => clearCachedState())), logout: (cwd) => { const logout = logoutAcpRegistry({ instanceId, diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 12514532b8413..f6d47a1181db4 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -34,6 +34,7 @@ import { parseSessionModeState, } from "@t3tools/provider-acp/server/runtimeModel"; import { + ACP_MAX_CATALOG_MODELS, acpProviderOptionDescriptors, flattenSelectChoices, isAcpThoughtLevelOption, @@ -42,7 +43,7 @@ import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator. import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; const MAX_AUTH_METHODS = 32; -const MAX_MODELS = 256; +const MAX_MODELS = ACP_MAX_CATALOG_MODELS; const MAX_ID_LENGTH = 128; const MAX_NAME_LENGTH = 160; const MAX_DESCRIPTION_LENGTH = 1_024; @@ -213,6 +214,8 @@ export interface AcpRegistryLiveConfiguration { // A single model from an explicit select is the agent's deliberate catalog // (e.g. an entitlement change), not a cold-start placeholder. readonly modelsFromModelSelect?: boolean; + // Carries explicit supportsReasoningEffort: false metadata on options-only updates. + readonly reasoningDisabledModelIds?: ReadonlyArray; } export function normalizeAcpRegistryLiveConfiguration( @@ -251,22 +254,32 @@ export function normalizeAcpRegistryLiveConfiguration( ); return reasoningEffort === undefined ? model : { ...model, reasoningEffort }; }); - const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }); + const currentModel = + boundedCurrentModelId === null + ? undefined + : advertisedModels.find((model) => model.id === boundedCurrentModelId); + const stripCurrentReasoning = !includeCatalog && currentModel?.reasoningEffort === null; + const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( + (descriptor) => + !stripCurrentReasoning || descriptor.type !== "select" || descriptor.role !== "reasoning", + ); const modelOptionIds = new Set( configOptions .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config") .map((option) => option.id), ); + const reasoningDisabledModelIds = !includeCatalog + ? advertisedModels.filter((model) => model.reasoningEffort === null).map((model) => model.id) + : []; return { models: includeCatalog ? advertisedModels : [], - currentModelId: advertisedModels.some((model) => model.id === boundedCurrentModelId) - ? boundedCurrentModelId - : null, + currentModelId: currentModel === undefined ? null : currentModel.id, configOptions: descriptors, modelOptionIds: descriptors .filter((descriptor) => modelOptionIds.has(descriptor.id)) .map((descriptor) => descriptor.id), modelsFromModelSelect: includeCatalog && modelOption !== undefined, + ...(reasoningDisabledModelIds.length > 0 ? { reasoningDisabledModelIds } : {}), }; } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 96b92098fca69..26f5370ee82d9 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -112,6 +112,7 @@ import { import { ACP_EMPTY_OPTION_VALUE, ACP_SESSION_MODE_OPTION_ID, + acpSessionCatalogKey, flattenSelectChoices, } from "./sessionConfig.ts"; import * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; @@ -2286,46 +2287,34 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.make(null); // Track the model catalog last published for the active session so mid-session // option updates do not re-advertise a frozen catalog over a newer periodic probe. - const lastPublishedCatalogKey = yield* Ref.make(null); - const sessionCatalogKey = ( - configOptions: ReadonlyArray, - modelState: EffectAcpSchema.SessionModelState | null | undefined, - ): string => { - const modelOption = findModelConfigOption(configOptions); - if (modelOption?.type === "select") { - return JSON.stringify([ - "select", - flattenSelectChoices(modelOption.options).map((choice) => [ - choice.value, - choice.name, - choice.description ?? null, - ]), - ]); - } - return JSON.stringify([ - "models", - (modelState?.availableModels ?? []).map((model) => [ - model.modelId, - model.name, - model.description ?? null, - ]), - ]); - }; + const lastPublishedCatalogKey = yield* Ref.make<{ + readonly epoch: number; + readonly key: string | null; + }>({ epoch: 0, key: null }); + const resetPublishedCatalogKey = Ref.update(lastPublishedCatalogKey, (current) => ({ + epoch: current.epoch + 1, + key: null, + })); + const sessionConfigurationPublishPermit = yield* Semaphore.make(1); const publishSessionConfiguration = Effect.fn("AcpAdapterV2.publishSessionConfiguration")( - function* ( - configOptions: ReadonlyArray, - modeState: AcpSessionModeState | undefined, - modelState: EffectAcpSchema.SessionModelState | null | undefined, - ) { + function* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { if (flavor.onSessionConfigurationUpdate === undefined) return; - const catalogKey = sessionCatalogKey(configOptions, modelState); - const includeCatalog = yield* Ref.modify(lastPublishedCatalogKey, (previous) => [ - previous !== catalogKey, - catalogKey, - ]); - yield* flavor.onSessionConfigurationUpdate(configOptions, modeState, modelState, { - includeCatalog, - }); + yield* sessionConfigurationPublishPermit.withPermit( + Effect.gen(function* () { + const { epoch, key } = yield* Ref.get(lastPublishedCatalogKey); + const configOptions = yield* targetRuntime.getConfigOptions; + const modeState = yield* targetRuntime.getModeState; + const modelState = (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models; + const catalogKey = acpSessionCatalogKey(configOptions, modelState); + const includeCatalog = key !== catalogKey; + yield* flavor.onSessionConfigurationUpdate!(configOptions, modeState, modelState, { + includeCatalog, + }); + yield* Ref.update(lastPublishedCatalogKey, (current) => + current.epoch === epoch ? { epoch, key: catalogKey } : current, + ); + }), + ); }, ); const setActiveSessionSetup = Effect.fnUntraced(function* ( @@ -2346,7 +2335,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rootForegroundWork = undefined; agentRequests.clear(); nativeChildren.clear(); - yield* Ref.set(lastPublishedCatalogKey, null); + yield* resetPublishedCatalogKey; yield* Ref.set(activeSessionSetup, setup); }); const activeSelection = yield* Ref.make(null); @@ -7129,11 +7118,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( notification.update.sessionUpdate === "config_option_update" || notification.update.sessionUpdate === "current_mode_update" ) { - yield* publishSessionConfiguration( - yield* runtime.getConfigOptions, - yield* runtime.getModeState, - (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, - ); + yield* publishSessionConfiguration(runtime); } const normalized = flavor.normalizeSessionUpdate?.(notification) ?? notification; // Turn projection misses compactions that finish while idle or after settlement. @@ -7248,7 +7233,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (current === null || current.sessionId !== result.sessionId) { return; } - yield* Ref.set(lastPublishedCatalogKey, null); + yield* resetPublishedCatalogKey; yield* Ref.set(activeSessionSetup, result); // The selection was configured against the provisional setup's // options, so the next turn re-applies it against the real ones. @@ -7264,11 +7249,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeBuildConfigurationBySessionId.delete(result.sessionId); } yield* refreshModelSwitchCapability; - yield* publishSessionConfiguration( - yield* targetRuntime.getConfigOptions, - yield* targetRuntime.getModeState, - result.sessionSetupResult.models, - ); + yield* publishSessionConfiguration(targetRuntime); }); const wireAcpRuntimeHandlers = Effect.fnUntraced(function* ( @@ -8401,11 +8382,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* validateModelSelection(modelSelection); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); - yield* publishSessionConfiguration( - yield* runtime.getConfigOptions, - yield* runtime.getModeState, - (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, - ); + yield* publishSessionConfiguration(runtime); }); yield* configureSession( @@ -9070,7 +9047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* restartAcpRuntime(threadId); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); - yield* Ref.set(lastPublishedCatalogKey, null); + yield* resetPublishedCatalogKey; yield* Ref.set(activeSessionSetup, null); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); diff --git a/packages/provider-acp/src/server/sessionConfig.test.ts b/packages/provider-acp/src/server/sessionConfig.test.ts index ceb6ceb92783a..9378c1e6e4bb3 100644 --- a/packages/provider-acp/src/server/sessionConfig.test.ts +++ b/packages/provider-acp/src/server/sessionConfig.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "@effect/vitest"; -import { ACP_SESSION_MODE_OPTION_ID, acpProviderOptionDescriptors } from "./sessionConfig.ts"; +import { + ACP_MAX_CATALOG_MODELS, + ACP_SESSION_MODE_OPTION_ID, + acpProviderOptionDescriptors, + acpSessionCatalogKey, +} from "./sessionConfig.ts"; describe("acpProviderOptionDescriptors", () => { it("maps non-model select options and excludes model and collaboration categories", () => { @@ -209,3 +214,57 @@ describe("acpProviderOptionDescriptors", () => { }); }); }); + +describe("acpSessionCatalogKey", () => { + it("ignores selection changes within the retained catalog but changes on labels or overflow selection", () => { + const modelSelect = ( + currentValue: string, + options: ReadonlyArray<{ value: string; name: string; description?: string }>, + ) => [ + { + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: [...options], + }, + ]; + const baseOptions = Array.from({ length: ACP_MAX_CATALOG_MODELS + 1 }, (_, index) => ({ + value: `m${index}`, + name: `Model ${index}`, + })); + + const selectedM0 = acpSessionCatalogKey(modelSelect("m0", baseOptions), undefined); + const selectedM1 = acpSessionCatalogKey(modelSelect("m1", baseOptions), undefined); + expect(selectedM1).toBe(selectedM0); + + // Selecting a model beyond the 256-model cap changes the retained catalog entry. + const selectedOverflow = acpSessionCatalogKey( + modelSelect(`m${ACP_MAX_CATALOG_MODELS}`, baseOptions), + undefined, + ); + expect(selectedOverflow).not.toBe(selectedM0); + + // Display-name or description updates within the retained catalog change the key too. + const renamed = acpSessionCatalogKey( + modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...baseOptions.slice(1)]), + undefined, + ); + expect(renamed).not.toBe(selectedM0); + + // Model-state catalogs follow the same cap and overflow-selection rule. + const availableModels = baseOptions.map((option) => ({ + modelId: option.value, + name: option.name, + })); + const stateM0 = acpSessionCatalogKey([], { currentModelId: "m0", availableModels }); + const stateM1 = acpSessionCatalogKey([], { currentModelId: "m1", availableModels }); + const stateOverflow = acpSessionCatalogKey([], { + currentModelId: `m${ACP_MAX_CATALOG_MODELS}`, + availableModels, + }); + expect(stateM1).toBe(stateM0); + expect(stateOverflow).not.toBe(stateM0); + }); +}); diff --git a/packages/provider-acp/src/server/sessionConfig.ts b/packages/provider-acp/src/server/sessionConfig.ts index af8ee0eec0f33..ffc92e205a15f 100644 --- a/packages/provider-acp/src/server/sessionConfig.ts +++ b/packages/provider-acp/src/server/sessionConfig.ts @@ -1,9 +1,10 @@ import type { ProviderOptionChoice, ProviderOptionDescriptor } from "@t3tools/contracts"; import type * as EffectAcpSchema from "effect-acp/compat"; -import type { AcpSessionModeState } from "./runtimeModel.ts"; +import { findModelConfigOption, type AcpSessionModeState } from "./runtimeModel.ts"; export const ACP_SESSION_MODE_OPTION_ID = "_t3/session-mode"; +export const ACP_MAX_CATALOG_MODELS = 256; /** Encodes a valid empty ACP choice as a non-empty T3 ID; map back before applying. */ export const ACP_EMPTY_OPTION_VALUE = "_t3/empty"; @@ -11,6 +12,8 @@ export const ACP_EMPTY_OPTION_VALUE = "_t3/empty"; const MAX_OPTION_DESCRIPTORS = 16; const MAX_OPTION_CHOICES = 64; const MAX_TEXT_LENGTH = 256; +const MAX_MODEL_ID_LENGTH = 128; +const MAX_MODEL_NAME_LENGTH = 160; const MAX_DESCRIPTION_LENGTH = 1_024; const boundedText = (value: string | null | undefined, maximumLength: number): string => @@ -33,6 +36,65 @@ export function flattenSelectChoices( return options.flatMap((candidate) => ("value" in candidate ? [candidate] : candidate.options)); } +/** + * Stable key for the effective model catalog advertised by a session, mirroring + * normalization's 256-model cap and overflow-selected retention while ignoring + * ordinary selection changes within the retained catalog. + */ +export function acpSessionCatalogKey( + configOptions: ReadonlyArray, + modelState: EffectAcpSchema.SessionModelState | null | undefined, +): string { + const modelOption = findModelConfigOption(configOptions); + const kind = modelOption?.type === "select" ? "select" : "models"; + const selectedId = + modelOption?.type === "select" + ? boundedOpaqueValue(modelOption.currentValue, MAX_MODEL_ID_LENGTH) + : modelState?.currentModelId === undefined + ? undefined + : boundedOpaqueValue(modelState.currentModelId, MAX_MODEL_ID_LENGTH); + const candidates: ReadonlyArray = + modelOption?.type === "select" + ? flattenSelectChoices(modelOption.options).map((choice) => [ + choice.value, + choice.name, + choice.description ?? null, + ]) + : (modelState?.availableModels ?? []).map((model) => [ + model.modelId, + model.name, + model.description ?? null, + ]); + const normalizeEntry = ( + id: string, + candidate: readonly [string, string, string | null], + ): readonly [string, string, string | null] => [ + id, + boundedText(candidate[1], MAX_MODEL_NAME_LENGTH) || id, + candidate[2] === null ? null : boundedText(candidate[2], MAX_DESCRIPTION_LENGTH) || null, + ]; + const seen = new Set(); + const retained: Array = []; + for (const candidate of candidates) { + if (retained.length === ACP_MAX_CATALOG_MODELS) break; + const id = boundedOpaqueValue(candidate[0], MAX_MODEL_ID_LENGTH); + if (id === undefined || seen.has(id)) continue; + seen.add(id); + retained.push(normalizeEntry(id, candidate)); + } + if ( + selectedId !== undefined && + retained.length === ACP_MAX_CATALOG_MODELS && + !seen.has(selectedId) + ) { + const selected = candidates.find((candidate) => candidate[0] === selectedId); + if (selected !== undefined) { + retained[ACP_MAX_CATALOG_MODELS - 1] = normalizeEntry(selectedId, selected); + } + } + return JSON.stringify([kind, retained]); +} + function selectChoices( candidates: ReadonlyArray<{ readonly value: string; From b875c2e8a5de80582c3b8e2f1981908e25ea3280 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 11:06:43 +0000 Subject: [PATCH 10/35] fix(acp-registry): simplify catalog key, keep only compatible live overrides, and serialize coordinator publish --- .../Adapters/AcpAdapterV2.test.ts | 67 ++- .../AcpRegistryRuntimeCoordinator.test.ts | 284 +++++++++---- .../server/AcpRegistryRuntimeCoordinator.ts | 103 ++--- .../src/server/adapter.ts | 2 + .../src/server/driver.test.ts | 383 ++++++++++++++++-- .../src/server/driver.ts | 167 +++++--- .../provider-acp-registry/src/server/probe.ts | 28 +- packages/provider-acp/src/server/adapter.ts | 42 +- .../src/server/sessionConfig.test.ts | 61 +-- .../provider-acp/src/server/sessionConfig.ts | 64 +-- 10 files changed, 827 insertions(+), 374 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index c8f89885bf69a..3499a66b4b7ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5269,7 +5269,7 @@ describe("AcpAdapterV2", () => { ); it.effect( - "deduplicates unchanged config_option_update catalogs and re-advertises on changed choices or new sessions", + "deduplicates unchanged config_option_update catalogs and re-advertises on changed choices or active native session replacement", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -5277,9 +5277,6 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* bundledMockAgentPath; type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdate: Parameters[0] | undefined; - let activeConfigOptions: ReadonlyArray | undefined; - const publications: Array<{ readonly includeCatalog: boolean | undefined }> = []; - const instanceId = ProviderInstanceId.make("acp-test-catalog-dedupe"); const makeModelSelect = ( currentValue: string, choices: ReadonlyArray<{ readonly value: string; readonly name: string }>, @@ -5297,6 +5294,10 @@ describe("AcpAdapterV2", () => { { value: "default", name: "Default" }, { value: "composer-2", name: "Composer 2" }, ] as const; + let activeConfigOptions: ReadonlyArray = + makeModelSelect("default", initialChoices); + const publications: Array<{ readonly includeCatalog: boolean | undefined }> = []; + const instanceId = ProviderInstanceId.make("acp-test-catalog-dedupe"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { @@ -5316,10 +5317,7 @@ describe("AcpAdapterV2", () => { mockAgentPath, wrapRuntime: (runtime) => ({ ...runtime, - getConfigOptions: - activeConfigOptions === undefined - ? runtime.getConfigOptions - : Effect.sync(() => activeConfigOptions!), + getConfigOptions: Effect.sync(() => activeConfigOptions), handleSessionUpdate: (next) => Effect.sync(() => { sessionUpdate = next; @@ -5329,21 +5327,28 @@ describe("AcpAdapterV2", () => { }, selfInvocation, }); + const threadId = ThreadId.make("thread-acp-catalog-dedupe"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", cwd: process.cwd(), }); - const open = (suffix: string) => - adapter.openSession({ - threadId: ThreadId.make(`thread-acp-catalog-dedupe-${suffix}`), - providerSessionId: ProviderSessionId.make(`provider-session-acp-dedupe-${suffix}`), - modelSelection: { instanceId, model: "default" }, - runtimePolicy, - }); - - activeConfigOptions = makeModelSelect("default", initialChoices); - yield* open("first"); + const modelSelection = { instanceId, model: "default" } as const; + const sessionRuntime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-dedupe"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* sessionRuntime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const initialNativeId = providerThread.nativeThreadRef?.nativeId; + if (typeof initialNativeId !== "string") { + assert.fail("expected initial native thread id"); + } assert.deepEqual( publications.map((entry) => entry.includeCatalog), [true], @@ -5353,7 +5358,7 @@ describe("AcpAdapterV2", () => { // config_option_update with unchanged model choices sets includeCatalog: false. activeConfigOptions = makeModelSelect("composer-2", initialChoices); yield* sessionUpdate!({ - sessionId: "mock-session-1", + sessionId: initialNativeId, update: { sessionUpdate: "config_option_update", configOptions: [] }, }); assert.deepEqual( @@ -5367,7 +5372,7 @@ describe("AcpAdapterV2", () => { { value: "composer-3", name: "Composer 3" }, ]); yield* sessionUpdate!({ - sessionId: "mock-session-1", + sessionId: initialNativeId, update: { sessionUpdate: "config_option_update", configOptions: [] }, }); assert.deepEqual( @@ -5375,8 +5380,26 @@ describe("AcpAdapterV2", () => { [true, false, true], ); - // Opening a new session resets the deduplication key even when choices match. - yield* open("second"); + // Replacing the active native session inside the same openSession (rollbackThread) + // resets lastPublishedCatalogKey so the first publication with identical choices + // sets includeCatalog: true again. + const rolledBack = yield* sessionRuntime.rollbackThread({ + providerThread, + providerThreadTurns: [], + target: { + type: "thread_start", + checkpointId: CheckpointId.make("checkpoint-acp-catalog-dedupe"), + appRunOrdinal: 0, + }, + }); + const rolledBackNativeId = rolledBack.providerThread.nativeThreadRef?.nativeId; + if (typeof rolledBackNativeId !== "string") { + assert.fail("expected rolled-back native thread id"); + } + yield* sessionUpdate!({ + sessionId: rolledBackNativeId, + update: { sessionUpdate: "config_option_update", configOptions: [] }, + }); assert.deepEqual( publications.map((entry) => entry.includeCatalog), [true, false, true, true], diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 1a592a3560cd3..52269613fbb20 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -258,12 +258,131 @@ describe("AcpRegistryRuntimeCoordinator", () => { }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); + it.effect("skips stale live configuration revisions when watching after a revision", () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + const configFor = (id: string) => ({ + models: [{ id, name: id, description: null }], + currentModelId: id, + configOptions: [], + modelsFromModelSelect: true, + }); + + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v1")); + const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(first.revision).toBeGreaterThan(0); + + const received: Array = []; + const secondSeen = yield* Deferred.make(); + const watcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Effect.sync(() => { + received.push([configuration.currentModelId, revision] as const); + }).pipe(Effect.andThen(Deferred.succeed(secondSeen, undefined)), Effect.asVoid), + { afterRevision: first.revision }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); + yield* Deferred.await(secondSeen); + yield* Fiber.interrupt(watcher); + const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(received).toEqual([["model-v2", second.revision]]); + + // Publications on another instance must not advance this instance's revision or watermark. + const otherInstanceId = ProviderInstanceId.make("acpRegistry_kimi"); + yield* coordinator.publishLiveConfiguration(otherInstanceId, configFor("kimi-v1")); + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual(second); + }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), + ); + it.effect( - "tracks live configuration revisions so stale snapshots are neither replayed nor able to clear newer ones", + "preserves an unsuperseded catalog only for options-only updates targeting that catalog", () => Effect.gen(function* () { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + const effortOption = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; + const catalogModels = [ + { id: "model-b", name: "Model B", description: null }, + { id: "model-c", name: "Model C", description: null }, + ]; + + yield* coordinator.publishLiveConfiguration(instanceId, { + models: catalogModels, + currentModelId: "model-b", + configOptions: [], + modelsFromModelSelect: true, + }); + const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + // Options-only update targeting model-b keeps the active catalog in coordinator state. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const matchingOptionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(matchingOptionsSnap.revision).toBe(catalogSnap.revision + 1); + expect(matchingOptionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); + expect(matchingOptionsSnap.configuration).toEqual( + Option.some({ + models: catalogModels, + currentModelId: "model-b", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }), + ); + + // An options-only update from another session running an absent model stores raw + // so stored snapshots never lose the default marker compared to the PubSub stream. + const foreignOptionsOnly = { + models: [], + currentModelId: "model-a", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }; + yield* coordinator.publishLiveConfiguration(instanceId, foreignOptionsOnly); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).configuration, + ).toEqual(Option.some(foreignOptionsOnly)); + }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), + ); + + it.effect( + "clears live configuration conditionally by catalogRevision with retention and full-clear modes", + () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + const effortOption = (currentValue: "low" | "high") => ({ + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue, + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); const configFor = (id: string) => ({ models: [{ id, name: id, description: null }], currentModelId: id, @@ -273,101 +392,52 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v1")); const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(first.revision).toBeGreaterThan(0); - - // Watching past the already-observed revision skips the stale replay, then delivers newer updates with their revision. - const received: Array = []; - const secondSeen = yield* Deferred.make(); - const watcher = yield* coordinator - .watchLiveConfiguration( - instanceId, - (configuration, revision) => - Effect.sync(() => { - received.push([configuration.currentModelId, revision] as const); - }).pipe(Effect.andThen(Deferred.succeed(secondSeen, undefined)), Effect.asVoid), - { afterRevision: first.revision }, - ) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); - yield* Deferred.await(secondSeen); - yield* Fiber.interrupt(watcher); const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(received).toEqual([["model-v2", second.revision]]); - // An outdated revision cannot clear a newer live configuration or advance clearedThroughRevision. + // Outdated catalogRevision cannot clear a newer catalog or advance clearedThroughRevision. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, first.revision), + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, first.revision, { + catalogRevision: first.catalogRevision, + }), ).toBe(false); - expect(Option.isSome(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, ).toBe(0); - expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision), - ).toBe(true); - const afterClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(Option.isNone(afterClear.configuration)).toBe(true); - expect(afterClear.clearedThroughRevision).toBe(second.revision); - - // Publications on another instance must not advance this instance's revision or watermark. - const otherInstanceId = ProviderInstanceId.make("acpRegistry_kimi"); - yield* coordinator.publishLiveConfiguration(otherInstanceId, configFor("kimi-v1")); - expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual(afterClear); - - // Options-only updates preserve any unsuperseded catalog in stored state while keeping - // catalogRevision unchanged, and a catalog-scoped clear strips only the catalog while - // preserving the newer options descriptor. - const effortOption = { - id: "effort", - label: "Effort", - type: "select" as const, - role: "reasoning" as const, - currentValue: "low", - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], - }; - yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v3")); - const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + // Catalog-scoped clear validates newer in-flight options-only updates through retainConfiguration. const optionsOnlyConfig = { models: [], - currentModelId: "model-v3", - configOptions: [effortOption], + currentModelId: "model-v2", + configOptions: [effortOption("high")], modelOptionIds: ["effort"], modelsFromModelSelect: false, }; yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyConfig); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(optionsSnap.revision).toBe(catalogSnap.revision + 1); - expect(optionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); - expect(optionsSnap.configuration).toEqual( - Option.some({ - ...optionsOnlyConfig, - models: configFor("model-v3").models, - modelsFromModelSelect: true, - }), - ); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, catalogSnap.revision, { - catalogRevision: catalogSnap.catalogRevision, + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision, { + catalogRevision: second.catalogRevision, + retainConfiguration: (live) => + Option.some({ + ...live, + configOptions: [effortOption("low")], + }), }), ).toBe(true); - const afterOptionsPreserved = - yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(afterOptionsPreserved).toEqual({ + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, - configuration: Option.some(optionsOnlyConfig), - clearedThroughRevision: catalogSnap.revision, + configuration: Option.some({ + ...optionsOnlyConfig, + configOptions: [effortOption("low")], + }), + clearedThroughRevision: second.revision, }); - // A catalog-scoped clear with clearOptions: true wipes both catalog and options - // (used by authoritative unauthenticated probes) and advances clearedThroughRevision. + // clearOptions: true wipes both catalog and options and advances clearedThroughRevision past optionsSnap. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, catalogSnap.revision, { - catalogRevision: catalogSnap.catalogRevision, + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision, { + catalogRevision: second.catalogRevision, clearOptions: true, }), ).toBe(true); @@ -377,29 +447,79 @@ describe("AcpRegistryRuntimeCoordinator", () => { clearedThroughRevision: optionsSnap.revision, }); - // A catalog-scoped clear at the exact catalog revision strips models while keeping options. + // Without retainConfiguration, clearing strips models while preserving non-empty options and drops empty ones. yield* coordinator.publishLiveConfiguration(instanceId, { - ...configFor("model-v4"), - configOptions: [effortOption], + ...configFor("model-v3"), + configOptions: [effortOption("low")], modelOptionIds: ["effort"], }); - const v4Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + const v3Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v4Snap.revision, { - catalogRevision: v4Snap.catalogRevision, + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v3Snap.revision, { + catalogRevision: v3Snap.catalogRevision, }), ).toBe(true); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ - ...v4Snap, + ...v3Snap, configuration: Option.some({ models: [], - currentModelId: "model-v4", - configOptions: [effortOption], + currentModelId: "model-v3", + configOptions: [effortOption("low")], modelOptionIds: ["effort"], modelsFromModelSelect: false, }), + clearedThroughRevision: v3Snap.revision, + }); + + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v4")); + const v4Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v4Snap.revision, { + catalogRevision: v4Snap.catalogRevision, + }), + ).toBe(true); + expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ + ...v4Snap, + configuration: Option.none(), clearedThroughRevision: v4Snap.revision, }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); + + it.effect("delivers concurrent live configuration publications in strict revision order", () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + const receivedRevisions: Array = []; + const allSeen = yield* Deferred.make(); + const watcher = yield* coordinator + .watchLiveConfiguration(instanceId, (_configuration, revision) => + Effect.sync(() => { + receivedRevisions.push(revision); + return receivedRevisions.length; + }).pipe( + Effect.flatMap((count) => + count === 4 ? Deferred.succeed(allSeen, undefined).pipe(Effect.asVoid) : Effect.void, + ), + ), + ) + .pipe(Effect.forkChild({ startImmediately: true })); + + yield* Effect.forEach( + [1, 2, 3, 4], + (index) => + coordinator.publishLiveConfiguration(instanceId, { + models: + index % 2 === 1 ? [{ id: `m${index}`, name: `m${index}`, description: null }] : [], + currentModelId: `m${index}`, + configOptions: [], + modelsFromModelSelect: index % 2 === 1, + }), + { concurrency: "unbounded", discard: true }, + ); + yield* Deferred.await(allSeen); + yield* Fiber.interrupt(watcher); + expect(receivedRevisions).toEqual([1, 2, 3, 4]); + }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), + ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 47d870ab98872..7332fd85c2cee 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -86,10 +86,10 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly clearLiveConfigurationIfRevision: ( instanceId: ProviderInstanceId, revision: number, - options?: { - readonly catalogRevision?: number; + options: { + readonly catalogRevision: number; readonly clearOptions?: boolean; - readonly retainPreProbeConfiguration?: ( + readonly retainConfiguration?: ( configuration: AcpRegistryLiveConfiguration, ) => Option.Option; }, @@ -144,6 +144,7 @@ const make = Effect.gen(function* () { const pendingUrlAuthActions = yield* Ref.make( new Map(), ); + const liveConfigurationPublishPermit = yield* Semaphore.make(1); const urlAuthActionPermit = yield* Semaphore.make(1); const sessionMutationPermit = yield* Semaphore.make(1); @@ -265,15 +266,10 @@ const make = Effect.gen(function* () { function* (instanceId, revision, options) { return yield* Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; - const catalogScoped = options?.catalogRevision !== undefined; - if (catalogScoped) { - if (current.catalogRevision !== options.catalogRevision) { - return [false, state] as const; - } - } else if (Option.isSome(current.configuration) && current.revision !== revision) { + if (current.catalogRevision !== options.catalogRevision) { return [false, state] as const; } - const clearAll = !catalogScoped || options.clearOptions === true; + const clearAll = options.clearOptions === true; const nextCleared = clearAll ? Math.max(current.clearedThroughRevision, current.revision, revision) : Math.max(current.clearedThroughRevision, revision); @@ -285,12 +281,8 @@ const make = Effect.gen(function* () { models: [], modelsFromModelSelect: false, }; - if (current.revision > revision) { - // Preserve options-only updates that landed while the probe ran. - return Option.some(withoutCatalog); - } - if (options.retainPreProbeConfiguration !== undefined) { - return options.retainPreProbeConfiguration(withoutCatalog); + if (options.retainConfiguration !== undefined) { + return options.retainConfiguration(withoutCatalog); } return withoutCatalog.configOptions.length > 0 ? Option.some(withoutCatalog) @@ -315,42 +307,53 @@ const make = Effect.gen(function* () { const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => - Ref.modify(liveConfigurations, (state) => { - const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; - const revision = current.revision + 1; - const hasCatalog = configuration.models.length > 0; - const catalogRevision = hasCatalog ? current.catalogRevision + 1 : current.catalogRevision; - // Keep any unsuperseded session catalog in coordinator state across options-only - // updates so readiness checks before acceptedCatalog settles do not regress to default. - const storedConfiguration: AcpRegistryLiveConfiguration = - !hasCatalog && - Option.isSome(current.configuration) && - current.configuration.value.models.length > 0 - ? { - ...configuration, - models: current.configuration.value.models, - ...(current.configuration.value.modelsFromModelSelect === undefined - ? {} - : { modelsFromModelSelect: current.configuration.value.modelsFromModelSelect }), - } - : configuration; - const next = new Map(state); - next.set(instanceId, { - configuration: Option.some(storedConfiguration), - revision, - catalogRevision, - clearedThroughRevision: current.clearedThroughRevision, - }); - return [revision, next] as const; - }).pipe( - Effect.flatMap((revision) => - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, + // Serialize store + PubSub publish so concurrent sessions emit in revision order. + liveConfigurationPublishPermit.withPermit( + Ref.modify(liveConfigurations, (state) => { + const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + const revision = current.revision + 1; + const hasCatalog = configuration.models.length > 0; + const catalogRevision = hasCatalog + ? current.catalogRevision + 1 + : current.catalogRevision; + // Preserve an unsuperseded session catalog across options-only updates only when + // the update targets that catalog (or no model), keeping the default marker intact. + const canPreserveStoredCatalog = + !hasCatalog && + Option.isSome(current.configuration) && + current.configuration.value.models.length > 0 && + (configuration.currentModelId === null || + current.configuration.value.models.some( + (model) => model.id === configuration.currentModelId, + )); + const storedConfiguration: AcpRegistryLiveConfiguration = + canPreserveStoredCatalog && Option.isSome(current.configuration) + ? { + ...configuration, + models: current.configuration.value.models, + ...(current.configuration.value.modelsFromModelSelect === undefined + ? {} + : { modelsFromModelSelect: current.configuration.value.modelsFromModelSelect }), + } + : configuration; + const next = new Map(state); + next.set(instanceId, { + configuration: Option.some(storedConfiguration), revision, - }), + catalogRevision, + clearedThroughRevision: current.clearedThroughRevision, + }); + return [revision, next] as const; + }).pipe( + Effect.flatMap((revision) => + PubSub.publish(liveConfigurationUpdates, { + instanceId, + configuration, + revision, + }), + ), + Effect.asVoid, ), - Effect.asVoid, ); const getLiveConfigurationWithRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationWithRevision"] = diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 95a327b272f5d..8bd9f87f504ba 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -41,6 +41,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { + acpRegistrySessionCatalogKey, normalizeAcpRegistryCommands, normalizeAcpRegistryLiveConfiguration, normalizeAcpRegistryWebUrl, @@ -374,6 +375,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), + sessionCatalogKey: acpRegistrySessionCatalogKey, onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => runtimeCoordinator.publishLiveConfiguration( options.instanceId, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 1b01fea744fc9..233e4cb2947fd 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -40,6 +40,7 @@ import { import { acpRegistryAdvertisesModelCatalog, acpRegistryProbeResult, + acpRegistrySessionCatalogKey, normalizeAcpRegistryLiveConfiguration, } from "./probe.ts"; @@ -448,13 +449,12 @@ describe("acpRegistrySnapshotReadiness", () => { ); expect(optionsOnlyDisabled.configOptions).toEqual([]); expect(optionsOnlyDisabled.modelOptionIds).toEqual([]); - expect(optionsOnlyDisabled.reasoningDisabledModelIds).toEqual(["glm"]); - const providerWithEffortOnGlm = applyAcpRegistryLiveConfiguration( + const providerAfterCatalogDisable = applyAcpRegistryLiveConfiguration( provider, normalizeAcpRegistryLiveConfiguration([effort], undefined, { currentModelId: "glm", availableModels: [ - { modelId: "glm", name: "GLM" }, + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, { modelId: "opus", name: "Opus" }, ], }), @@ -462,12 +462,47 @@ describe("acpRegistrySnapshotReadiness", () => { ); expect( applyAcpRegistryLiveConfiguration( - providerWithEffortOnGlm, + providerAfterCatalogDisable, optionsOnlyDisabled, [], ).models.map((model) => model.capabilities?.optionDescriptors ?? []), ).toEqual([[], []]); + // An options-only update from an older session whose frozen _meta had supportsReasoningEffort: false + // for a non-current model must not undo reasoning that a newer probe re-enabled on that model. + const probeReenabledGlm = applyAcpRegistryLiveConfiguration( + provider, + normalizeAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "glm", + availableModels: [ + { modelId: "glm", name: "GLM" }, + { modelId: "opus", name: "Opus" }, + ], + }), + [], + ); + const staleSessionOptionsOnOpus = normalizeAcpRegistryLiveConfiguration( + [effort], + undefined, + { + currentModelId: "opus", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }, + { includeCatalog: false }, + ); + expect( + applyAcpRegistryLiveConfiguration( + probeReenabledGlm, + staleSessionOptionsOnOpus, + [], + ).models.map((model) => + (model.capabilities?.optionDescriptors ?? []).map((descriptor) => descriptor.id), + ), + ).toEqual([["effort"], ["effort"]]); + // Explicit probe-level reasoningDisabledModelSlugs keeps effort off a disabled model during // an options-only overlay while preserving unrelated options and allowing enabled models. const modeDescriptor = { @@ -1194,8 +1229,8 @@ describe("acpRegistryEnrichmentCache", () => { }), ).toBe(true); }); - it("retains valid live option values across a superseding probe while dropping removed or disabled options", () => { - const mode = (currentValue: "ask" | "code") => ({ + it("retains only compatible live overrides across superseding probes without storing probe defaults or stripping default-model options", () => { + const mode = (currentValue: "ask" | "code" | "removed") => ({ id: "mode", label: "Mode", type: "select" as const, @@ -1205,16 +1240,16 @@ describe("acpRegistryEnrichmentCache", () => { { id: "code", label: "Code" }, ], }); - const effort = (currentValue: "low" | "high") => ({ + const effort = ( + currentValue: "low" | "high", + choices: ReadonlyArray<"low" | "high"> = ["low", "high"], + ) => ({ id: "effort", label: "Effort", type: "select" as const, role: "reasoning" as const, currentValue, - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], + options: choices.map((id) => ({ id, label: id === "low" ? "Low" : "High" })), }); const legacy = { id: "legacy", @@ -1223,7 +1258,12 @@ describe("acpRegistryEnrichmentCache", () => { currentValue: "on", options: [{ id: "on", label: "On" }], }; - const fast = { id: "fast", label: "Fast", type: "boolean" as const, currentValue: false }; + const fast = (currentValue: boolean) => ({ + id: "fast", + label: "Fast", + type: "boolean" as const, + currentValue, + }); const retained = retainAcpRegistryLiveOptionsAfterProbe( { @@ -1239,17 +1279,160 @@ describe("acpRegistryEnrichmentCache", () => { { id: "old-model", name: "old-model", description: null }, ], currentModelId: "new-model", - configOptions: [mode("ask"), fast, effort("high")], + configOptions: [mode("ask"), fast(false), effort("high")], modelOptionIds: new Set(["effort"]), }, ); + // Probe-only defaults (fast=false) must not be stored as live overrides. expect(retained).toEqual( Option.some({ models: [], currentModelId: "old-model", - configOptions: [mode("code"), fast, effort("low")], + configOptions: [mode("code"), effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + partialOptions: true, + }), + ); + + // Applying the retained override onto a later probe where fast=true preserves mode=code + // and keeps the new probe default fast=true instead of reverting it to false. + const probeWithFast = (fastDefault: boolean) => + buildCheckedAcpRegistrySnapshot({ + ...identity, + settings: decodeSettings({ agentId: "test-agent" }), + checkedAt: "2026-08-13T10:00:00.000Z", + inspection: { + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + }, + probe: { + probe: { + instanceId: identity.instanceId, + ready: true, + icon: null, + authMethods: [], + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null }, + ], + currentModelId: "new-model", + configOptions: [mode("ask"), fast(fastDefault), effort("high")], + modelOptionIds: ["effort"], + sessionManagement: noSessionManagement, + }, + slashCommands: [], + skills: [], + }, + }); + const appliedProbe2 = applyAcpRegistryLiveConfiguration( + probeWithFast(true), + Option.getOrThrow(retained), + [], + ); + expect( + appliedProbe2.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["mode", "code"], + ["fast", true], + ["effort", "high"], + ]); + expect( + appliedProbe2.models + .find((m) => m.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["mode", "code"], + ["fast", true], + ["effort", "low"], + ]); + + // When the live session's model was removed upstream, keep live.currentModelId so the + // probe's default model retains its own model-specific options (effort) alongside shared mode=code. + const retainedAfterRemovedModel = Option.getOrThrow( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "removed-model", + configOptions: [mode("code"), effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null }, + ], + currentModelId: "new-model", + configOptions: [mode("ask"), fast(false), effort("high")], + modelOptionIds: new Set(["effort"]), + }, + ), + ); + expect(retainedAfterRemovedModel.currentModelId).toBe("removed-model"); + const appliedRemovedModel = applyAcpRegistryLiveConfiguration( + probeWithFast(false), + retainedAfterRemovedModel, + [], + ); + expect(appliedRemovedModel.models.find((m) => m.slug === "new-model")?.isDefault).toBe(true); + expect( + appliedRemovedModel.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["mode", "code"], + ["fast", false], + ["effort", "high"], + ]); + + // Invalid or removed live values are dropped rather than storing probe fallbacks as overrides. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [mode("removed"), effort("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [{ id: "old-model", name: "old-model", description: null }], + currentModelId: "old-model", + configOptions: [mode("ask"), effort("low", ["low"])], + modelOptionIds: new Set(["effort"]), + }, + ), + ).toEqual(Option.none()); + // Valid live values on the same model survive while removed values are dropped. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [mode("code"), effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + { + models: [{ id: "old-model", name: "old-model", description: null }], + currentModelId: "old-model", + configOptions: [mode("ask"), effort("low", ["low"])], + modelOptionIds: new Set(["effort"]), + }, + ), + ).toEqual( + Option.some({ + models: [], + currentModelId: "old-model", + configOptions: [mode("code"), effort("low", ["low"])], modelOptionIds: ["effort"], modelsFromModelSelect: false, + partialOptions: true, }), ); @@ -1296,6 +1479,71 @@ describe("acpRegistryEnrichmentCache", () => { }); }); +describe("acpRegistrySessionCatalogKey", () => { + it("ignores in-cap selection and effort value tweaks while detecting overflow selection, renames, and newly normalized per-model reasoning", () => { + const modelSelect = ( + currentValue: string, + options: ReadonlyArray<{ value: string; name: string }>, + ) => [ + { + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: [...options], + }, + ]; + const choices = Array.from({ length: 257 }, (_, index) => ({ + value: `m${index}`, + name: `Model ${index}`, + })); + + const keyM0 = acpRegistrySessionCatalogKey(modelSelect("m0", choices)); + expect(acpRegistrySessionCatalogKey(modelSelect("m1", choices))).toBe(keyM0); + expect(acpRegistrySessionCatalogKey(modelSelect("m256", choices))).not.toBe(keyM0); + expect( + acpRegistrySessionCatalogKey( + modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...choices.slice(1)]), + ), + ).not.toBe(keyM0); + + // When a session initially omits the effort selector and later exposes it, another model's + // _meta.reasoningEfforts becomes normalizable and must change the catalog key, while changing + // only the active effort currentValue must not. + const modelState = { + currentModelId: "model-a", + availableModels: [ + { modelId: "model-a", name: "Model A" }, + { + modelId: "model-b", + name: "Model B", + _meta: { + reasoningEfforts: [{ value: "low", label: "Low" }], + reasoningEffort: "low", + }, + }, + ], + }; + const effortSelect = (currentValue: "low" | "high") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }); + const withoutEffort = acpRegistrySessionCatalogKey([], modelState); + const withEffortHigh = acpRegistrySessionCatalogKey([effortSelect("high")], modelState); + const withEffortLow = acpRegistrySessionCatalogKey([effortSelect("low")], modelState); + expect(withEffortHigh).not.toBe(withoutEffort); + expect(withEffortLow).toBe(withEffortHigh); + }); +}); + describe("acpRegistryAdvertisesModelCatalog", () => { it("counts choices inside option groups and available model state", () => { expect( @@ -2310,8 +2558,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); - // Re-populate the catalog, then verify disableProvider clears acceptedCatalog so a - // provisional probe afterward does not stick to the disabled provider's models. + // Re-populate the catalog AND live coordinator state, then verify disableProvider clears + // both coordinator state and acceptedCatalog so a provisional probe does not retain old models. yield* writeModels(["new-model", "old-model", "other-model"]); const restored = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -2319,10 +2567,35 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(restored); + const liveBeforeDisable = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.map((m) => m.slug).join() === "live-disable-a,live-disable-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "live-disable-a", name: "Live Disable A", description: null }, + { id: "live-disable-b", name: "Live Disable B", description: null }, + ], + currentModelId: "live-disable-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(liveBeforeDisable); + expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); + yield* instance.acpSessionManagement!.disableProvider({ cwd: directory, providerId: "old-provider", }); + expect(Option.isNone(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); yield* writeModels({ provisional: "placeholder" }); const afterDisable = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -2332,7 +2605,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Option.getOrThrow(yield* Fiber.join(afterDisable)).models.map((model) => model.slug), ).toEqual(["placeholder"]); - // Re-populate, then verify invalidateCaches and auth.invalidate clear acceptedCatalog. + // Re-populate, then verify invalidateCaches and auth.invalidate clear both coordinator and acceptedCatalog. yield* writeModels(["new-model", "old-model", "other-model"]); yield* TestClock.adjust("1 minute"); const restored2 = yield* waitForEnriched().pipe( @@ -2362,9 +2635,32 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* instance.snapshot.refresh; yield* Fiber.join(restoredForAuthInvalidate); + const liveBeforeAuthInvalidate = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.map((m) => m.slug).join() === "live-auth-a,live-auth-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "live-auth-a", name: "Live Auth A", description: null }, + { id: "live-auth-b", name: "Live Auth B", description: null }, + ], + currentModelId: "live-auth-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(liveBeforeAuthInvalidate); + expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.auth?.invalidate ?? Effect.void; + expect( + Option.isNone(yield* coordinator.getLiveConfiguration(identity.instanceId)), + ).toBe(true); expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ "default", ]); @@ -2581,12 +2877,40 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(initial); - // Fresh probe disables reasoning on old-model while adding new-model. - yield* writeModels([ - { modelId: "old-model", name: "old-model", _meta: { supportsReasoningEffort: false } }, - "other-model", - "new-model", - ]); + // Fresh probe advertises mode=[code, plan], restricts effort on old-model to [low] only, + // and disables reasoning on other-model while adding new-model. + yield* writeModels({ + models: [ + "old-model", + { + modelId: "other-model", + name: "other-model", + _meta: { supportsReasoningEffort: false }, + }, + "new-model", + ], + configOptions: [ + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "code", + options: [ + { value: "code", name: "Code" }, + { value: "plan", name: "Plan" }, + ], + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "low", + options: [{ value: "low", name: "Low" }], + }, + ], + }); yield* TestClock.adjust("16 minutes"); gateNextResolve = true; yield* instance.snapshot.refresh; @@ -2603,6 +2927,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + // Live update sets mode=plan (still valid) and effort=high (removed by the probe). yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [], currentModelId: "old-model", @@ -2622,7 +2947,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { label: "Effort", type: "select", role: "reasoning", - currentValue: "low", + currentValue: "high", options: [ { id: "low", label: "Low" }, { id: "high", label: "High" }, @@ -2644,11 +2969,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "other-model", "new-model", ]); - // Unrelated live option (mode) stays applied while disabled reasoning (effort) stays stripped. + // Valid live option (mode=plan) survives while the removed choice (effort=high) is replaced by probe's low. expect( updated.models .find((model) => model.slug === "old-model") ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["mode", "plan"], + ["effort", "low"], + ]); + expect( + updated.models + .find((model) => model.slug === "other-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), ).toEqual([["mode", "plan"]]); // Verify the fresh catalog was saved to acceptedCatalog (survives skipped readiness) and cache. diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b6786144097c3..b6326c54a28a7 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -284,24 +284,24 @@ function updateLearnedModelsFromLive( return changed ? Array.from(learnedBySlug.values()) : learned; } -function overlayLiveOptionValue( +function compatibleLiveOptionValue( probed: ProviderOptionDescriptor, live: ProviderOptionDescriptor | undefined, -): ProviderOptionDescriptor { +): Option.Option { if (live === undefined || live.type !== probed.type || live.currentValue === undefined) { - return probed; + return Option.none(); } if (probed.type === "boolean") { - return { ...probed, currentValue: live.currentValue as boolean }; + return Option.some({ ...probed, currentValue: live.currentValue as boolean }); } return probed.options.some((option) => option.id === live.currentValue) - ? { ...probed, currentValue: live.currentValue as string } - : probed; + ? Option.some({ ...probed, currentValue: live.currentValue as string }) + : Option.none(); } /** - * Keeps live session option values that still apply after a superseding probe replaces - * the catalog, while dropping removed shared options and dropped/disabled model options. + * Keeps only compatible live session option overrides after a superseding probe replaces + * the catalog, leaving probe-only defaults out of coordinator state. */ export function retainAcpRegistryLiveOptionsAfterProbe( live: AcpRegistryLiveConfiguration, @@ -316,38 +316,31 @@ export function retainAcpRegistryLiveOptionsAfterProbe( const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); const liveModelOptionIds = new Set(live.modelOptionIds ?? []); const probedModelById = new Map(probe.models.map((model) => [model.id, model])); - const nextCurrentModelId = - live.currentModelId !== null && probedModelById.has(live.currentModelId) - ? live.currentModelId - : null; const currentProbedModel = - nextCurrentModelId === null ? undefined : probedModelById.get(nextCurrentModelId); + live.currentModelId === null ? undefined : probedModelById.get(live.currentModelId); - let preservedAnyLiveOption = false; const sharedDescriptors: Array = []; for (const descriptor of probe.configOptions) { if (isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; - const liveMatch = liveById.get(descriptor.id); - if (liveMatch !== undefined) preservedAnyLiveOption = true; - sharedDescriptors.push(overlayLiveOptionValue(descriptor, liveMatch)); + const retained = compatibleLiveOptionValue(descriptor, liveById.get(descriptor.id)); + if (Option.isSome(retained)) sharedDescriptors.push(retained.value); } const sharedIds = new Set(sharedDescriptors.map((descriptor) => descriptor.id)); const modelDescriptors: Array = []; - if (nextCurrentModelId !== null) { - const reasoningDisabled = currentProbedModel?.reasoningEffort === null; - if (nextCurrentModelId === probe.currentModelId) { + if (currentProbedModel !== undefined) { + const reasoningDisabled = currentProbedModel.reasoningEffort === null; + if (currentProbedModel.id === probe.currentModelId) { for (const descriptor of probe.configOptions) { if (sharedIds.has(descriptor.id)) continue; if (reasoningDisabled && descriptor.type === "select" && descriptor.role === "reasoning") { continue; } - const liveMatch = liveById.get(descriptor.id); - if (liveMatch !== undefined) preservedAnyLiveOption = true; - modelDescriptors.push(overlayLiveOptionValue(descriptor, liveMatch)); + const retained = compatibleLiveOptionValue(descriptor, liveById.get(descriptor.id)); + if (Option.isSome(retained)) modelDescriptors.push(retained.value); } } else { - const advertisedReasoning = currentProbedModel?.reasoningEffort; + const advertisedReasoning = currentProbedModel.reasoningEffort; let addedAdvertisedReasoning = false; for (const descriptor of live.configOptions) { if (sharedIds.has(descriptor.id)) continue; @@ -356,30 +349,31 @@ export function retainAcpRegistryLiveOptionsAfterProbe( if (reasoningDisabled) continue; if (advertisedReasoning != null) { if (!addedAdvertisedReasoning) { - modelDescriptors.push(overlayLiveOptionValue(advertisedReasoning, descriptor)); - addedAdvertisedReasoning = true; - preservedAnyLiveOption = true; + const retained = compatibleLiveOptionValue(advertisedReasoning, descriptor); + if (Option.isSome(retained)) { + modelDescriptors.push(retained.value); + addedAdvertisedReasoning = true; + } } continue; } } modelDescriptors.push(descriptor); - preservedAnyLiveOption = true; - } - if (advertisedReasoning != null && !addedAdvertisedReasoning) { - modelDescriptors.push(advertisedReasoning); } } } const configOptions = [...sharedDescriptors, ...modelDescriptors]; - if (!preservedAnyLiveOption || configOptions.length === 0) return Option.none(); + if (configOptions.length === 0) return Option.none(); return Option.some({ models: [], - currentModelId: nextCurrentModelId, + // Keep live.currentModelId even when removed upstream so overlay does not + // apply session options onto the probe's default model. + currentModelId: live.currentModelId, configOptions, modelOptionIds: modelDescriptors.map((descriptor) => descriptor.id), modelsFromModelSelect: false, + partialOptions: true, }); } @@ -700,6 +694,69 @@ function stripReasoningForDisabledModels( return changed ? next : models; } +function overlayPartialLiveOptions( + models: ReadonlyArray, + configuration: AcpRegistryLiveConfiguration, + selectedProbedModelId: string | null, + disabledReasoningSlugs: ReadonlySet, +): ReadonlyArray { + const modelOptionIds = new Set(configuration.modelOptionIds ?? []); + const sharedOverrides = new Map(); + const modelOverrides: Array = []; + for (const descriptor of configuration.configOptions) { + if (isModelSpecificDescriptor(descriptor, modelOptionIds)) { + modelOverrides.push(descriptor); + } else { + sharedOverrides.set(descriptor.id, descriptor); + } + } + const updated = models.map((model) => { + const existing = model.capabilities?.optionDescriptors ?? []; + const isCurrentModel = + !model.isCustom && + configuration.currentModelId !== null && + model.slug === configuration.currentModelId; + const reasoningDisabled = !model.isCustom && disabledReasoningSlugs.has(model.slug); + const nextDescriptors: Array = []; + for (const descriptor of existing) { + if (reasoningDisabled && descriptor.type === "select" && descriptor.role === "reasoning") { + continue; + } + const sharedOverride = sharedOverrides.get(descriptor.id); + if (sharedOverride !== undefined) { + const overlaid = compatibleLiveOptionValue(descriptor, sharedOverride); + nextDescriptors.push(Option.getOrElse(overlaid, () => descriptor)); + } else { + nextDescriptors.push(descriptor); + } + } + if (isCurrentModel) { + for (const override of modelOverrides) { + if (reasoningDisabled && override.type === "select" && override.role === "reasoning") { + continue; + } + const existingIndex = nextDescriptors.findIndex((item) => item.id === override.id); + if (existingIndex >= 0) { + const currentDescriptor = nextDescriptors[existingIndex]!; + const overlaid = compatibleLiveOptionValue(currentDescriptor, override); + nextDescriptors[existingIndex] = Option.getOrElse(overlaid, () => currentDescriptor); + } else { + nextDescriptors.push(override); + } + } + } + if (Equal.equals(existing, nextDescriptors)) return model; + return { + ...model, + capabilities: + nextDescriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: nextDescriptors }), + }; + }); + return withAcpRegistryDefaultModel(updated, selectedProbedModelId); +} + export function applyAcpRegistryLiveConfiguration( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, @@ -726,18 +783,25 @@ export function applyAcpRegistryLiveConfiguration( (configuration.models.length === 1 && !liveCatalogIsProvisional); const disabledReasoningSlugs: ReadonlySet = useLiveCatalog ? EMPTY_SLUG_SET - : (configuration.reasoningDisabledModelIds?.length ?? 0) === 0 - ? (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET) - : new Set([ - ...(options?.reasoningDisabledModelSlugs ?? []), - ...(configuration.reasoningDisabledModelIds ?? []), - ]); + : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); const liveCurrentModelInProbed = configuration.currentModelId !== null && probedModels.some((model) => model.slug === configuration.currentModelId); const selectedProbedModelId = liveCurrentModelInProbed ? configuration.currentModelId : (probedModels.find((model) => model.isDefault)?.slug ?? null); + if (!useLiveCatalog && configuration.partialOptions === true) { + return { + ...snapshot, + status: provider.enabled ? "ready" : provider.status, + models: overlayPartialLiveOptions( + provider.models, + configuration, + selectedProbedModelId, + disabledReasoningSlugs, + ), + }; + } // When retaining the probed catalog for a live session running an absent // model (e.g. a cold-start placeholder), keep only shared options and leave // each retained model's own learned options untouched. @@ -1156,14 +1220,7 @@ export const AcpRegistryDriver: ProviderDriver 0 - ? EMPTY_SLUG_SET - : (configuration.reasoningDisabledModelIds?.length ?? 0) === 0 - ? reasoningDisabledModelSlugs - : new Set([ - ...reasoningDisabledModelSlugs, - ...(configuration.reasoningDisabledModelIds ?? []), - ]); + configuration.models.length > 0 ? EMPTY_SLUG_SET : reasoningDisabledModelSlugs; return Ref.modify(learnedModels, (learned) => { const next = applyAcpRegistryLiveConfiguration( provider, @@ -1338,9 +1395,6 @@ export const AcpRegistryDriver: ProviderDriver liveConfigurationReplacesAcceptedCatalog(configuration, accepted), @@ -1430,7 +1487,7 @@ export const AcpRegistryDriver: ProviderDriver + retainConfiguration: (live) => retainAcpRegistryLiveOptionsAfterProbe(live, { models: probedModels, currentModelId: probedCurrentModelId, @@ -1608,12 +1665,7 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) .map((model) => model.id), ) - : (configuration.reasoningDisabledModelIds?.length ?? 0) > 0 - ? new Set([ - ...acceptedBefore.reasoningDisabledModelSlugs, - ...(configuration.reasoningDisabledModelIds ?? []), - ]) - : acceptedBefore.reasoningDisabledModelSlugs; + : acceptedBefore.reasoningDisabledModelSlugs; if (current.auth.status !== "unauthenticated" || replacesCatalog) { yield* Ref.update(acceptedCatalog, (previous) => replacesCatalog @@ -1627,7 +1679,6 @@ export const AcpRegistryDriver: ProviderDriver; + // Set on retained post-probe overrides so probe-only options stay untouched. + readonly partialOptions?: boolean; } export function normalizeAcpRegistryLiveConfiguration( @@ -268,9 +267,6 @@ export function normalizeAcpRegistryLiveConfiguration( .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config") .map((option) => option.id), ); - const reasoningDisabledModelIds = !includeCatalog - ? advertisedModels.filter((model) => model.reasoningEffort === null).map((model) => model.id) - : []; return { models: includeCatalog ? advertisedModels : [], currentModelId: currentModel === undefined ? null : currentModel.id, @@ -279,10 +275,26 @@ export function normalizeAcpRegistryLiveConfiguration( .filter((descriptor) => modelOptionIds.has(descriptor.id)) .map((descriptor) => descriptor.id), modelsFromModelSelect: includeCatalog && modelOption !== undefined, - ...(reasoningDisabledModelIds.length > 0 ? { reasoningDisabledModelIds } : {}), }; } +/** + * Stable key for the effective normalized model catalog advertised by a registry + * session, covering cap/overflow selection, names, provenance, and per-model reasoning. + */ +export function acpRegistrySessionCatalogKey( + configOptions: ReadonlyArray, + modelState?: EffectAcpSchema.SessionModelState | null, +): string { + const { models, modelsFromModelSelect } = normalizeAcpRegistryLiveConfiguration( + configOptions, + undefined, + modelState, + { includeCatalog: true }, + ); + return JSON.stringify([modelsFromModelSelect === true, models]); +} + const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({ slashCommands: [], skills: [], diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 26f5370ee82d9..9bb8d43c88cc9 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -112,7 +112,6 @@ import { import { ACP_EMPTY_OPTION_VALUE, ACP_SESSION_MODE_OPTION_ID, - acpSessionCatalogKey, flattenSelectChoices, } from "./sessionConfig.ts"; import * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; @@ -430,6 +429,10 @@ export interface AcpAdapterV2Flavor { readonly onAvailableCommandsUpdate?: ( commands: ReadonlyArray, ) => Effect.Effect; + readonly sessionCatalogKey?: ( + configOptions: ReadonlyArray, + modelState: EffectAcpSchema.SessionModelState | null | undefined, + ) => string; readonly onSessionConfigurationUpdate?: ( configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, @@ -2285,8 +2288,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); - // Track the model catalog last published for the active session so mid-session - // option updates do not re-advertise a frozen catalog over a newer periodic probe. + // Track the model catalog last published per session so mid-session option + // updates do not re-advertise a frozen catalog over a newer periodic probe; + // cache invalidation relies on the follow-up probe rather than session replay. const lastPublishedCatalogKey = yield* Ref.make<{ readonly epoch: number; readonly key: string | null; @@ -2295,19 +2299,45 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( epoch: current.epoch + 1, key: null, })); + const defaultSessionCatalogKey = ( + configOptions: ReadonlyArray, + modelState: EffectAcpSchema.SessionModelState | null | undefined, + ): string => { + const modelOption = findModelConfigOption(configOptions); + if (modelOption !== undefined) { + return JSON.stringify([ + "select", + flattenSelectChoices(modelOption.options).map((choice) => [ + choice.value, + choice.name, + choice.description ?? null, + ]), + ]); + } + return JSON.stringify([ + "models", + (modelState?.availableModels ?? []).map((model) => [ + model.modelId, + model.name, + model.description ?? null, + ]), + ]); + }; + const computeSessionCatalogKey = flavor.sessionCatalogKey ?? defaultSessionCatalogKey; const sessionConfigurationPublishPermit = yield* Semaphore.make(1); const publishSessionConfiguration = Effect.fn("AcpAdapterV2.publishSessionConfiguration")( function* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { - if (flavor.onSessionConfigurationUpdate === undefined) return; + const onSessionConfigurationUpdate = flavor.onSessionConfigurationUpdate; + if (onSessionConfigurationUpdate === undefined) return; yield* sessionConfigurationPublishPermit.withPermit( Effect.gen(function* () { const { epoch, key } = yield* Ref.get(lastPublishedCatalogKey); const configOptions = yield* targetRuntime.getConfigOptions; const modeState = yield* targetRuntime.getModeState; const modelState = (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models; - const catalogKey = acpSessionCatalogKey(configOptions, modelState); + const catalogKey = computeSessionCatalogKey(configOptions, modelState); const includeCatalog = key !== catalogKey; - yield* flavor.onSessionConfigurationUpdate!(configOptions, modeState, modelState, { + yield* onSessionConfigurationUpdate(configOptions, modeState, modelState, { includeCatalog, }); yield* Ref.update(lastPublishedCatalogKey, (current) => diff --git a/packages/provider-acp/src/server/sessionConfig.test.ts b/packages/provider-acp/src/server/sessionConfig.test.ts index 9378c1e6e4bb3..ceb6ceb92783a 100644 --- a/packages/provider-acp/src/server/sessionConfig.test.ts +++ b/packages/provider-acp/src/server/sessionConfig.test.ts @@ -1,11 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; -import { - ACP_MAX_CATALOG_MODELS, - ACP_SESSION_MODE_OPTION_ID, - acpProviderOptionDescriptors, - acpSessionCatalogKey, -} from "./sessionConfig.ts"; +import { ACP_SESSION_MODE_OPTION_ID, acpProviderOptionDescriptors } from "./sessionConfig.ts"; describe("acpProviderOptionDescriptors", () => { it("maps non-model select options and excludes model and collaboration categories", () => { @@ -214,57 +209,3 @@ describe("acpProviderOptionDescriptors", () => { }); }); }); - -describe("acpSessionCatalogKey", () => { - it("ignores selection changes within the retained catalog but changes on labels or overflow selection", () => { - const modelSelect = ( - currentValue: string, - options: ReadonlyArray<{ value: string; name: string; description?: string }>, - ) => [ - { - id: "model", - name: "Model", - category: "model" as const, - type: "select" as const, - currentValue, - options: [...options], - }, - ]; - const baseOptions = Array.from({ length: ACP_MAX_CATALOG_MODELS + 1 }, (_, index) => ({ - value: `m${index}`, - name: `Model ${index}`, - })); - - const selectedM0 = acpSessionCatalogKey(modelSelect("m0", baseOptions), undefined); - const selectedM1 = acpSessionCatalogKey(modelSelect("m1", baseOptions), undefined); - expect(selectedM1).toBe(selectedM0); - - // Selecting a model beyond the 256-model cap changes the retained catalog entry. - const selectedOverflow = acpSessionCatalogKey( - modelSelect(`m${ACP_MAX_CATALOG_MODELS}`, baseOptions), - undefined, - ); - expect(selectedOverflow).not.toBe(selectedM0); - - // Display-name or description updates within the retained catalog change the key too. - const renamed = acpSessionCatalogKey( - modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...baseOptions.slice(1)]), - undefined, - ); - expect(renamed).not.toBe(selectedM0); - - // Model-state catalogs follow the same cap and overflow-selection rule. - const availableModels = baseOptions.map((option) => ({ - modelId: option.value, - name: option.name, - })); - const stateM0 = acpSessionCatalogKey([], { currentModelId: "m0", availableModels }); - const stateM1 = acpSessionCatalogKey([], { currentModelId: "m1", availableModels }); - const stateOverflow = acpSessionCatalogKey([], { - currentModelId: `m${ACP_MAX_CATALOG_MODELS}`, - availableModels, - }); - expect(stateM1).toBe(stateM0); - expect(stateOverflow).not.toBe(stateM0); - }); -}); diff --git a/packages/provider-acp/src/server/sessionConfig.ts b/packages/provider-acp/src/server/sessionConfig.ts index ffc92e205a15f..af8ee0eec0f33 100644 --- a/packages/provider-acp/src/server/sessionConfig.ts +++ b/packages/provider-acp/src/server/sessionConfig.ts @@ -1,10 +1,9 @@ import type { ProviderOptionChoice, ProviderOptionDescriptor } from "@t3tools/contracts"; import type * as EffectAcpSchema from "effect-acp/compat"; -import { findModelConfigOption, type AcpSessionModeState } from "./runtimeModel.ts"; +import type { AcpSessionModeState } from "./runtimeModel.ts"; export const ACP_SESSION_MODE_OPTION_ID = "_t3/session-mode"; -export const ACP_MAX_CATALOG_MODELS = 256; /** Encodes a valid empty ACP choice as a non-empty T3 ID; map back before applying. */ export const ACP_EMPTY_OPTION_VALUE = "_t3/empty"; @@ -12,8 +11,6 @@ export const ACP_EMPTY_OPTION_VALUE = "_t3/empty"; const MAX_OPTION_DESCRIPTORS = 16; const MAX_OPTION_CHOICES = 64; const MAX_TEXT_LENGTH = 256; -const MAX_MODEL_ID_LENGTH = 128; -const MAX_MODEL_NAME_LENGTH = 160; const MAX_DESCRIPTION_LENGTH = 1_024; const boundedText = (value: string | null | undefined, maximumLength: number): string => @@ -36,65 +33,6 @@ export function flattenSelectChoices( return options.flatMap((candidate) => ("value" in candidate ? [candidate] : candidate.options)); } -/** - * Stable key for the effective model catalog advertised by a session, mirroring - * normalization's 256-model cap and overflow-selected retention while ignoring - * ordinary selection changes within the retained catalog. - */ -export function acpSessionCatalogKey( - configOptions: ReadonlyArray, - modelState: EffectAcpSchema.SessionModelState | null | undefined, -): string { - const modelOption = findModelConfigOption(configOptions); - const kind = modelOption?.type === "select" ? "select" : "models"; - const selectedId = - modelOption?.type === "select" - ? boundedOpaqueValue(modelOption.currentValue, MAX_MODEL_ID_LENGTH) - : modelState?.currentModelId === undefined - ? undefined - : boundedOpaqueValue(modelState.currentModelId, MAX_MODEL_ID_LENGTH); - const candidates: ReadonlyArray = - modelOption?.type === "select" - ? flattenSelectChoices(modelOption.options).map((choice) => [ - choice.value, - choice.name, - choice.description ?? null, - ]) - : (modelState?.availableModels ?? []).map((model) => [ - model.modelId, - model.name, - model.description ?? null, - ]); - const normalizeEntry = ( - id: string, - candidate: readonly [string, string, string | null], - ): readonly [string, string, string | null] => [ - id, - boundedText(candidate[1], MAX_MODEL_NAME_LENGTH) || id, - candidate[2] === null ? null : boundedText(candidate[2], MAX_DESCRIPTION_LENGTH) || null, - ]; - const seen = new Set(); - const retained: Array = []; - for (const candidate of candidates) { - if (retained.length === ACP_MAX_CATALOG_MODELS) break; - const id = boundedOpaqueValue(candidate[0], MAX_MODEL_ID_LENGTH); - if (id === undefined || seen.has(id)) continue; - seen.add(id); - retained.push(normalizeEntry(id, candidate)); - } - if ( - selectedId !== undefined && - retained.length === ACP_MAX_CATALOG_MODELS && - !seen.has(selectedId) - ) { - const selected = candidates.find((candidate) => candidate[0] === selectedId); - if (selected !== undefined) { - retained[ACP_MAX_CATALOG_MODELS - 1] = normalizeEntry(selectedId, selected); - } - } - return JSON.stringify([kind, retained]); -} - function selectChoices( candidates: ReadonlyArray<{ readonly value: string; From bd05986f32f341793563a35bcdad1b91519fa2b6 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 11:45:11 +0000 Subject: [PATCH 11/35] fix(acp-registry): reconcile superseded session options and coordinator watermarks --- .../Adapters/AcpAdapterV2.test.ts | 40 +- .../AcpRegistryRuntimeCoordinator.test.ts | 143 +++--- .../server/AcpRegistryRuntimeCoordinator.ts | 179 ++++---- .../src/server/adapter.ts | 29 +- .../src/server/driver.test.ts | 414 +++++++++++++++--- .../src/server/driver.ts | 270 +++++++----- .../provider-acp-registry/src/server/probe.ts | 77 ++-- packages/provider-acp/src/server/adapter.ts | 50 +-- 8 files changed, 805 insertions(+), 397 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 3499a66b4b7ee..7914901e866f7 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5083,7 +5083,9 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, onSessionConfigurationUpdate: (configOptions) => - Effect.sync(() => publishedConfigurations.push(configOptions)), + Effect.sync(() => { + publishedConfigurations.push(configOptions); + }), makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, @@ -5172,13 +5174,20 @@ describe("AcpAdapterV2", () => { : Effect.void, // Holds openSession's own publication until the adapter has seen the // late response, so adoption overlaps session configuration. - onSessionConfigurationUpdate: (configOptions, _modeState, _modelState, updateOptions) => - (publications++ === 0 ? Deferred.await(adoptionHandled) : Effect.void).pipe( + onSessionConfigurationUpdate: (configOptions, _modeState, _modelState, updateOptions) => { + const modelOption = configOptions.find( + (option) => option.category === "model" && option.type === "select", + ); + const catalogKey = JSON.stringify( + modelOption?.type === "select" ? modelOption.options : [], + ); + const includeCatalog = updateOptions?.lastCatalogKey !== catalogKey; + return (publications++ === 0 ? Deferred.await(adoptionHandled) : Effect.void).pipe( Effect.andThen( Effect.sync(() => publishedConfigurations.push({ configOptions, - includeCatalog: updateOptions?.includeCatalog, + includeCatalog, }), ), ), @@ -5187,7 +5196,9 @@ describe("AcpAdapterV2", () => { ? Deferred.succeed(adopted, undefined) : Effect.void, ), - ), + Effect.as(catalogKey), + ); + }, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, @@ -5304,14 +5315,23 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, onSessionConfigurationUpdate: ( - _configOptions, + configOptions, _modeState, _modelState, updateOptions, - ) => - Effect.sync(() => { - publications.push({ includeCatalog: updateOptions?.includeCatalog }); - }), + ) => { + const modelOption = configOptions.find( + (option) => option.category === "model" && option.type === "select", + ); + const catalogKey = JSON.stringify( + modelOption?.type === "select" ? modelOption.options : [], + ); + const includeCatalog = updateOptions?.lastCatalogKey !== catalogKey; + return Effect.sync(() => { + publications.push({ includeCatalog }); + return catalogKey; + }); + }, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 52269613fbb20..7ad8605faa5d2 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -397,7 +397,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { // Outdated catalogRevision cannot clear a newer catalog or advance clearedThroughRevision. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, first.revision, { + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: first.catalogRevision, }), ).toBe(false); @@ -405,7 +405,8 @@ describe("AcpRegistryRuntimeCoordinator", () => { (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, ).toBe(0); - // Catalog-scoped clear validates newer in-flight options-only updates through retainConfiguration. + // Catalog-scoped clear reconciles newer in-flight options-only updates through retain + // and advances clearedThroughRevision past them so delayed raw callbacks are skipped. const optionsOnlyConfig = { models: [], currentModelId: "model-v2", @@ -416,9 +417,9 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyConfig); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision, { + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: second.catalogRevision, - retainConfiguration: (live) => + retain: (live) => Option.some({ ...live, configOptions: [effortOption("low")], @@ -431,14 +432,13 @@ describe("AcpRegistryRuntimeCoordinator", () => { ...optionsOnlyConfig, configOptions: [effortOption("low")], }), - clearedThroughRevision: second.revision, + clearedThroughRevision: optionsSnap.revision, }); - // clearOptions: true wipes both catalog and options and advances clearedThroughRevision past optionsSnap. + // Omitting retain wipes both catalog and options while keeping clearedThroughRevision. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, second.revision, { + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: second.catalogRevision, - clearOptions: true, }), ).toBe(true); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ @@ -446,80 +446,79 @@ describe("AcpRegistryRuntimeCoordinator", () => { configuration: Option.none(), clearedThroughRevision: optionsSnap.revision, }); - - // Without retainConfiguration, clearing strips models while preserving non-empty options and drops empty ones. - yield* coordinator.publishLiveConfiguration(instanceId, { - ...configFor("model-v3"), - configOptions: [effortOption("low")], - modelOptionIds: ["effort"], - }); - const v3Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v3Snap.revision, { - catalogRevision: v3Snap.catalogRevision, - }), - ).toBe(true); - expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ - ...v3Snap, - configuration: Option.some({ - models: [], - currentModelId: "model-v3", - configOptions: [effortOption("low")], - modelOptionIds: ["effort"], - modelsFromModelSelect: false, - }), - clearedThroughRevision: v3Snap.revision, - }); - - yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v4")); - const v4Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, v4Snap.revision, { - catalogRevision: v4Snap.catalogRevision, - }), - ).toBe(true); - expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ - ...v4Snap, - configuration: Option.none(), - clearedThroughRevision: v4Snap.revision, - }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); - it.effect("delivers concurrent live configuration publications in strict revision order", () => + it.effect("replays raw options-only payloads when watching after the last catalog revision", () => Effect.gen(function* () { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const instanceId = ProviderInstanceId.make("acpRegistry_devin"); - const receivedRevisions: Array = []; - const allSeen = yield* Deferred.make(); - const watcher = yield* coordinator - .watchLiveConfiguration(instanceId, (_configuration, revision) => - Effect.sync(() => { - receivedRevisions.push(revision); - return receivedRevisions.length; - }).pipe( - Effect.flatMap((count) => - count === 4 ? Deferred.succeed(allSeen, undefined).pipe(Effect.asVoid) : Effect.void, + const catalogModels = [ + { id: "model-b", name: "Model B", description: null }, + { id: "model-c", name: "Model C", description: null }, + ]; + const effortOption = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; + + yield* coordinator.publishLiveConfiguration(instanceId, { + models: catalogModels, + currentModelId: "model-b", + configOptions: [], + modelsFromModelSelect: true, + }); + const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + const optionsOnly = { + models: [], + currentModelId: "model-b", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }; + yield* coordinator.publishLiveConfiguration(instanceId, optionsOnly); + const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + // A watcher already at the catalog revision receives the raw options-only payload on replay. + const rawReplay = yield* Deferred.make(); + const afterCatalogWatcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Deferred.succeed(rawReplay, [configuration.models.length, revision] as const).pipe( + Effect.asVoid, ), - ), + { afterRevision: catalogSnap.revision }, ) .pipe(Effect.forkChild({ startImmediately: true })); + expect(yield* Deferred.await(rawReplay)).toEqual([0, optionsSnap.revision]); + yield* Fiber.interrupt(afterCatalogWatcher); - yield* Effect.forEach( - [1, 2, 3, 4], - (index) => - coordinator.publishLiveConfiguration(instanceId, { - models: - index % 2 === 1 ? [{ id: `m${index}`, name: `m${index}`, description: null }] : [], - currentModelId: `m${index}`, - configOptions: [], - modelsFromModelSelect: index % 2 === 1, - }), - { concurrency: "unbounded", discard: true }, - ); - yield* Deferred.await(allSeen); - yield* Fiber.interrupt(watcher); - expect(receivedRevisions).toEqual([1, 2, 3, 4]); + // A watcher behind the catalog revision receives the preserved catalog alongside the options. + const fullReplay = yield* Deferred.make(); + const beforeCatalogWatcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Deferred.succeed(fullReplay, [configuration.models.length, revision] as const).pipe( + Effect.asVoid, + ), + { afterRevision: 0 }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + expect(yield* Deferred.await(fullReplay)).toEqual([ + catalogModels.length, + optionsSnap.revision, + ]); + yield* Fiber.interrupt(beforeCatalogWatcher); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 7332fd85c2cee..1eae61b376636 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -36,6 +36,11 @@ export interface AcpRegistryLiveConfigurationSnapshot { readonly clearedThroughRevision: number; } +interface StoredLiveConfiguration extends AcpRegistryLiveConfigurationSnapshot { + readonly lastPublishedConfiguration: Option.Option; + readonly lastCatalogPublishedRevision: number; +} + export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { configuration: Option.none(), revision: 0, @@ -43,6 +48,21 @@ export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnap clearedThroughRevision: 0, }; +const EMPTY_STORED_LIVE_CONFIGURATION: StoredLiveConfiguration = { + ...EMPTY_LIVE_CONFIGURATION_SNAPSHOT, + lastPublishedConfiguration: Option.none(), + lastCatalogPublishedRevision: 0, +}; + +const toPublicLiveConfigurationSnapshot = ( + entry: StoredLiveConfiguration, +): AcpRegistryLiveConfigurationSnapshot => ({ + configuration: entry.configuration, + revision: entry.revision, + catalogRevision: entry.catalogRevision, + clearedThroughRevision: entry.clearedThroughRevision, +}); + interface UrlAuthActionUpdate { readonly instanceId: ProviderInstanceId; readonly action: AcpRegistryUrlAuthAction | null; @@ -85,11 +105,9 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; readonly clearLiveConfigurationIfRevision: ( instanceId: ProviderInstanceId, - revision: number, options: { readonly catalogRevision: number; - readonly clearOptions?: boolean; - readonly retainConfiguration?: ( + readonly retain?: ( configuration: AcpRegistryLiveConfiguration, ) => Option.Option; }, @@ -138,7 +156,7 @@ const make = Effect.gen(function* () { ); const liveConfigurationUpdates = yield* PubSub.unbounded(); const liveConfigurations = yield* Ref.make< - ReadonlyMap + ReadonlyMap >(new Map()); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( @@ -247,15 +265,16 @@ const make = Effect.gen(function* () { const nextCleared = Math.max(current.clearedThroughRevision, current.revision); if ( Option.isNone(current.configuration) && + Option.isNone(current.lastPublishedConfiguration) && nextCleared === current.clearedThroughRevision ) { return state; } const next = new Map(state); next.set(instanceId, { + ...current, configuration: Option.none(), - revision: current.revision, - catalogRevision: current.catalogRevision, + lastPublishedConfiguration: Option.none(), clearedThroughRevision: nextCleared, }); return next; @@ -263,33 +282,28 @@ const make = Effect.gen(function* () { const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( - function* (instanceId, revision, options) { + function* (instanceId, options) { return yield* Ref.modify(liveConfigurations, (state) => { - const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + const current = state.get(instanceId) ?? EMPTY_STORED_LIVE_CONFIGURATION; if (current.catalogRevision !== options.catalogRevision) { return [false, state] as const; } - const clearAll = options.clearOptions === true; - const nextCleared = clearAll - ? Math.max(current.clearedThroughRevision, current.revision, revision) - : Math.max(current.clearedThroughRevision, revision); - const nextConfiguration: Option.Option = clearAll - ? Option.none() - : Option.flatMap(current.configuration, (configuration) => { - const withoutCatalog: AcpRegistryLiveConfiguration = { - ...configuration, - models: [], - modelsFromModelSelect: false, - }; - if (options.retainConfiguration !== undefined) { - return options.retainConfiguration(withoutCatalog); - } - return withoutCatalog.configOptions.length > 0 - ? Option.some(withoutCatalog) - : Option.none(); - }); + // Every revision through current.revision is either cleared or reconciled by retain. + const nextCleared = Math.max(current.clearedThroughRevision, current.revision); + const retain = options.retain; + const nextConfiguration: Option.Option = + retain === undefined + ? Option.none() + : Option.flatMap(current.configuration, (configuration) => + retain({ + ...configuration, + models: [], + modelsFromModelSelect: false, + }), + ); if ( Equal.equals(current.configuration, nextConfiguration) && + Equal.equals(current.lastPublishedConfiguration, nextConfiguration) && nextCleared === current.clearedThroughRevision ) { return [true, state] as const; @@ -298,6 +312,7 @@ const make = Effect.gen(function* () { next.set(instanceId, { ...current, configuration: nextConfiguration, + lastPublishedConfiguration: nextConfiguration, clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -307,61 +322,71 @@ const make = Effect.gen(function* () { const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => - // Serialize store + PubSub publish so concurrent sessions emit in revision order. + // Serialize store + PubSub publish uninterruptibly so concurrent sessions emit in revision order. liveConfigurationPublishPermit.withPermit( - Ref.modify(liveConfigurations, (state) => { - const current = state.get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT; - const revision = current.revision + 1; - const hasCatalog = configuration.models.length > 0; - const catalogRevision = hasCatalog - ? current.catalogRevision + 1 - : current.catalogRevision; - // Preserve an unsuperseded session catalog across options-only updates only when - // the update targets that catalog (or no model), keeping the default marker intact. - const canPreserveStoredCatalog = - !hasCatalog && - Option.isSome(current.configuration) && - current.configuration.value.models.length > 0 && - (configuration.currentModelId === null || - current.configuration.value.models.some( - (model) => model.id === configuration.currentModelId, - )); - const storedConfiguration: AcpRegistryLiveConfiguration = - canPreserveStoredCatalog && Option.isSome(current.configuration) - ? { - ...configuration, - models: current.configuration.value.models, - ...(current.configuration.value.modelsFromModelSelect === undefined - ? {} - : { modelsFromModelSelect: current.configuration.value.modelsFromModelSelect }), - } - : configuration; - const next = new Map(state); - next.set(instanceId, { - configuration: Option.some(storedConfiguration), - revision, - catalogRevision, - clearedThroughRevision: current.clearedThroughRevision, - }); - return [revision, next] as const; - }).pipe( - Effect.flatMap((revision) => - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, + Effect.uninterruptible( + Ref.modify(liveConfigurations, (state) => { + const current = state.get(instanceId) ?? EMPTY_STORED_LIVE_CONFIGURATION; + const revision = current.revision + 1; + const hasCatalog = configuration.models.length > 0; + const catalogRevision = hasCatalog + ? current.catalogRevision + 1 + : current.catalogRevision; + const lastCatalogPublishedRevision = hasCatalog + ? revision + : current.lastCatalogPublishedRevision; + // Preserve an unsuperseded session catalog across options-only updates only when + // the update targets that catalog (or no model), keeping the default marker intact. + const canPreserveStoredCatalog = + !hasCatalog && + Option.isSome(current.configuration) && + current.configuration.value.models.length > 0 && + (configuration.currentModelId === null || + current.configuration.value.models.some( + (model) => model.id === configuration.currentModelId, + )); + const storedConfiguration: AcpRegistryLiveConfiguration = + canPreserveStoredCatalog && Option.isSome(current.configuration) + ? { + ...configuration, + models: current.configuration.value.models, + ...(current.configuration.value.modelsFromModelSelect === undefined + ? {} + : { + modelsFromModelSelect: current.configuration.value.modelsFromModelSelect, + }), + } + : configuration; + const next = new Map(state); + next.set(instanceId, { + configuration: Option.some(storedConfiguration), + lastPublishedConfiguration: Option.some(configuration), revision, - }), + catalogRevision, + lastCatalogPublishedRevision, + clearedThroughRevision: current.clearedThroughRevision, + }); + return [revision, next] as const; + }).pipe( + Effect.flatMap((revision) => + PubSub.publish(liveConfigurationUpdates, { + instanceId, + configuration, + revision, + }), + ), + Effect.asVoid, ), - Effect.asVoid, ), ); const getLiveConfigurationWithRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationWithRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfigurationWithRevision")( function* (instanceId) { - return ( - (yield* Ref.get(liveConfigurations)).get(instanceId) ?? EMPTY_LIVE_CONFIGURATION_SNAPSHOT - ); + const entry = (yield* Ref.get(liveConfigurations)).get(instanceId); + return entry === undefined + ? EMPTY_LIVE_CONFIGURATION_SNAPSHOT + : toPublicLiveConfigurationSnapshot(entry); }, ); @@ -384,7 +409,13 @@ const make = Effect.gen(function* () { (afterRevision === undefined || current.revision > afterRevision) ) { deliveredRevision = current.revision; - yield* onUpdate(current.configuration.value, current.revision); + const replayConfiguration = + afterRevision !== undefined && + current.lastCatalogPublishedRevision <= afterRevision && + Option.isSome(current.lastPublishedConfiguration) + ? current.lastPublishedConfiguration.value + : current.configuration.value; + yield* onUpdate(replayConfiguration, current.revision); } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8bd9f87f504ba..71c5bd42bfac6 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -41,10 +41,9 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { - acpRegistrySessionCatalogKey, normalizeAcpRegistryCommands, - normalizeAcpRegistryLiveConfiguration, normalizeAcpRegistryWebUrl, + prepareAcpRegistryLiveConfiguration, } from "./probe.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -375,17 +374,21 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), - sessionCatalogKey: acpRegistrySessionCatalogKey, - onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => - runtimeCoordinator.publishLiveConfiguration( - options.instanceId, - normalizeAcpRegistryLiveConfiguration( - configOptions, - modeState, - modelState, - updateOptions, - ), - ), + onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => { + const prepared = prepareAcpRegistryLiveConfiguration( + configOptions, + modeState, + modelState, + ); + return runtimeCoordinator + .publishLiveConfiguration( + options.instanceId, + prepared.toLiveConfiguration({ + includeCatalog: updateOptions?.lastCatalogKey !== prepared.catalogKey, + }), + ) + .pipe(Effect.as(prepared.catalogKey)); + }, onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); if (normalizedUrl === undefined || elicitationId.trim().length === 0) { diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 233e4cb2947fd..ade96e0b3797d 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -40,8 +40,8 @@ import { import { acpRegistryAdvertisesModelCatalog, acpRegistryProbeResult, - acpRegistrySessionCatalogKey, normalizeAcpRegistryLiveConfiguration, + prepareAcpRegistryLiveConfiguration, } from "./probe.ts"; const decodeSettings = Schema.decodeSync(AcpRegistrySettings); @@ -434,8 +434,17 @@ describe("acpRegistrySnapshotReadiness", () => { ).models.map((model) => model.capabilities?.optionDescriptors ?? []); expect(currentDisabled).toEqual([[], []]); - // Options-only updates (includeCatalog: false) must also strip effort on a reasoning-disabled current model. - const optionsOnlyDisabled = normalizeAcpRegistryLiveConfiguration( + // supportsReasoningEffort: false marks reasoning disabled even without an effort selector, + // and strips current-model reasoning consistently regardless of includeCatalog. + const disabledWithoutSelector = normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "glm", + availableModels: [{ modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }], + }); + expect(disabledWithoutSelector.models).toEqual([ + { id: "glm", name: "GLM", description: null, reasoningEffort: null }, + ]); + + const catalogDisabled = normalizeAcpRegistryLiveConfiguration( [effort], undefined, { @@ -445,19 +454,26 @@ describe("acpRegistrySnapshotReadiness", () => { { modelId: "opus", name: "Opus" }, ], }, - { includeCatalog: false }, + { includeCatalog: true }, ); - expect(optionsOnlyDisabled.configOptions).toEqual([]); - expect(optionsOnlyDisabled.modelOptionIds).toEqual([]); - const providerAfterCatalogDisable = applyAcpRegistryLiveConfiguration( - provider, - normalizeAcpRegistryLiveConfiguration([effort], undefined, { + const optionsOnlyDisabled = normalizeAcpRegistryLiveConfiguration( + [effort], + undefined, + { currentModelId: "glm", availableModels: [ { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, { modelId: "opus", name: "Opus" }, ], - }), + }, + { includeCatalog: false }, + ); + expect(catalogDisabled.configOptions).toEqual([]); + expect(optionsOnlyDisabled.configOptions).toEqual(catalogDisabled.configOptions); + expect(optionsOnlyDisabled.modelOptionIds).toEqual([]); + const providerAfterCatalogDisable = applyAcpRegistryLiveConfiguration( + provider, + catalogDisabled, [], ); expect( @@ -988,6 +1004,27 @@ describe("acpRegistrySnapshotReadiness", () => { ); expect(afterProvisionalModelOnly.models).toBe(entitled.models); + // An options-only update with no currentModelId on a discovered catalog applies only + // shared options and must not overwrite the default model's own options. + const afterUnknownModelOptions = applyAcpRegistryLiveConfiguration( + entitled, + { + models: [], + currentModelId: null, + configOptions: [placeholderEffort, sharedMode], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + entitled.models, + { preserveSingleModelCatalog: true }, + ); + expect(afterUnknownModelOptions.models.find((m) => m.slug === "gmodel")?.isDefault).toBe(true); + expect( + afterUnknownModelOptions.models.find((m) => m.slug === "gmodel")?.capabilities + ?.optionDescriptors, + ).toEqual([sharedMode, entitledEffort]); + const replacedExplicit = applyAcpRegistryLiveConfiguration( entitled, { @@ -1476,10 +1513,32 @@ describe("acpRegistryEnrichmentCache", () => { }, ), ).toEqual(Option.none()); + + // Never promotes a live model-specific option into a probe-shared option across models. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [fast(true)], + modelOptionIds: ["fast"], + modelsFromModelSelect: false, + }, + { + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null }, + ], + currentModelId: "new-model", + configOptions: [fast(false)], + modelOptionIds: new Set(), + }, + ), + ).toEqual(Option.none()); }); }); -describe("acpRegistrySessionCatalogKey", () => { +describe("prepareAcpRegistryLiveConfiguration", () => { it("ignores in-cap selection and effort value tweaks while detecting overflow selection, renames, and newly normalized per-model reasoning", () => { const modelSelect = ( currentValue: string, @@ -1499,13 +1558,15 @@ describe("acpRegistrySessionCatalogKey", () => { name: `Model ${index}`, })); - const keyM0 = acpRegistrySessionCatalogKey(modelSelect("m0", choices)); - expect(acpRegistrySessionCatalogKey(modelSelect("m1", choices))).toBe(keyM0); - expect(acpRegistrySessionCatalogKey(modelSelect("m256", choices))).not.toBe(keyM0); + const keyM0 = prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).catalogKey; + expect(prepareAcpRegistryLiveConfiguration(modelSelect("m1", choices)).catalogKey).toBe(keyM0); + expect(prepareAcpRegistryLiveConfiguration(modelSelect("m256", choices)).catalogKey).not.toBe( + keyM0, + ); expect( - acpRegistrySessionCatalogKey( + prepareAcpRegistryLiveConfiguration( modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...choices.slice(1)]), - ), + ).catalogKey, ).not.toBe(keyM0); // When a session initially omits the effort selector and later exposes it, another model's @@ -1536,9 +1597,17 @@ describe("acpRegistrySessionCatalogKey", () => { { value: "high", name: "High" }, ], }); - const withoutEffort = acpRegistrySessionCatalogKey([], modelState); - const withEffortHigh = acpRegistrySessionCatalogKey([effortSelect("high")], modelState); - const withEffortLow = acpRegistrySessionCatalogKey([effortSelect("low")], modelState); + const withoutEffort = prepareAcpRegistryLiveConfiguration([], undefined, modelState).catalogKey; + const withEffortHigh = prepareAcpRegistryLiveConfiguration( + [effortSelect("high")], + undefined, + modelState, + ).catalogKey; + const withEffortLow = prepareAcpRegistryLiveConfiguration( + [effortSelect("low")], + undefined, + modelState, + ).catalogKey; expect(withEffortHigh).not.toBe(withoutEffort); expect(withEffortLow).toBe(withEffortHigh); }); @@ -1937,6 +2006,89 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = expect(effortBySlug(yield* instance.snapshot.getSnapshot)).toBe( "model-a:effort,model-b:effort", ); + + // A reasoning-disabled model keeps its learned model_config options when switching to + // another model and tweaking shared options. + const variantLearned = yield* waitFor("model-a:mode+effort,model-b:mode+variant").pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "ask", + options: [ + { value: "ask", name: "Ask" }, + { value: "code", name: "Code" }, + ], + }, + { + id: "variant", + name: "Variant", + category: "model_config", + type: "select", + currentValue: "v1", + options: [{ value: "v1", name: "V1" }], + }, + ], + undefined, + { + currentModelId: "model-b", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-b", name: "model-b", _meta: { supportsReasoningEffort: false } }, + ], + }, + ), + ); + yield* Fiber.join(variantLearned); + + const modeTweaked = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "model-a") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "mode") + ?.currentValue === "code", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "code", + options: [ + { value: "ask", name: "Ask" }, + { value: "code", name: "Code" }, + ], + }, + ], + undefined, + { + currentModelId: "model-a", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-b", name: "model-b", _meta: { supportsReasoningEffort: false } }, + ], + }, + { includeCatalog: false }, + ), + ); + expect(effortBySlug(Option.getOrThrow(yield* Fiber.join(modeTweaked)))).toBe( + "model-a:mode,model-b:mode+variant", + ); }), ); }); @@ -2112,16 +2264,40 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* Fiber.join(learnedEffort); - // Upstream adds a model, removes the shared legacy option, and disables reasoning on other-model. - yield* writeModels([ - "new-model", - "old-model", - { - modelId: "other-model", - name: "other-model", - _meta: { supportsReasoningEffort: false }, - }, - ]); + // Upstream adds a model and a probe-only shared option (fast), removes the shared legacy + // option, and disables reasoning on other-model. + yield* writeModels({ + models: [ + "new-model", + "old-model", + { + modelId: "other-model", + name: "other-model", + _meta: { supportsReasoningEffort: false }, + }, + ], + configOptions: [ + { + id: "fast", + name: "Fast", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + }); yield* TestClock.adjust("16 minutes"); const postTtl = yield* waitForEnriched().pipe( @@ -2134,22 +2310,30 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "old-model", "other-model", ]); - // old-model keeps its live effort value (low) while legacy is dropped and other-model has no effort. + // old-model keeps its live effort value (low) alongside probe-only fast=on while legacy is dropped. expect( updated.models .find((model) => model.slug === "old-model") ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), - ).toEqual([["effort", "low"]]); + ).toEqual([ + ["fast", "on"], + ["effort", "low"], + ]); expect( updated.models .find((model) => model.slug === "other-model") - ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], - ).toEqual([]); + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]) ?? + [], + ).toEqual([["fast", "on"]]); expect( updated.models .find((model) => model.slug === "new-model") - ?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [], - ).toEqual(["effort"]); + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]) ?? + [], + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); // Coordinator retains live option values (with models stripped) for Copilot unsetOptionDefaults. expect( Option.map(yield* coordinator.getLiveConfiguration(identity.instanceId), (config) => ({ @@ -2158,7 +2342,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { })), ).toEqual(Option.some({ models: [], effort: "low" })); - // A mid-session option update (includeCatalog: false) keeps the newly probed catalog intact. + // A mid-session options-only update from the older superseded session (lacking probe-only + // fast and still carrying removed legacy) keeps the new catalog, keeps fast=on, and drops legacy. const effortUpdated = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => @@ -2172,21 +2357,51 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - sessionWithOptions("old-model", "high", { includeCatalog: false }), + sessionWithOptions("old-model", "high", { includeCatalog: false, includeLegacy: true }), ); + const afterSupersededOptions = Option.getOrThrow(yield* Fiber.join(effortUpdated)); + expect(afterSupersededOptions.models.map((model) => model.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); expect( - Option.getOrThrow(yield* Fiber.join(effortUpdated)).models.map((model) => model.slug), - ).toEqual(["new-model", "old-model", "other-model"]); + afterSupersededOptions.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); + expect( + afterSupersededOptions.models + .find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); - // Cached refresh must reuse the cached catalog without re-probing. + // Cached refresh must reuse the cached catalog and probe-only options without re-probing. yield* writeModels(["unexpected-reprobe", "other-model"]); const nextCached = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; + const cachedAfterSuperseded = Option.getOrThrow(yield* Fiber.join(nextCached)); + expect(cachedAfterSuperseded.models.map((model) => model.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); expect( - Option.getOrThrow(yield* Fiber.join(nextCached)).models.map((model) => model.slug), - ).toEqual(["new-model", "old-model", "other-model"]); + cachedAfterSuperseded.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); // When a later post-TTL probe runs directly on old-model without effort, learned effort is dropped. yield* writeModels(["old-model", "new-model"]); @@ -2466,7 +2681,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { const probeEntered = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); + const signOutRejected = yield* Deferred.make(); let gateNextResolve = false; + let injectCatalogBeforeSignOutClear = false; const { directory, coordinator, @@ -2477,6 +2694,28 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { } = yield* setupPeriodicDriver({ prefix: "acp-driver-clear-", initialModels: ["new-model", "old-model", "other-model"], + wrapCoordinator: (base) => ({ + ...base, + clearLiveConfigurationIfRevision: (instanceId, options) => + Effect.gen(function* () { + if (injectCatalogBeforeSignOutClear && options.retain === undefined) { + injectCatalogBeforeSignOutClear = false; + yield* base.publishLiveConfiguration(instanceId, { + models: [ + { id: "raced-auth-a", name: "Raced Auth A", description: null }, + { id: "raced-auth-b", name: "Raced Auth B", description: null }, + ], + currentModelId: "raced-auth-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); + yield* Deferred.succeed(signOutRejected, undefined); + return cleared; + } + return yield* base.clearLiveConfigurationIfRevision(instanceId, options); + }), + }), onResolve: () => Effect.gen(function* () { if (gateNextResolve) { @@ -2666,6 +2905,27 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ]); }), ); + + // If a newer live catalog lands right before an unauthenticated probe clears + // coordinator state, clearLiveConfigurationIfRevision returns false and the stale + // sign-out warning must be discarded rather than overwriting the new catalog. + yield* writeModels({ fail: "Sign in required", code: -32000 }); + injectCatalogBeforeSignOutClear = true; + const racedLiveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.map((m) => m.slug).join() === "raced-auth-a,raced-auth-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(signOutRejected); + const racedSnap = Option.getOrThrow(yield* Fiber.join(racedLiveApplied)); + expect(racedSnap.status).toBe("ready"); + expect(racedSnap.auth.status).not.toBe("unauthenticated"); + expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); }), ); @@ -2845,12 +3105,16 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); it.effect( - "commits a fresh post-TTL catalog when only an options-only live update arrives in flight while enforcing disabled reasoning", + "commits a fresh post-TTL catalog when only an options-only live update arrives in flight while suppressing delayed raw callbacks", () => Effect.gen(function* () { const secondProbeEntered = yield* Deferred.make(); const releaseSecondProbe = yield* Deferred.make(); + const delayedOptionsEntered = yield* Deferred.make(); + const releaseDelayedOptions = yield* Deferred.make(); + const delayedOptionsDone = yield* Deferred.make(); let gateNextResolve = false; + let holdNextOptionsCallback = false; const { coordinator, @@ -2861,6 +3125,26 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { } = yield* setupPeriodicDriver({ prefix: "acp-driver-inflight-options-", initialModels: ["old-model", "other-model"], + wrapCoordinator: (base) => ({ + ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + holdNextOptionsCallback && configuration.models.length === 0 + ? Effect.sync(() => { + holdNextOptionsCallback = false; + }).pipe( + Effect.andThen(Deferred.succeed(delayedOptionsEntered, undefined)), + Effect.andThen(Deferred.await(releaseDelayedOptions)), + Effect.andThen(onUpdate(configuration, revision)), + Effect.andThen(Deferred.succeed(delayedOptionsDone, undefined)), + Effect.asVoid, + ) + : onUpdate(configuration, revision), + options, + ), + }), onResolve: () => Effect.gen(function* () { if (gateNextResolve) { @@ -2916,18 +3200,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Deferred.await(secondProbeEntered); - const optionsApplied = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.find((option) => option.id === "mode") - ?.currentValue === "plan", - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - // Live update sets mode=plan (still valid) and effort=high (removed by the probe). + // Hold the raw watcher callback for this in-flight options-only revision until after the + // probe commits, verifying clearedThroughRevision suppresses it after retain reconciles it. + holdNextOptionsCallback = true; yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [], currentModelId: "old-model", @@ -2957,7 +3232,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { modelOptionIds: ["effort"], modelsFromModelSelect: false, }); - yield* Fiber.join(optionsApplied); + yield* Deferred.await(delayedOptionsEntered); const committed = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -2984,6 +3259,18 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), ).toEqual([["mode", "plan"]]); + // Releasing the delayed raw watcher callback must not bring back removed effort=high. + yield* Deferred.succeed(releaseDelayedOptions, undefined); + yield* Deferred.await(delayedOptionsDone); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["mode", "plan"], + ["effort", "low"], + ]); + // Verify the fresh catalog was saved to acceptedCatalog (survives skipped readiness) and cache. yield* withBlockedForegroundStartup( Effect.gen(function* () { @@ -2999,9 +3286,20 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* writeModels(["unexpected-reprobe", "other-model"]); const cached = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); yield* instance.snapshot.refresh; + const cachedSnapshot = Option.getOrThrow(yield* Fiber.join(cached)); + expect(cachedSnapshot.models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); expect( - Option.getOrThrow(yield* Fiber.join(cached)).models.map((model) => model.slug), - ).toEqual(["old-model", "other-model", "new-model"]); + cachedSnapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["mode", "plan"], + ["effort", "low"], + ]); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b6326c54a28a7..1caf632360a18 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -86,11 +86,19 @@ interface AcpRegistryEnrichmentCache { } | null; } +interface AcpRegistryProbeOptionSchema { + readonly models: ReadonlyArray; + readonly currentModelId: string | null; + readonly configOptions: ReadonlyArray; + readonly modelOptionIds: ReadonlySet; +} + interface AcceptedAcpRegistryCatalog { readonly models: ReadonlyArray; readonly builtInModelCount: number; readonly modelsFromModelSelect: boolean; readonly reasoningDisabledModelSlugs: ReadonlySet; + readonly probeOptions: AcpRegistryProbeOptionSchema | null; } const EMPTY_SLUG_SET: ReadonlySet = new Set(); @@ -100,6 +108,7 @@ const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { builtInModelCount: 0, modelsFromModelSelect: false, reasoningDisabledModelSlugs: EMPTY_SLUG_SET, + probeOptions: null, }; function isExplicitSingletonCatalog(catalog: { @@ -222,14 +231,15 @@ const makeUnsupportedTextGeneration = (): ProviderTextGeneration => { }; }; +function isReasoningDescriptor(descriptor: ProviderOptionDescriptor): boolean { + return descriptor.type === "select" && descriptor.role === "reasoning"; +} + function isModelSpecificDescriptor( descriptor: ProviderOptionDescriptor, modelOptionIds: ReadonlySet, ): boolean { - return ( - modelOptionIds.has(descriptor.id) || - (descriptor.type === "select" && descriptor.role === "reasoning") - ); + return modelOptionIds.has(descriptor.id) || isReasoningDescriptor(descriptor); } function modelWithSpecificOptions( @@ -264,10 +274,23 @@ function updateLearnedModelsFromLive( const hasAdvertisedReasoning = configuredById.get(model.slug)?.reasoningEffort !== undefined; const isReasoningDisabled = disabledReasoningSlugs.has(model.slug); if (!isCurrentModel && !hasAdvertisedReasoning && !isReasoningDisabled) continue; - const specific = (model.capabilities?.optionDescriptors ?? []).filter((descriptor) => - isModelSpecificDescriptor(descriptor, modelOptionIds), - ); + const descriptors = model.capabilities?.optionDescriptors ?? []; const previous = learnedBySlug.get(model.slug); + const previousDescriptors = previous?.capabilities?.optionDescriptors ?? []; + const previousIds = new Set(previousDescriptors.map((descriptor) => descriptor.id)); + const specific = isCurrentModel + ? configuration.partialOptions === true + ? descriptors.filter( + (descriptor) => + (isModelSpecificDescriptor(descriptor, modelOptionIds) || + previousIds.has(descriptor.id)) && + (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), + ) + : descriptors.filter((descriptor) => isModelSpecificDescriptor(descriptor, modelOptionIds)) + : [ + ...descriptors.filter(isReasoningDescriptor), + ...previousDescriptors.filter((descriptor) => !isReasoningDescriptor(descriptor)), + ]; if (specific.length === 0) { if (previous !== undefined) { learnedBySlug.delete(model.slug); @@ -305,12 +328,7 @@ function compatibleLiveOptionValue( */ export function retainAcpRegistryLiveOptionsAfterProbe( live: AcpRegistryLiveConfiguration, - probe: { - readonly models: ReadonlyArray; - readonly currentModelId: string | null; - readonly configOptions: ReadonlyArray; - readonly modelOptionIds: ReadonlySet; - }, + probe: AcpRegistryProbeOptionSchema, ): Option.Option { if (live.configOptions.length === 0) return Option.none(); const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); @@ -319,23 +337,26 @@ export function retainAcpRegistryLiveOptionsAfterProbe( const currentProbedModel = live.currentModelId === null ? undefined : probedModelById.get(live.currentModelId); + const probeSharedIds = new Set(); const sharedDescriptors: Array = []; for (const descriptor of probe.configOptions) { if (isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; - const retained = compatibleLiveOptionValue(descriptor, liveById.get(descriptor.id)); + probeSharedIds.add(descriptor.id); + const liveMatch = liveById.get(descriptor.id); + if (liveMatch === undefined || isModelSpecificDescriptor(liveMatch, liveModelOptionIds)) { + continue; + } + const retained = compatibleLiveOptionValue(descriptor, liveMatch); if (Option.isSome(retained)) sharedDescriptors.push(retained.value); } - const sharedIds = new Set(sharedDescriptors.map((descriptor) => descriptor.id)); const modelDescriptors: Array = []; if (currentProbedModel !== undefined) { const reasoningDisabled = currentProbedModel.reasoningEffort === null; if (currentProbedModel.id === probe.currentModelId) { for (const descriptor of probe.configOptions) { - if (sharedIds.has(descriptor.id)) continue; - if (reasoningDisabled && descriptor.type === "select" && descriptor.role === "reasoning") { - continue; - } + if (!isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; + if (reasoningDisabled && isReasoningDescriptor(descriptor)) continue; const retained = compatibleLiveOptionValue(descriptor, liveById.get(descriptor.id)); if (Option.isSome(retained)) modelDescriptors.push(retained.value); } @@ -343,9 +364,9 @@ export function retainAcpRegistryLiveOptionsAfterProbe( const advertisedReasoning = currentProbedModel.reasoningEffort; let addedAdvertisedReasoning = false; for (const descriptor of live.configOptions) { - if (sharedIds.has(descriptor.id)) continue; + if (probeSharedIds.has(descriptor.id)) continue; if (!isModelSpecificDescriptor(descriptor, liveModelOptionIds)) continue; - if (descriptor.type === "select" && descriptor.role === "reasoning") { + if (isReasoningDescriptor(descriptor)) { if (reasoningDisabled) continue; if (advertisedReasoning != null) { if (!addedAdvertisedReasoning) { @@ -377,6 +398,20 @@ export function retainAcpRegistryLiveOptionsAfterProbe( }); } +function reconcileLiveConfigurationAgainstAccepted( + configuration: AcpRegistryLiveConfiguration, + accepted: AcceptedAcpRegistryCatalog, +): Option.Option { + if ( + liveConfigurationReplacesAcceptedCatalog(configuration, accepted) || + configuration.partialOptions === true || + accepted.probeOptions === null + ) { + return Option.some(configuration); + } + return retainAcpRegistryLiveOptionsAfterProbe(configuration, accepted.probeOptions); +} + function mergeLearnedModelOptions( models: ReadonlyArray, learned: ReadonlyArray, @@ -802,20 +837,22 @@ export function applyAcpRegistryLiveConfiguration( ), }; } - // When retaining the probed catalog for a live session running an absent - // model (e.g. a cold-start placeholder), keep only shared options and leave - // each retained model's own learned options untouched. + // When retaining a discovered catalog for a live session with an absent or + // unknown current model, keep only shared options and leave each model's own + // options untouched. Only the synthetic "default" placeholder accepts them. + const hasSyntheticDefaultOnly = probedModels.length === 1 && probedModels[0]?.slug === "default"; const dropUnmatchedModelOptions = - !useLiveCatalog && configuration.currentModelId !== null && !liveCurrentModelInProbed; + !useLiveCatalog && + !liveCurrentModelInProbed && + !(configuration.currentModelId === null && hasSyntheticDefaultOnly); const unmatchedModelOptionIds = dropUnmatchedModelOptions ? new Set(configuration.modelOptionIds ?? []) : EMPTY_SLUG_SET; - const effectiveConfigOptions = - unmatchedModelOptionIds.size === 0 - ? configuration.configOptions - : configuration.configOptions.filter( - (descriptor) => !unmatchedModelOptionIds.has(descriptor.id), - ); + const effectiveConfigOptions = dropUnmatchedModelOptions + ? configuration.configOptions.filter( + (descriptor) => !isModelSpecificDescriptor(descriptor, unmatchedModelOptionIds), + ) + : configuration.configOptions; const discovery = useLiveCatalog ? configuration : { @@ -1214,27 +1251,39 @@ export const AcpRegistryDriver: ProviderDriver Ref.get(acceptedCatalog).pipe( - Effect.flatMap((accepted) => { - const preserveSingleModelCatalog = - options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); - const reasoningDisabledModelSlugs = - options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; - const disabledForLearning = - configuration.models.length > 0 ? EMPTY_SLUG_SET : reasoningDisabledModelSlugs; - return Ref.modify(learnedModels, (learned) => { - const next = applyAcpRegistryLiveConfiguration( - provider, - configuration, - effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, - ); - return [ - next, - updateLearnedModelsFromLive(learned, next.models, configuration, disabledForLearning), - ]; - }); - }), + Effect.flatMap((accepted) => + Option.match(reconcileLiveConfigurationAgainstAccepted(configuration, accepted), { + onNone: () => Effect.succeed(provider), + onSome: (effectiveConfiguration) => { + const preserveSingleModelCatalog = + options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); + const reasoningDisabledModelSlugs = + options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; + const disabledForLearning = + effectiveConfiguration.models.length > 0 + ? EMPTY_SLUG_SET + : reasoningDisabledModelSlugs; + return Ref.modify(learnedModels, (learned) => { + const next = applyAcpRegistryLiveConfiguration( + provider, + effectiveConfiguration, + effectiveConfig.customModels, + learned.length > 0 ? learned : provider.models, + { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, + ); + return [ + next, + updateLearnedModelsFromLive( + learned, + next.models, + effectiveConfiguration, + disabledForLearning, + ), + ]; + }); + }, + }), + ), ); const lastObservedLiveRevision = yield* Ref.make(0); const liveSnapshotSemaphore = yield* Semaphore.make(1); @@ -1380,7 +1429,6 @@ export const AcpRegistryDriver: ProviderDriver liveConfigurationReplacesAcceptedCatalog(configuration, accepted), @@ -1479,25 +1522,29 @@ export const AcpRegistryDriver: ProviderDriver - retainAcpRegistryLiveOptionsAfterProbe(live, { - models: probedModels, - currentModelId: probedCurrentModelId, - configOptions: probedConfigOptions, - modelOptionIds: probedModelOptionIds, - }), + retain: (live) => + retainAcpRegistryLiveOptionsAfterProbe(live, probeOptionSchema), }, ) : true : false; + if (probeSupersedesLiveCatalog && !cleared) return; + if (effectiveConfig.source === "local") { + yield* Ref.set(reportedLocalVersion, provider.version); + } if ( !probeSupersedesLiveCatalog && Option.isNone(liveCatalog) && @@ -1521,6 +1568,23 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshot.revision || + accepted.probeOptions !== null; + yield* Ref.set(acceptedCatalog, { + models: resolved.models, + builtInModelCount: probedModelCount, + modelsFromModelSelect: probedModelsFromModelSelect, + reasoningDisabledModelSlugs, + probeOptions: supersededLiveSession ? probeOptionSchema : null, + }); + } const published = yield* withLiveRuntimeState(resolved, { preserveSingleModelCatalog: probeSupersedesLiveCatalog && @@ -1532,42 +1596,31 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) .map((model) => model.id), ) @@ -1671,9 +1735,11 @@ export const AcpRegistryDriver: ProviderDriver 0 ? { @@ -1687,7 +1753,7 @@ export const AcpRegistryDriver: ProviderDriver updateAcpRegistryEnrichmentCache({ cache, - configuration, + configuration: effectiveConfiguration.value, customModels: effectiveConfig.customModels, now, preserveSingleModelCatalog, diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 8e39f323ee4bb..5fc41fe4af162 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -69,9 +69,9 @@ function advertisedReasoningEffort( option: EffectAcpSchema.SessionConfigOption | undefined, meta: Readonly> | null | undefined, ): AcpRegistryProbeModel["reasoningEffort"] { - if (option?.type !== "select" || meta == null) return undefined; + if (meta == null) return undefined; if (meta.supportsReasoningEffort === false) return null; - if (!Array.isArray(meta.reasoningEfforts)) return undefined; + if (option?.type !== "select" || !Array.isArray(meta.reasoningEfforts)) return undefined; const options = meta.reasoningEfforts.flatMap((level: unknown) => typeof level === "object" && level !== null && @@ -217,13 +217,22 @@ export interface AcpRegistryLiveConfiguration { readonly partialOptions?: boolean; } -export function normalizeAcpRegistryLiveConfiguration( +export interface PreparedAcpRegistryLiveConfiguration { + readonly catalogKey: string; + readonly toLiveConfiguration: (options?: { + readonly includeCatalog?: boolean; + }) => AcpRegistryLiveConfiguration; +} + +/** + * Normalizes a registry session's advertised catalog and options once, returning a stable + * catalog key alongside a projection that can omit unchanged model lists. + */ +export function prepareAcpRegistryLiveConfiguration( configOptions: ReadonlyArray, modeState?: Parameters[0]["modeState"], modelState?: EffectAcpSchema.SessionModelState | null, - options?: { readonly includeCatalog?: boolean }, -): AcpRegistryLiveConfiguration { - const includeCatalog = options?.includeCatalog !== false; +): PreparedAcpRegistryLiveConfiguration { const modelOption = findModelConfigOption(configOptions); const currentModelId = modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId; @@ -246,53 +255,61 @@ export function normalizeAcpRegistryLiveConfiguration( const effortOption = configOptions.find((option) => option.category === "thought_level") ?? configOptions.find(isAcpThoughtLevelOption); + const metaByModelId = new Map(); + for (const info of modelState?.availableModels ?? []) { + if (!metaByModelId.has(info.modelId)) { + metaByModelId.set(info.modelId, info._meta); + } + } const advertisedModels = normalizeModels(candidates, boundedCurrentModelId).map((model) => { - const reasoningEffort = advertisedReasoningEffort( - effortOption, - modelState?.availableModels.find((info) => info.modelId === model.id)?._meta, - ); + const reasoningEffort = advertisedReasoningEffort(effortOption, metaByModelId.get(model.id)); return reasoningEffort === undefined ? model : { ...model, reasoningEffort }; }); const currentModel = boundedCurrentModelId === null ? undefined : advertisedModels.find((model) => model.id === boundedCurrentModelId); - const stripCurrentReasoning = !includeCatalog && currentModel?.reasoningEffort === null; + const stripCurrentReasoning = currentModel?.reasoningEffort === null; const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( (descriptor) => !stripCurrentReasoning || descriptor.type !== "select" || descriptor.role !== "reasoning", ); - const modelOptionIds = new Set( + const modelOptionIdSet = new Set( configOptions .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config") .map((option) => option.id), ); + const modelOptionIds = descriptors + .filter((descriptor) => modelOptionIdSet.has(descriptor.id)) + .map((descriptor) => descriptor.id); + const hasModelSelect = modelOption !== undefined; + const resolvedCurrentModelId = currentModel === undefined ? null : currentModel.id; return { - models: includeCatalog ? advertisedModels : [], - currentModelId: currentModel === undefined ? null : currentModel.id, - configOptions: descriptors, - modelOptionIds: descriptors - .filter((descriptor) => modelOptionIds.has(descriptor.id)) - .map((descriptor) => descriptor.id), - modelsFromModelSelect: includeCatalog && modelOption !== undefined, + catalogKey: JSON.stringify([hasModelSelect, advertisedModels]), + toLiveConfiguration: (options) => { + const includeCatalog = options?.includeCatalog !== false; + return { + models: includeCatalog ? advertisedModels : [], + currentModelId: resolvedCurrentModelId, + configOptions: descriptors, + modelOptionIds, + modelsFromModelSelect: includeCatalog && hasModelSelect, + }; + }, }; } -/** - * Stable key for the effective normalized model catalog advertised by a registry - * session, covering cap/overflow selection, names, provenance, and per-model reasoning. - */ -export function acpRegistrySessionCatalogKey( +export function normalizeAcpRegistryLiveConfiguration( configOptions: ReadonlyArray, + modeState?: Parameters[0]["modeState"], modelState?: EffectAcpSchema.SessionModelState | null, -): string { - const { models, modelsFromModelSelect } = normalizeAcpRegistryLiveConfiguration( + options?: { readonly includeCatalog?: boolean }, +): AcpRegistryLiveConfiguration { + return prepareAcpRegistryLiveConfiguration( configOptions, - undefined, + modeState, modelState, - { includeCatalog: true }, - ); - return JSON.stringify([modelsFromModelSelect === true, models]); + ).toLiveConfiguration(options); } const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({ diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 9bb8d43c88cc9..94fe23e97b678 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -429,16 +429,12 @@ export interface AcpAdapterV2Flavor { readonly onAvailableCommandsUpdate?: ( commands: ReadonlyArray, ) => Effect.Effect; - readonly sessionCatalogKey?: ( - configOptions: ReadonlyArray, - modelState: EffectAcpSchema.SessionModelState | null | undefined, - ) => string; readonly onSessionConfigurationUpdate?: ( configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, modelState: EffectAcpSchema.SessionModelState | null | undefined, - options?: { readonly includeCatalog?: boolean }, - ) => Effect.Effect; + options?: { readonly lastCatalogKey: string | null }, + ) => Effect.Effect; readonly onUrlElicitation?: (input: { readonly elicitationId: string; readonly url: string; @@ -2299,31 +2295,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( epoch: current.epoch + 1, key: null, })); - const defaultSessionCatalogKey = ( - configOptions: ReadonlyArray, - modelState: EffectAcpSchema.SessionModelState | null | undefined, - ): string => { - const modelOption = findModelConfigOption(configOptions); - if (modelOption !== undefined) { - return JSON.stringify([ - "select", - flattenSelectChoices(modelOption.options).map((choice) => [ - choice.value, - choice.name, - choice.description ?? null, - ]), - ]); - } - return JSON.stringify([ - "models", - (modelState?.availableModels ?? []).map((model) => [ - model.modelId, - model.name, - model.description ?? null, - ]), - ]); - }; - const computeSessionCatalogKey = flavor.sessionCatalogKey ?? defaultSessionCatalogKey; const sessionConfigurationPublishPermit = yield* Semaphore.make(1); const publishSessionConfiguration = Effect.fn("AcpAdapterV2.publishSessionConfiguration")( function* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { @@ -2335,14 +2306,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const configOptions = yield* targetRuntime.getConfigOptions; const modeState = yield* targetRuntime.getModeState; const modelState = (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models; - const catalogKey = computeSessionCatalogKey(configOptions, modelState); - const includeCatalog = key !== catalogKey; - yield* onSessionConfigurationUpdate(configOptions, modeState, modelState, { - includeCatalog, - }); - yield* Ref.update(lastPublishedCatalogKey, (current) => - current.epoch === epoch ? { epoch, key: catalogKey } : current, + const nextKey = yield* onSessionConfigurationUpdate( + configOptions, + modeState, + modelState, + { lastCatalogKey: key }, ); + if (typeof nextKey === "string") { + yield* Ref.update(lastPublishedCatalogKey, (current) => + current.epoch === epoch ? { epoch, key: nextKey } : current, + ); + } }), ); }, From 94ab71c3a5c37b9875277c39598a89443994299d Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 12:23:27 +0000 Subject: [PATCH 12/35] fix(acp-registry): store active catalog separately and rebuild superseded overrides from probe baseline --- .../Adapters/AcpRegistryAdapterV2.test.ts | 14 +- .../AcpRegistryRuntimeCoordinator.test.ts | 108 +++-- .../server/AcpRegistryRuntimeCoordinator.ts | 89 ++-- .../src/server/driver.test.ts | 438 +++++++++++++++--- .../src/server/driver.ts | 436 +++++++++-------- .../provider-acp-registry/src/server/probe.ts | 28 +- 6 files changed, 754 insertions(+), 359 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..246dc7b5e71c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1009,16 +1009,16 @@ describe("AcpRegistryAdapterV2", () => { })), [ { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["hermes", "auto", "default"], current: "hermes" }, - { models: ["hermes", "auto", "default"], current: null }, - { models: ["hermes", "auto", "default"], current: "auto" }, - { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["auto"], current: null }, + { models: [], current: "hermes" }, + { models: [], current: null }, + { models: [], current: "auto" }, + { models: [], current: "default" }, { models: ["auto"], current: null }, + { models: [], current: null }, { models: ["default"], current: null }, - { models: ["default"], current: null }, + { models: [], current: null }, { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["hermes", "auto", "default"], current: "hermes" }, + { models: [], current: "hermes" }, ], ); }).pipe(Effect.provide(layerTest)), diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 7ad8605faa5d2..7aa2d683cf0bf 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -300,7 +300,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { ); it.effect( - "preserves an unsuperseded catalog only for options-only updates targeting that catalog", + "preserves the active catalog independently of options-only updates from any session", () => Effect.gen(function* () { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; @@ -316,42 +316,38 @@ describe("AcpRegistryRuntimeCoordinator", () => { { id: "high", label: "High" }, ], }; - const catalogModels = [ - { id: "model-b", name: "Model B", description: null }, - { id: "model-c", name: "Model C", description: null }, - ]; - - yield* coordinator.publishLiveConfiguration(instanceId, { - models: catalogModels, + const catalogConfig = { + models: [ + { id: "model-b", name: "Model B", description: null }, + { id: "model-c", name: "Model C", description: null }, + ], currentModelId: "model-b", configOptions: [], modelsFromModelSelect: true, - }); + }; + + yield* coordinator.publishLiveConfiguration(instanceId, catalogConfig); const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(catalogSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(catalogSnap.configuration).toEqual(Option.some(catalogConfig)); - // Options-only update targeting model-b keeps the active catalog in coordinator state. - yield* coordinator.publishLiveConfiguration(instanceId, { + // Options-only update targeting model-b keeps the active catalog separately from raw options. + const matchingOptionsOnly = { models: [], currentModelId: "model-b", configOptions: [effortOption], modelOptionIds: ["effort"], modelsFromModelSelect: false, - }); + }; + yield* coordinator.publishLiveConfiguration(instanceId, matchingOptionsOnly); const matchingOptionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(matchingOptionsSnap.revision).toBe(catalogSnap.revision + 1); expect(matchingOptionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); - expect(matchingOptionsSnap.configuration).toEqual( - Option.some({ - models: catalogModels, - currentModelId: "model-b", - configOptions: [effortOption], - modelOptionIds: ["effort"], - modelsFromModelSelect: true, - }), - ); + expect(matchingOptionsSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(matchingOptionsSnap.configuration).toEqual(Option.some(matchingOptionsOnly)); - // An options-only update from another session running an absent model stores raw - // so stored snapshots never lose the default marker compared to the PubSub stream. + // An options-only update from another session running an absent model neither discards + // the active catalog nor merges foreign model options into it. const foreignOptionsOnly = { models: [], currentModelId: "model-a", @@ -360,9 +356,39 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }; yield* coordinator.publishLiveConfiguration(instanceId, foreignOptionsOnly); - expect( - (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).configuration, - ).toEqual(Option.some(foreignOptionsOnly)); + const foreignSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(foreignSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(foreignSnap.configuration).toEqual(Option.some(foreignOptionsOnly)); + + // A watcher starting behind the active catalog replays the catalog first, then the raw options. + const replayed: Array = []; + const bothReplayed = yield* Deferred.make(); + const watcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Effect.sync(() => { + replayed.push([ + configuration.models.length, + configuration.currentModelId, + revision, + ] as const); + return replayed.length; + }).pipe( + Effect.flatMap((count) => + count === 2 ? Deferred.succeed(bothReplayed, undefined) : Effect.void, + ), + Effect.asVoid, + ), + { afterRevision: 0 }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(bothReplayed); + yield* Fiber.interrupt(watcher); + expect(replayed).toEqual([ + [2, "model-b", catalogSnap.revision], + [0, "model-a", foreignSnap.revision], + ]); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); @@ -405,8 +431,8 @@ describe("AcpRegistryRuntimeCoordinator", () => { (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, ).toBe(0); - // Catalog-scoped clear reconciles newer in-flight options-only updates through retain - // and advances clearedThroughRevision past them so delayed raw callbacks are skipped. + // Catalog-scoped clear reconciles newer in-flight options-only updates through retain, + // clears the stored catalog, and advances clearedThroughRevision past them. const optionsOnlyConfig = { models: [], currentModelId: "model-v2", @@ -428,6 +454,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, + catalog: Option.none(), configuration: Option.some({ ...optionsOnlyConfig, configOptions: [effortOption("low")], @@ -443,6 +470,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, + catalog: Option.none(), configuration: Option.none(), clearedThroughRevision: optionsSnap.revision, }); @@ -487,7 +515,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, optionsOnly); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - // A watcher already at the catalog revision receives the raw options-only payload on replay. + // A watcher already at the catalog revision receives only the raw options-only payload. const rawReplay = yield* Deferred.make(); const afterCatalogWatcher = yield* coordinator .watchLiveConfiguration( @@ -502,23 +530,31 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect(yield* Deferred.await(rawReplay)).toEqual([0, optionsSnap.revision]); yield* Fiber.interrupt(afterCatalogWatcher); - // A watcher behind the catalog revision receives the preserved catalog alongside the options. - const fullReplay = yield* Deferred.make(); + // A watcher behind the catalog revision receives the catalog first, then the raw options. + const fullReplay: Array = []; + const fullReplayDone = yield* Deferred.make(); const beforeCatalogWatcher = yield* coordinator .watchLiveConfiguration( instanceId, (configuration, revision) => - Deferred.succeed(fullReplay, [configuration.models.length, revision] as const).pipe( + Effect.sync(() => { + fullReplay.push([configuration.models.length, revision] as const); + return fullReplay.length; + }).pipe( + Effect.flatMap((count) => + count === 2 ? Deferred.succeed(fullReplayDone, undefined) : Effect.void, + ), Effect.asVoid, ), { afterRevision: 0 }, ) .pipe(Effect.forkChild({ startImmediately: true })); - expect(yield* Deferred.await(fullReplay)).toEqual([ - catalogModels.length, - optionsSnap.revision, - ]); + yield* Deferred.await(fullReplayDone); yield* Fiber.interrupt(beforeCatalogWatcher); + expect(fullReplay).toEqual([ + [catalogModels.length, catalogSnap.revision], + [0, optionsSnap.revision], + ]); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 1eae61b376636..6d56280e91a04 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -30,18 +30,26 @@ interface LiveConfigurationUpdate { } export interface AcpRegistryLiveConfigurationSnapshot { + readonly catalog: Option.Option; readonly configuration: Option.Option; readonly revision: number; readonly catalogRevision: number; readonly clearedThroughRevision: number; } -interface StoredLiveConfiguration extends AcpRegistryLiveConfigurationSnapshot { - readonly lastPublishedConfiguration: Option.Option; - readonly lastCatalogPublishedRevision: number; +interface StoredLiveConfiguration { + readonly catalog: { + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; + } | null; + readonly configuration: Option.Option; + readonly revision: number; + readonly catalogRevision: number; + readonly clearedThroughRevision: number; } export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { + catalog: Option.none(), configuration: Option.none(), revision: 0, catalogRevision: 0, @@ -49,14 +57,17 @@ export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnap }; const EMPTY_STORED_LIVE_CONFIGURATION: StoredLiveConfiguration = { - ...EMPTY_LIVE_CONFIGURATION_SNAPSHOT, - lastPublishedConfiguration: Option.none(), - lastCatalogPublishedRevision: 0, + catalog: null, + configuration: Option.none(), + revision: 0, + catalogRevision: 0, + clearedThroughRevision: 0, }; const toPublicLiveConfigurationSnapshot = ( entry: StoredLiveConfiguration, ): AcpRegistryLiveConfigurationSnapshot => ({ + catalog: entry.catalog === null ? Option.none() : Option.some(entry.catalog.configuration), configuration: entry.configuration, revision: entry.revision, catalogRevision: entry.catalogRevision, @@ -264,8 +275,8 @@ const make = Effect.gen(function* () { if (current === undefined) return state; const nextCleared = Math.max(current.clearedThroughRevision, current.revision); if ( + current.catalog === null && Option.isNone(current.configuration) && - Option.isNone(current.lastPublishedConfiguration) && nextCleared === current.clearedThroughRevision ) { return state; @@ -273,8 +284,8 @@ const make = Effect.gen(function* () { const next = new Map(state); next.set(instanceId, { ...current, + catalog: null, configuration: Option.none(), - lastPublishedConfiguration: Option.none(), clearedThroughRevision: nextCleared, }); return next; @@ -302,8 +313,8 @@ const make = Effect.gen(function* () { }), ); if ( + current.catalog === null && Equal.equals(current.configuration, nextConfiguration) && - Equal.equals(current.lastPublishedConfiguration, nextConfiguration) && nextCleared === current.clearedThroughRevision ) { return [true, state] as const; @@ -311,8 +322,8 @@ const make = Effect.gen(function* () { const next = new Map(state); next.set(instanceId, { ...current, + catalog: null, configuration: nextConfiguration, - lastPublishedConfiguration: nextConfiguration, clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -332,38 +343,15 @@ const make = Effect.gen(function* () { const catalogRevision = hasCatalog ? current.catalogRevision + 1 : current.catalogRevision; - const lastCatalogPublishedRevision = hasCatalog - ? revision - : current.lastCatalogPublishedRevision; - // Preserve an unsuperseded session catalog across options-only updates only when - // the update targets that catalog (or no model), keeping the default marker intact. - const canPreserveStoredCatalog = - !hasCatalog && - Option.isSome(current.configuration) && - current.configuration.value.models.length > 0 && - (configuration.currentModelId === null || - current.configuration.value.models.some( - (model) => model.id === configuration.currentModelId, - )); - const storedConfiguration: AcpRegistryLiveConfiguration = - canPreserveStoredCatalog && Option.isSome(current.configuration) - ? { - ...configuration, - models: current.configuration.value.models, - ...(current.configuration.value.modelsFromModelSelect === undefined - ? {} - : { - modelsFromModelSelect: current.configuration.value.modelsFromModelSelect, - }), - } - : configuration; + // Store the active catalog separately from options-only updates so an + // unrelated session's options update never discards or mutates it. + const catalog = hasCatalog ? { configuration, revision } : current.catalog; const next = new Map(state); next.set(instanceId, { - configuration: Option.some(storedConfiguration), - lastPublishedConfiguration: Option.some(configuration), + catalog, + configuration: Option.some(configuration), revision, catalogRevision, - lastCatalogPublishedRevision, clearedThroughRevision: current.clearedThroughRevision, }); return [revision, next] as const; @@ -399,23 +387,18 @@ const make = Effect.gen(function* () { (instanceId, onUpdate, options) => Effect.scoped( Effect.gen(function* () { - const afterRevision = options?.afterRevision; const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); const current = (yield* Ref.get(liveConfigurations)).get(instanceId); - let deliveredRevision = afterRevision ?? 0; - if ( - current !== undefined && - Option.isSome(current.configuration) && - (afterRevision === undefined || current.revision > afterRevision) - ) { - deliveredRevision = current.revision; - const replayConfiguration = - afterRevision !== undefined && - current.lastCatalogPublishedRevision <= afterRevision && - Option.isSome(current.lastPublishedConfiguration) - ? current.lastPublishedConfiguration.value - : current.configuration.value; - yield* onUpdate(replayConfiguration, current.revision); + let deliveredRevision = options?.afterRevision ?? 0; + if (current !== undefined) { + if (current.catalog !== null && current.catalog.revision > deliveredRevision) { + deliveredRevision = current.catalog.revision; + yield* onUpdate(current.catalog.configuration, current.catalog.revision); + } + if (Option.isSome(current.configuration) && current.revision > deliveredRevision) { + deliveredRevision = current.revision; + yield* onUpdate(current.configuration.value, current.revision); + } } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index ade96e0b3797d..fd45fdd110d23 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -444,30 +444,15 @@ describe("acpRegistrySnapshotReadiness", () => { { id: "glm", name: "GLM", description: null, reasoningEffort: null }, ]); - const catalogDisabled = normalizeAcpRegistryLiveConfiguration( - [effort], - undefined, - { - currentModelId: "glm", - availableModels: [ - { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, - { modelId: "opus", name: "Opus" }, - ], - }, - { includeCatalog: true }, - ); - const optionsOnlyDisabled = normalizeAcpRegistryLiveConfiguration( - [effort], - undefined, - { - currentModelId: "glm", - availableModels: [ - { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, - { modelId: "opus", name: "Opus" }, - ], - }, - { includeCatalog: false }, - ); + const preparedDisabled = prepareAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "glm", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }); + const catalogDisabled = preparedDisabled.toLiveConfiguration({ includeCatalog: true }); + const optionsOnlyDisabled = preparedDisabled.toLiveConfiguration({ includeCatalog: false }); expect(catalogDisabled.configOptions).toEqual([]); expect(optionsOnlyDisabled.configOptions).toEqual(catalogDisabled.configOptions); expect(optionsOnlyDisabled.modelOptionIds).toEqual([]); @@ -497,18 +482,13 @@ describe("acpRegistrySnapshotReadiness", () => { }), [], ); - const staleSessionOptionsOnOpus = normalizeAcpRegistryLiveConfiguration( - [effort], - undefined, - { - currentModelId: "opus", - availableModels: [ - { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, - { modelId: "opus", name: "Opus" }, - ], - }, - { includeCatalog: false }, - ); + const staleSessionOptionsOnOpus = prepareAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "opus", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }).toLiveConfiguration({ includeCatalog: false }); expect( applyAcpRegistryLiveConfiguration( probeReenabledGlm, @@ -1004,10 +984,21 @@ describe("acpRegistrySnapshotReadiness", () => { ); expect(afterProvisionalModelOnly.models).toBe(entitled.models); - // An options-only update with no currentModelId on a discovered catalog applies only - // shared options and must not overwrite the default model's own options. + // An options-only update with no currentModelId on a discovered catalog (even one whose + // model ID happens to be "default") applies only shared options and leaves own options alone. + const discoveredNamedDefault = applyAcpRegistryLiveConfiguration( + provider, + { + models: [{ id: "default", name: "Default Model", description: null }], + currentModelId: "default", + configOptions: [entitledEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }, + [], + ); const afterUnknownModelOptions = applyAcpRegistryLiveConfiguration( - entitled, + discoveredNamedDefault, { models: [], currentModelId: null, @@ -1016,15 +1007,35 @@ describe("acpRegistrySnapshotReadiness", () => { modelsFromModelSelect: false, }, [], - entitled.models, - { preserveSingleModelCatalog: true }, + discoveredNamedDefault.models, + { hasDiscoveredCatalog: true }, ); - expect(afterUnknownModelOptions.models.find((m) => m.slug === "gmodel")?.isDefault).toBe(true); + expect(afterUnknownModelOptions.models.find((m) => m.slug === "default")?.isDefault).toBe(true); expect( - afterUnknownModelOptions.models.find((m) => m.slug === "gmodel")?.capabilities + afterUnknownModelOptions.models.find((m) => m.slug === "default")?.capabilities ?.optionDescriptors, ).toEqual([sharedMode, entitledEffort]); + // Synthetic placeholder ("default" without a discovered catalog) still accepts model options. + const syntheticDefault = providerWithModels([], null); + const afterSyntheticOptions = applyAcpRegistryLiveConfiguration( + syntheticDefault, + { + models: [], + currentModelId: null, + configOptions: [placeholderEffort, sharedMode], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + syntheticDefault.models, + { hasDiscoveredCatalog: false }, + ); + expect( + afterSyntheticOptions.models.find((m) => m.slug === "default")?.capabilities + ?.optionDescriptors, + ).toEqual([placeholderEffort, sharedMode]); + const replacedExplicit = applyAcpRegistryLiveConfiguration( entitled, { @@ -1113,7 +1124,7 @@ describe("acpRegistryEnrichmentCache", () => { expect(provisionalUpdate).toBe(explicitSingletonCache); expect(provisionalUpdate.entry?.provider.models.map((m) => m.slug)).toEqual(["gmodel"]); - const optionsOnly = normalizeAcpRegistryLiveConfiguration( + const optionsOnly = prepareAcpRegistryLiveConfiguration( [ { id: "effort", @@ -1132,8 +1143,7 @@ describe("acpRegistryEnrichmentCache", () => { { modelId: "qmodel", name: "Qwen" }, ], }, - { includeCatalog: false }, - ); + ).toLiveConfiguration({ includeCatalog: false }); expect(optionsOnly.models).toEqual([]); expect(optionsOnly.currentModelId).toBe("auto"); expect(optionsOnly.modelsFromModelSelect).toBe(false); @@ -1535,11 +1545,47 @@ describe("acpRegistryEnrichmentCache", () => { }, ), ).toEqual(Option.none()); + + // Off-current reasoning retention requires matching native option IDs (thinking != effort). + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [ + { + id: "thinking", + label: "Thinking", + type: "select", + role: "reasoning", + currentValue: "low", + options: [{ id: "low", label: "Low" }], + }, + ], + modelOptionIds: ["thinking"], + modelsFromModelSelect: false, + }, + { + models: [ + { id: "new-model", name: "new-model", description: null }, + { + id: "old-model", + name: "old-model", + description: null, + reasoningEffort: effort("high"), + }, + ], + currentModelId: "new-model", + configOptions: [effort("high")], + modelOptionIds: new Set(["effort"]), + }, + ), + ).toEqual(Option.none()); }); }); describe("prepareAcpRegistryLiveConfiguration", () => { - it("ignores in-cap selection and effort value tweaks while detecting overflow selection, renames, and newly normalized per-model reasoning", () => { + it("ignores in-cap selection and effort selector toggles while detecting overflow selection, renames, and projecting newly normalized per-model reasoning", () => { const modelSelect = ( currentValue: string, options: ReadonlyArray<{ value: string; name: string }>, @@ -1569,9 +1615,9 @@ describe("prepareAcpRegistryLiveConfiguration", () => { ).catalogKey, ).not.toBe(keyM0); - // When a session initially omits the effort selector and later exposes it, another model's - // _meta.reasoningEfforts becomes normalizable and must change the catalog key, while changing - // only the active effort currentValue must not. + // Toggling an effort selector on a session with a fixed modelState must keep catalogKey + // stable (so frozen lists never re-advertise over a newer probe) while projecting newly + // normalized non-current _meta.reasoningEfforts via advertisedReasoning. const modelState = { currentModelId: "model-a", availableModels: [ @@ -1597,19 +1643,42 @@ describe("prepareAcpRegistryLiveConfiguration", () => { { value: "high", name: "High" }, ], }); - const withoutEffort = prepareAcpRegistryLiveConfiguration([], undefined, modelState).catalogKey; + const withoutEffort = prepareAcpRegistryLiveConfiguration([], undefined, modelState); const withEffortHigh = prepareAcpRegistryLiveConfiguration( [effortSelect("high")], undefined, modelState, - ).catalogKey; + ); const withEffortLow = prepareAcpRegistryLiveConfiguration( [effortSelect("low")], undefined, modelState, - ).catalogKey; - expect(withEffortHigh).not.toBe(withoutEffort); - expect(withEffortLow).toBe(withEffortHigh); + ); + expect(withEffortHigh.catalogKey).toBe(withoutEffort.catalogKey); + expect(withEffortLow.catalogKey).toBe(withEffortHigh.catalogKey); + const optionsOnlyWithEffort = withEffortHigh.toLiveConfiguration({ includeCatalog: false }); + expect(optionsOnlyWithEffort.models).toEqual([]); + expect(optionsOnlyWithEffort.advertisedReasoning?.["model-b"]).toMatchObject({ + id: "effort", + currentValue: "low", + options: [{ id: "low", label: "Low" }], + }); + const appliedToActive = applyAcpRegistryLiveConfiguration( + providerWithModels( + [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null }, + ], + "model-a", + ), + optionsOnlyWithEffort, + [], + ); + expect( + appliedToActive.models + .find((model) => model.slug === "model-b") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([["effort", "low"]]); }); }); @@ -1852,15 +1921,43 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = yield* Fiber.join(probed); yield* coordinator.publishLiveConfiguration( identity.instanceId, - normalizeAcpRegistryLiveConfiguration([], undefined, { - currentModelId: "old-model", - availableModels: [ - { modelId: "old-model", name: "old-model" }, - { modelId: "session-model", name: "session-model" }, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "legacy", + name: "Legacy", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ], + undefined, + { + currentModelId: "old-model", + availableModels: [ + { modelId: "old-model", name: "old-model" }, + { modelId: "session-model", name: "session-model" }, + ], + }, + ), + ); + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify({ + models: ["old-model", "new-model"], + configOptions: [ + { + id: "fast", + name: "Fast", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, ], }), ); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "new-model"])); const refreshed = yield* waitForModels(["old-model", "new-model"]).pipe( Effect.forkScoped({ startImmediately: true }), @@ -1868,6 +1965,66 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = yield* instance.invalidateCaches ?? Effect.void; yield* instance.snapshot.refresh; expect(Option.isSome(yield* Fiber.join(refreshed))).toBe(true); + + // A still-running session sending an options-only update after invalidateCaches must still + // reconcile against the replacement probe's schema (keeping fast and dropping legacy). + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + [ + { + id: "legacy", + name: "Legacy", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ], + undefined, + { + currentModelId: "old-model", + availableModels: [ + { modelId: "old-model", name: "old-model" }, + { modelId: "session-model", name: "session-model" }, + ], + }, + ).toLiveConfiguration({ includeCatalog: false }), + ); + // Force a cached refresh so the semaphore-serialized watcher has finished before reading. + const synced = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterOptions = Option.getOrThrow(yield* Fiber.join(synced)); + expect(afterOptions.models.map((model) => model.slug)).toEqual(["old-model", "new-model"]); + expect( + afterOptions.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([["fast", "on"]]); + + // When a probe returns no models, invalidateCaches + refresh must preserve the running + // session's catalog instead of dropping to synthetic default. + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "session-x", + availableModels: [ + { modelId: "session-x", name: "session-x" }, + { modelId: "session-y", name: "session-y" }, + ], + }), + ); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify([])); + const emptyProbeAfterInvalidate = yield* waitForModels(["session-x", "session-y"]).pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(emptyProbeAfterInvalidate))).toBe(true); }), ); @@ -2061,7 +2218,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - normalizeAcpRegistryLiveConfiguration( + prepareAcpRegistryLiveConfiguration( [ { id: "mode", @@ -2083,8 +2240,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = { modelId: "model-b", name: "model-b", _meta: { supportsReasoningEffort: false } }, ], }, - { includeCatalog: false }, - ), + ).toLiveConfiguration({ includeCatalog: false }), ); expect(effortBySlug(Option.getOrThrow(yield* Fiber.join(modeTweaked)))).toBe( "model-a:mode,model-b:mode+variant", @@ -2198,10 +2354,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const sessionWithOptions = ( currentModelId: string, - effortValue: "low" | "high" = "high", + effortValue: "low" | "high" | "turbo" = "high", options?: { readonly includeCatalog?: boolean; readonly includeLegacy?: boolean }, ) => - normalizeAcpRegistryLiveConfiguration( + prepareAcpRegistryLiveConfiguration( [ { id: "effort", @@ -2212,6 +2368,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { options: [ { value: "low", name: "Low" }, { value: "high", name: "High" }, + ...(effortValue === "turbo" ? [{ value: "turbo", name: "Turbo" }] : []), ], }, ...(options?.includeLegacy === true @@ -2233,8 +2390,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { availableModels: [ { modelId: "old-model", name: "old-model" }, { modelId: "other-model", name: "other-model" }, + ...(currentModelId === "new-model" + ? [{ modelId: "new-model", name: "new-model" }] + : []), ], }, + ).toLiveConfiguration( options?.includeCatalog === undefined ? undefined : { includeCatalog: options.includeCatalog }, @@ -2403,6 +2564,62 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ["effort", "high"], ]); + // If a superseded session overrides new-model's effort to low and later reports an + // invalid value (turbo), both snapshot and cached refresh restore the probe default (high). + const newModelLow = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithOptions("new-model", "low", { includeCatalog: false }), + ); + yield* Fiber.join(newModelLow); + + const restoredBaseline = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithOptions("new-model", "turbo", { includeCatalog: false }), + ); + const afterRejectedOverride = Option.getOrThrow(yield* Fiber.join(restoredBaseline)); + expect( + afterRejectedOverride.models + .find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); + const cachedAfterRejection = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(cachedAfterRejection)) + .models.find((model) => model.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["effort", "high"], + ]); + // When a later post-TTL probe runs directly on old-model without effort, learned effort is dropped. yield* writeModels(["old-model", "new-model"]); yield* TestClock.adjust("16 minutes"); @@ -3201,7 +3418,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.await(secondProbeEntered); // Hold the raw watcher callback for this in-flight options-only revision until after the - // probe commits, verifying clearedThroughRevision suppresses it after retain reconciles it. + // probe commits, verifying clearedThroughRevision advances past it and the snapshot stays clean. holdNextOptionsCallback = true; yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -3233,12 +3450,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { modelsFromModelSelect: false, }); yield* Deferred.await(delayedOptionsEntered); + const inFlightRevision = (yield* coordinator.getLiveConfigurationWithRevision( + identity.instanceId, + )).revision; const committed = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* Deferred.succeed(releaseSecondProbe, undefined); const updated = Option.getOrThrow(yield* Fiber.join(committed)); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(identity.instanceId)) + .clearedThroughRevision, + ).toBe(inFlightRevision); expect(updated.models.map((model) => model.slug)).toEqual([ "old-model", "other-model", @@ -3259,7 +3483,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), ).toEqual([["mode", "plan"]]); - // Releasing the delayed raw watcher callback must not bring back removed effort=high. + // Releasing the delayed raw watcher callback leaves the reconciled snapshot and cache intact. yield* Deferred.succeed(releaseDelayedOptions, undefined); yield* Deferred.await(delayedOptionsDone); expect( @@ -3493,4 +3717,82 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual(["old-model", "newer-live-model"]); }), ); + + it.effect( + "syncs acceptedCatalog during readiness handoff when a refresh interrupts an unapplied live catalog", + () => + Effect.gen(function* () { + const handoffCallbackBlocked = yield* Deferred.make(); + let blockHandoffWatcher = false; + const { + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-handoff-", + initialModels: ["old-model", "other-model"], + wrapCoordinator: (base) => ({ + ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + blockHandoffWatcher && configuration.currentModelId === "handoff-a" + ? Effect.sync(() => { + blockHandoffWatcher = false; + }).pipe( + Effect.andThen(Deferred.succeed(handoffCallbackBlocked, undefined)), + Effect.andThen(Effect.never), + ) + : onUpdate(configuration, revision), + options, + ), + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish a live catalog whose watcher callback blocks until refresh interrupts it. + blockHandoffWatcher = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "handoff-a", name: "Handoff A", description: null }, + { id: "handoff-b", name: "Handoff B", description: null }, + ], + currentModelId: "handoff-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Deferred.await(handoffCallbackBlocked); + + // Refresh interrupts the blocked watcher; readiness must still have synced acceptedCatalog + // before recording lastObservedLiveRevision, so a subsequent provisional probe keeps it. + yield* instance.snapshot.refresh; + yield* writeModels({ provisional: "placeholder" }); + yield* TestClock.adjust("16 minutes"); + const afterProvisional = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterProvisional)).models.map((m) => m.slug), + ).toEqual(["handoff-a", "handoff-b"]); + + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "handoff-a", + "handoff-b", + ]); + }), + ); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 1caf632360a18..d28d93c9ccf91 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -166,6 +166,7 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly now: number; readonly preserveSingleModelCatalog?: boolean | undefined; readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; }): AcpRegistryEnrichmentCache { const { cache, @@ -174,6 +175,7 @@ export function updateAcpRegistryEnrichmentCache(input: { now, preserveSingleModelCatalog, reasoningDisabledModelSlugs, + hasDiscoveredCatalog, } = input; if (cache.entry === null) { // Only advance the cache epoch when the live session discovered a catalog @@ -185,7 +187,7 @@ export function updateAcpRegistryEnrichmentCache(input: { configuration, customModels, undefined, - { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, + { preserveSingleModelCatalog, reasoningDisabledModelSlugs, hasDiscoveredCatalog }, ); if (Equal.equals(provider, cache.entry.provider)) return cache; const previousBuiltIn = cache.entry.provider.models.filter((model) => !model.isCustom); @@ -271,7 +273,9 @@ function updateLearnedModelsFromLive( if (model.isCustom) continue; const isCurrentModel = configuration.currentModelId !== null && model.slug === configuration.currentModelId; - const hasAdvertisedReasoning = configuredById.get(model.slug)?.reasoningEffort !== undefined; + const hasAdvertisedReasoning = + configuredById.get(model.slug)?.reasoningEffort !== undefined || + configuration.advertisedReasoning?.[model.slug] !== undefined; const isReasoningDisabled = disabledReasoningSlugs.has(model.slug); if (!isCurrentModel && !hasAdvertisedReasoning && !isReasoningDisabled) continue; const descriptors = model.capabilities?.optionDescriptors ?? []; @@ -311,7 +315,12 @@ function compatibleLiveOptionValue( probed: ProviderOptionDescriptor, live: ProviderOptionDescriptor | undefined, ): Option.Option { - if (live === undefined || live.type !== probed.type || live.currentValue === undefined) { + if ( + live === undefined || + live.id !== probed.id || + live.type !== probed.type || + live.currentValue === undefined + ) { return Option.none(); } if (probed.type === "boolean") { @@ -398,20 +407,6 @@ export function retainAcpRegistryLiveOptionsAfterProbe( }); } -function reconcileLiveConfigurationAgainstAccepted( - configuration: AcpRegistryLiveConfiguration, - accepted: AcceptedAcpRegistryCatalog, -): Option.Option { - if ( - liveConfigurationReplacesAcceptedCatalog(configuration, accepted) || - configuration.partialOptions === true || - accepted.probeOptions === null - ) { - return Option.some(configuration); - } - return retainAcpRegistryLiveOptionsAfterProbe(configuration, accepted.probeOptions); -} - function mergeLearnedModelOptions( models: ReadonlyArray, learned: ReadonlyArray, @@ -800,6 +795,7 @@ export function applyAcpRegistryLiveConfiguration( options?: { readonly preserveSingleModelCatalog?: boolean | undefined; readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; @@ -840,7 +836,10 @@ export function applyAcpRegistryLiveConfiguration( // When retaining a discovered catalog for a live session with an absent or // unknown current model, keep only shared options and leave each model's own // options untouched. Only the synthetic "default" placeholder accepts them. - const hasSyntheticDefaultOnly = probedModels.length === 1 && probedModels[0]?.slug === "default"; + const hasDiscoveredCatalog = + options?.hasDiscoveredCatalog === true || options?.preserveSingleModelCatalog === true; + const hasSyntheticDefaultOnly = + !hasDiscoveredCatalog && probedModels.length === 1 && probedModels[0]?.slug === "default"; const dropUnmatchedModelOptions = !useLiveCatalog && !liveCurrentModelInProbed && @@ -853,23 +852,38 @@ export function applyAcpRegistryLiveConfiguration( (descriptor) => !isModelSpecificDescriptor(descriptor, unmatchedModelOptionIds), ) : configuration.configOptions; + const hasAdvertisedReasoning = + !useLiveCatalog && + configuration.advertisedReasoning !== undefined && + Object.keys(configuration.advertisedReasoning).length > 0; const discovery = useLiveCatalog ? configuration : { ...configuration, - models: probedModels.map((model) => ({ - id: model.slug, - name: model.name, - description: null, - ...(disabledReasoningSlugs.has(model.slug) ? { reasoningEffort: null } : {}), - })), + models: probedModels.map((model) => { + if (disabledReasoningSlugs.has(model.slug)) { + return { + id: model.slug, + name: model.name, + description: null, + reasoningEffort: null, + }; + } + const advertised = configuration.advertisedReasoning?.[model.slug]; + return { + id: model.slug, + name: model.name, + description: null, + ...(advertised === undefined ? {} : { reasoningEffort: advertised }), + }; + }), currentModelId: dropUnmatchedModelOptions ? configuration.currentModelId : selectedProbedModelId, configOptions: effectiveConfigOptions, }; const nextModels = - !useLiveCatalog && effectiveConfigOptions.length === 0 + !useLiveCatalog && effectiveConfigOptions.length === 0 && !hasAdvertisedReasoning ? stripReasoningForDisabledModels( withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), disabledReasoningSlugs, @@ -883,7 +897,7 @@ export function applyAcpRegistryLiveConfiguration( ...snapshot, status: provider.enabled ? "ready" : provider.status, models: - dropUnmatchedModelOptions && effectiveConfigOptions.length > 0 + dropUnmatchedModelOptions && (effectiveConfigOptions.length > 0 || hasAdvertisedReasoning) ? withAcpRegistryDefaultModel(nextModels, selectedProbedModelId) : nextModels, }; @@ -1248,43 +1262,143 @@ export const AcpRegistryDriver: ProviderDriver | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; }, ) => Ref.get(acceptedCatalog).pipe( - Effect.flatMap((accepted) => - Option.match(reconcileLiveConfigurationAgainstAccepted(configuration, accepted), { - onNone: () => Effect.succeed(provider), - onSome: (effectiveConfiguration) => { - const preserveSingleModelCatalog = - options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); - const reasoningDisabledModelSlugs = - options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; - const disabledForLearning = - effectiveConfiguration.models.length > 0 - ? EMPTY_SLUG_SET - : reasoningDisabledModelSlugs; - return Ref.modify(learnedModels, (learned) => { - const next = applyAcpRegistryLiveConfiguration( - provider, - effectiveConfiguration, - effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - { preserveSingleModelCatalog, reasoningDisabledModelSlugs }, - ); - return [ - next, - updateLearnedModelsFromLive( - learned, - next.models, - effectiveConfiguration, - disabledForLearning, - ), - ]; - }); - }, - }), - ), + Effect.flatMap((accepted) => { + const preserveSingleModelCatalog = + options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); + const reasoningDisabledModelSlugs = + options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; + const hasDiscoveredCatalog = + options?.hasDiscoveredCatalog ?? accepted.builtInModelCount > 0; + const disabledForLearning = + configuration.models.length > 0 ? EMPTY_SLUG_SET : reasoningDisabledModelSlugs; + return Ref.modify(learnedModels, (learned) => { + const next = applyAcpRegistryLiveConfiguration( + provider, + configuration, + effectiveConfig.customModels, + learned.length > 0 ? learned : provider.models, + { preserveSingleModelCatalog, reasoningDisabledModelSlugs, hasDiscoveredCatalog }, + ); + return [ + next, + updateLearnedModelsFromLive(learned, next.models, configuration, disabledForLearning), + ]; + }); + }), ); + const applyLiveConfigurationStep = Effect.fn("AcpRegistryDriver.applyLiveConfigurationStep")( + function* ( + current: ServerProvider, + configuration: AcpRegistryLiveConfiguration, + options?: { + readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; + readonly preserveStatus?: boolean | undefined; + readonly updateAcceptedAndCache?: boolean | undefined; + }, + ) { + const acceptedBefore = yield* Ref.get(acceptedCatalog); + const replacesCatalog = liveConfigurationReplacesAcceptedCatalog( + configuration, + acceptedBefore, + ); + const preserveSingleModelCatalog = + options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(acceptedBefore); + const reasoningDisabledModelSlugs = + options?.reasoningDisabledModelSlugs ?? acceptedBefore.reasoningDisabledModelSlugs; + const hasDiscoveredCatalog = + options?.hasDiscoveredCatalog ?? acceptedBefore.builtInModelCount > 0; + const withPreservedStatus = (applied: ServerProvider) => + options?.preserveStatus === true + ? { + ...applied, + status: current.status, + ...(current.message === undefined ? {} : { message: current.message }), + } + : applied; + + if (!replacesCatalog && acceptedBefore.probeOptions !== null) { + const effectiveConfiguration = + configuration.partialOptions === true + ? Option.some(configuration) + : retainAcpRegistryLiveOptionsAfterProbe(configuration, acceptedBefore.probeOptions); + // Rebuild from the accepted probe baseline so rejected live values restore + // probe defaults instead of leaving earlier overrides in the snapshot or cache. + const baselineModels = yield* Ref.get(learnedModels).pipe( + Effect.map((learned) => + mergeLearnedModelOptions(acceptedBefore.models, learned, { + currentModelId: acceptedBefore.probeOptions!.currentModelId, + reasoningDisabledModelSlugs, + }), + ), + ); + const baselineProvider = + acceptedBefore.models.length > 0 ? { ...current, models: baselineModels } : current; + const applied = yield* Option.match(effectiveConfiguration, { + onNone: () => Effect.succeed(baselineProvider), + onSome: (partial) => + applyLiveConfiguration(baselineProvider, partial, { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + }), + }); + return withPreservedStatus(applied); + } + + const applied = yield* applyLiveConfiguration(current, configuration, { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + }); + const next = withPreservedStatus(applied); + if (options?.updateAcceptedAndCache === true) { + const nextReasoningDisabled = replacesCatalog + ? new Set( + configuration.models + .filter((model) => model.reasoningEffort === null) + .map((model) => model.id), + ) + : acceptedBefore.reasoningDisabledModelSlugs; + if (current.auth.status !== "unauthenticated" || replacesCatalog) { + yield* Ref.update(acceptedCatalog, (previous) => + replacesCatalog + ? { + models: next.models, + builtInModelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, + reasoningDisabledModelSlugs: nextReasoningDisabled, + probeOptions: null, + } + : current.status === "ready" && previous.models.length > 0 + ? { + ...previous, + models: next.models, + } + : previous, + ); + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + preserveSingleModelCatalog, + reasoningDisabledModelSlugs: acceptedBefore.reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + }), + ); + } + return next; + }, + ); const lastObservedLiveRevision = yield* Ref.make(0); const liveSnapshotSemaphore = yield* Semaphore.make(1); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( @@ -1295,6 +1409,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; readonly preserveStatus?: boolean; }, ) { @@ -1314,58 +1429,50 @@ export const AcpRegistryDriver: ProviderDriver - options?.recordLiveRevision === true - ? Ref.set(lastObservedLiveRevision, liveConfiguration.revision) - : Effect.void, - ), - Effect.flatMap(({ commands, liveConfiguration, authAction }) => - applyAcceptedModelsFallback( - applyAcpRegistryAvailableCommands(provider, commands), - ).pipe( - Effect.flatMap((withBaseModels) => - Option.match( - options?.applyLiveModels === false || - !withBaseModels.enabled || - !withBaseModels.installed - ? Option.none() - : liveConfiguration.configuration, - { - onNone: () => Effect.succeed(withBaseModels), - onSome: (configuration) => - applyLiveConfiguration(withBaseModels, configuration, { - preserveSingleModelCatalog: options?.preserveSingleModelCatalog, - reasoningDisabledModelSlugs: options?.reasoningDisabledModelSlugs, - }).pipe( - Effect.map((applied) => - options?.preserveStatus === true - ? { - ...applied, - status: withBaseModels.status, - ...(withBaseModels.message === undefined - ? {} - : { message: withBaseModels.message }), - } - : applied, - ), - ), - }, - ), - ), - Effect.map((withConfiguration) => - applyAcpRegistryUrlAuthAction(withConfiguration, authAction), - ), - ), - ), - ); + if (Option.isNone(runtimeCoordinator)) { + return yield* applyAcceptedModelsFallback(provider); + } + const { commands, liveConfiguration, authAction } = yield* Effect.all({ + commands: runtimeCoordinator.value.getAvailableCommands(instanceId), + liveConfiguration: runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId), + authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId), + }); + const withBaseModels = yield* applyAcceptedModelsFallback( + applyAcpRegistryAvailableCommands(provider, commands), + ); + let withConfiguration = withBaseModels; + if ( + options?.applyLiveModels !== false && + withBaseModels.enabled && + withBaseModels.installed + ) { + const steps: Array = []; + if (Option.isSome(liveConfiguration.catalog)) { + steps.push(liveConfiguration.catalog.value); + } + if ( + Option.isSome(liveConfiguration.configuration) && + (!Option.isSome(liveConfiguration.catalog) || + liveConfiguration.configuration.value !== liveConfiguration.catalog.value) + ) { + steps.push(liveConfiguration.configuration.value); + } + for (const step of steps) { + withConfiguration = yield* applyLiveConfigurationStep(withConfiguration, step, { + preserveSingleModelCatalog: options?.preserveSingleModelCatalog, + reasoningDisabledModelSlugs: options?.reasoningDisabledModelSlugs, + hasDiscoveredCatalog: options?.hasDiscoveredCatalog, + preserveStatus: options?.preserveStatus, + // Readiness records lastObservedLiveRevision before the replacement watcher + // starts, so sync acceptedCatalog and enrichmentCache before skipping it. + updateAcceptedAndCache: options?.recordLiveRevision === true, + }); + } + if (options?.recordLiveRevision === true) { + yield* Ref.set(lastObservedLiveRevision, liveConfiguration.revision); + } + } + return applyAcpRegistryUrlAuthAction(withConfiguration, authAction); }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. const reportedLocalVersion = yield* Ref.make(null); @@ -1503,7 +1610,7 @@ export const AcpRegistryDriver: ProviderDriver + const liveCatalog = Option.filter(liveSnapshot.catalog, (configuration) => liveConfigurationReplacesAcceptedCatalog(configuration, accepted), ); const incumbent = Option.match(liveCatalog, { @@ -1573,6 +1680,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshot.revision || @@ -1595,6 +1703,7 @@ export const AcpRegistryDriver: ProviderDriver 0 : undefined, }); const completedAt = yield* Clock.currentTimeMillis; yield* Ref.set(enrichmentCache, { @@ -1679,7 +1788,8 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) - .map((model) => model.id), - ) - : acceptedBefore.reasoningDisabledModelSlugs; - if (current.auth.status !== "unauthenticated" || replacesCatalog) { - yield* Ref.update(acceptedCatalog, (previous) => - replacesCatalog - ? { - models: next.models, - builtInModelCount: effectiveConfiguration.value.models.length, - modelsFromModelSelect: - effectiveConfiguration.value.modelsFromModelSelect === true, - reasoningDisabledModelSlugs: nextReasoningDisabled, - probeOptions: null, - } - : current.status === "ready" && previous.models.length > 0 - ? { - ...previous, - models: next.models, - } - : previous, - ); - } - const now = yield* Clock.currentTimeMillis; - yield* Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration: effectiveConfiguration.value, - customModels: effectiveConfig.customModels, - now, - preserveSingleModelCatalog, - reasoningDisabledModelSlugs: acceptedBefore.reasoningDisabledModelSlugs, - }), - ); + const next = yield* applyLiveConfigurationStep(current, configuration, { + preserveStatus: current.status !== "ready", + updateAcceptedAndCache: true, + }); yield* publishSnapshot(next); }), ), @@ -1825,7 +1871,10 @@ export const AcpRegistryDriver: ProviderDriver + const clearCachedState = (options?: { + readonly clearCommands?: boolean; + readonly clearLiveConfiguration?: boolean; + }) => liveSnapshotSemaphore.withPermit( Effect.uninterruptible( invalidateEnrichmentCache.pipe( @@ -1833,15 +1882,16 @@ export const AcpRegistryDriver: ProviderDriver controller.refreshMethods ?? Effect.void)), }, - invalidateCaches: clearCachedState(), + // Keep coordinator live state on cache invalidation so probe-empty agents + // preserve running session catalogs and probes that find models supersede them. + invalidateCaches: clearCachedState({ clearLiveConfiguration: false }), orchestrationAdapter, textGeneration: makeUnsupportedTextGeneration(), acpSessionManagement: { diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 5fc41fe4af162..623fa4241fb0e 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -215,6 +215,11 @@ export interface AcpRegistryLiveConfiguration { readonly modelsFromModelSelect?: boolean; // Set on retained post-probe overrides so probe-only options stay untouched. readonly partialOptions?: boolean; + // Non-current per-model reasoning descriptors normalized from `_meta` when an + // effort selector appears mid-session without re-advertising the frozen model list. + readonly advertisedReasoning?: Readonly< + Record> + >; } export interface PreparedAcpRegistryLiveConfiguration { @@ -284,8 +289,25 @@ export function prepareAcpRegistryLiveConfiguration( .map((descriptor) => descriptor.id); const hasModelSelect = modelOption !== undefined; const resolvedCurrentModelId = currentModel === undefined ? null : currentModel.id; + const advertisedReasoningEntries: Array< + readonly [string, NonNullable] + > = []; + for (const model of advertisedModels) { + if (model.id !== resolvedCurrentModelId && model.reasoningEffort != null) { + advertisedReasoningEntries.push([model.id, model.reasoningEffort]); + } + } + const advertisedReasoning = + advertisedReasoningEntries.length > 0 + ? Object.fromEntries(advertisedReasoningEntries) + : undefined; return { - catalogKey: JSON.stringify([hasModelSelect, advertisedModels]), + // Key on catalog identity and provenance (not per-model reasoning) so toggling + // an effort selector mid-session does not re-send a frozen pre-probe model list. + catalogKey: JSON.stringify([ + hasModelSelect, + advertisedModels.map(({ id, name, description }) => [id, name, description]), + ]), toLiveConfiguration: (options) => { const includeCatalog = options?.includeCatalog !== false; return { @@ -294,6 +316,7 @@ export function prepareAcpRegistryLiveConfiguration( configOptions: descriptors, modelOptionIds, modelsFromModelSelect: includeCatalog && hasModelSelect, + ...(!includeCatalog && advertisedReasoning !== undefined ? { advertisedReasoning } : {}), }; }, }; @@ -303,13 +326,12 @@ export function normalizeAcpRegistryLiveConfiguration( configOptions: ReadonlyArray, modeState?: Parameters[0]["modeState"], modelState?: EffectAcpSchema.SessionModelState | null, - options?: { readonly includeCatalog?: boolean }, ): AcpRegistryLiveConfiguration { return prepareAcpRegistryLiveConfiguration( configOptions, modeState, modelState, - ).toLiveConfiguration(options); + ).toLiveConfiguration(); } const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({ From 380b550c345dd45e6cbb93982592d8be42f6e53c Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 13:02:59 +0000 Subject: [PATCH 13/35] fix(acp-registry): harden live replay, overflow selection, and post-probe option retention --- .../AcpRegistryRuntimeCoordinator.test.ts | 153 ++-- .../server/AcpRegistryRuntimeCoordinator.ts | 71 +- .../src/server/driver.test.ts | 703 ++++++++++++++---- .../src/server/driver.ts | 282 +++++-- .../provider-acp-registry/src/server/probe.ts | 36 +- 5 files changed, 918 insertions(+), 327 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 7aa2d683cf0bf..4bb1528da7bc5 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -328,8 +328,11 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, catalogConfig); const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(catalogSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(catalogSnap.catalog).toEqual( + Option.some({ configuration: catalogConfig, revision: catalogSnap.revision }), + ); expect(catalogSnap.configuration).toEqual(Option.some(catalogConfig)); + expect(catalogSnap.pendingOptions).toEqual([]); // Options-only update targeting model-b keeps the active catalog separately from raw options. const matchingOptionsOnly = { @@ -343,11 +346,16 @@ describe("AcpRegistryRuntimeCoordinator", () => { const matchingOptionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(matchingOptionsSnap.revision).toBe(catalogSnap.revision + 1); expect(matchingOptionsSnap.catalogRevision).toBe(catalogSnap.catalogRevision); - expect(matchingOptionsSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(matchingOptionsSnap.catalog).toEqual( + Option.some({ configuration: catalogConfig, revision: catalogSnap.revision }), + ); expect(matchingOptionsSnap.configuration).toEqual(Option.some(matchingOptionsOnly)); + expect(matchingOptionsSnap.pendingOptions).toEqual([ + { configuration: matchingOptionsOnly, revision: matchingOptionsSnap.revision }, + ]); // An options-only update from another session running an absent model neither discards - // the active catalog nor merges foreign model options into it. + // the active catalog nor drops earlier per-model pending options. const foreignOptionsOnly = { models: [], currentModelId: "model-a", @@ -357,12 +365,18 @@ describe("AcpRegistryRuntimeCoordinator", () => { }; yield* coordinator.publishLiveConfiguration(instanceId, foreignOptionsOnly); const foreignSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(foreignSnap.catalog).toEqual(Option.some(catalogConfig)); + expect(foreignSnap.catalog).toEqual( + Option.some({ configuration: catalogConfig, revision: catalogSnap.revision }), + ); expect(foreignSnap.configuration).toEqual(Option.some(foreignOptionsOnly)); + expect(foreignSnap.pendingOptions).toEqual([ + { configuration: matchingOptionsOnly, revision: matchingOptionsSnap.revision }, + { configuration: foreignOptionsOnly, revision: foreignSnap.revision }, + ]); - // A watcher starting behind the active catalog replays the catalog first, then the raw options. + // A watcher behind the active catalog replays the catalog first, then each pending option update. const replayed: Array = []; - const bothReplayed = yield* Deferred.make(); + const allReplayed = yield* Deferred.make(); const watcher = yield* coordinator .watchLiveConfiguration( instanceId, @@ -376,17 +390,48 @@ describe("AcpRegistryRuntimeCoordinator", () => { return replayed.length; }).pipe( Effect.flatMap((count) => - count === 2 ? Deferred.succeed(bothReplayed, undefined) : Effect.void, + count === 3 ? Deferred.succeed(allReplayed, undefined) : Effect.void, ), Effect.asVoid, ), { afterRevision: 0 }, ) .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(bothReplayed); + yield* Deferred.await(allReplayed); yield* Fiber.interrupt(watcher); expect(replayed).toEqual([ [2, "model-b", catalogSnap.revision], + [0, "model-b", matchingOptionsSnap.revision], + [0, "model-a", foreignSnap.revision], + ]); + + // A watcher already at the catalog revision receives only the pending raw options-only payloads. + const optionsOnlyReplay: Array = []; + const optionsReplayed = yield* Deferred.make(); + const afterCatalogWatcher = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Effect.sync(() => { + optionsOnlyReplay.push([ + configuration.models.length, + configuration.currentModelId, + revision, + ] as const); + return optionsOnlyReplay.length; + }).pipe( + Effect.flatMap((count) => + count === 2 ? Deferred.succeed(optionsReplayed, undefined) : Effect.void, + ), + Effect.asVoid, + ), + { afterRevision: catalogSnap.revision }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(optionsReplayed); + yield* Fiber.interrupt(afterCatalogWatcher); + expect(optionsOnlyReplay).toEqual([ + [0, "model-b", matchingOptionsSnap.revision], [0, "model-a", foreignSnap.revision], ]); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), @@ -442,6 +487,10 @@ describe("AcpRegistryRuntimeCoordinator", () => { }; yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyConfig); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + const retainedConfig = { + ...optionsOnlyConfig, + configOptions: [effortOption("low")], + }; expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: second.catalogRevision, @@ -455,10 +504,8 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, catalog: Option.none(), - configuration: Option.some({ - ...optionsOnlyConfig, - configOptions: [effortOption("low")], - }), + configuration: Option.some(retainedConfig), + pendingOptions: [{ configuration: retainedConfig, revision: optionsSnap.revision }], clearedThroughRevision: optionsSnap.revision, }); @@ -472,89 +519,9 @@ describe("AcpRegistryRuntimeCoordinator", () => { ...optionsSnap, catalog: Option.none(), configuration: Option.none(), + pendingOptions: [], clearedThroughRevision: optionsSnap.revision, }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); - - it.effect("replays raw options-only payloads when watching after the last catalog revision", () => - Effect.gen(function* () { - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const instanceId = ProviderInstanceId.make("acpRegistry_devin"); - const catalogModels = [ - { id: "model-b", name: "Model B", description: null }, - { id: "model-c", name: "Model C", description: null }, - ]; - const effortOption = { - id: "effort", - label: "Effort", - type: "select" as const, - role: "reasoning" as const, - currentValue: "high", - options: [ - { id: "low", label: "Low" }, - { id: "high", label: "High" }, - ], - }; - - yield* coordinator.publishLiveConfiguration(instanceId, { - models: catalogModels, - currentModelId: "model-b", - configOptions: [], - modelsFromModelSelect: true, - }); - const catalogSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - - const optionsOnly = { - models: [], - currentModelId: "model-b", - configOptions: [effortOption], - modelOptionIds: ["effort"], - modelsFromModelSelect: false, - }; - yield* coordinator.publishLiveConfiguration(instanceId, optionsOnly); - const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - - // A watcher already at the catalog revision receives only the raw options-only payload. - const rawReplay = yield* Deferred.make(); - const afterCatalogWatcher = yield* coordinator - .watchLiveConfiguration( - instanceId, - (configuration, revision) => - Deferred.succeed(rawReplay, [configuration.models.length, revision] as const).pipe( - Effect.asVoid, - ), - { afterRevision: catalogSnap.revision }, - ) - .pipe(Effect.forkChild({ startImmediately: true })); - expect(yield* Deferred.await(rawReplay)).toEqual([0, optionsSnap.revision]); - yield* Fiber.interrupt(afterCatalogWatcher); - - // A watcher behind the catalog revision receives the catalog first, then the raw options. - const fullReplay: Array = []; - const fullReplayDone = yield* Deferred.make(); - const beforeCatalogWatcher = yield* coordinator - .watchLiveConfiguration( - instanceId, - (configuration, revision) => - Effect.sync(() => { - fullReplay.push([configuration.models.length, revision] as const); - return fullReplay.length; - }).pipe( - Effect.flatMap((count) => - count === 2 ? Deferred.succeed(fullReplayDone, undefined) : Effect.void, - ), - Effect.asVoid, - ), - { afterRevision: 0 }, - ) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(fullReplayDone); - yield* Fiber.interrupt(beforeCatalogWatcher); - expect(fullReplay).toEqual([ - [catalogModels.length, catalogSnap.revision], - [0, optionsSnap.revision], - ]); - }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), - ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 6d56280e91a04..68d44af45119d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -29,28 +29,38 @@ interface LiveConfigurationUpdate { readonly revision: number; } +export interface AcpRegistryRevisionedLiveConfiguration { + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + export interface AcpRegistryLiveConfigurationSnapshot { - readonly catalog: Option.Option; + readonly catalog: Option.Option; readonly configuration: Option.Option; + readonly pendingOptions: ReadonlyArray; readonly revision: number; readonly catalogRevision: number; readonly clearedThroughRevision: number; } interface StoredLiveConfiguration { - readonly catalog: { - readonly configuration: AcpRegistryLiveConfiguration; - readonly revision: number; - } | null; + readonly catalog: AcpRegistryRevisionedLiveConfiguration | null; readonly configuration: Option.Option; + readonly optionsByModel: ReadonlyMap; readonly revision: number; readonly catalogRevision: number; readonly clearedThroughRevision: number; } +const MAX_TRACKED_MODEL_OPTIONS = 256; + +const EMPTY_OPTIONS_BY_MODEL: ReadonlyMap = + new Map(); + export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { catalog: Option.none(), configuration: Option.none(), + pendingOptions: [], revision: 0, catalogRevision: 0, clearedThroughRevision: 0, @@ -59,16 +69,23 @@ export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnap const EMPTY_STORED_LIVE_CONFIGURATION: StoredLiveConfiguration = { catalog: null, configuration: Option.none(), + optionsByModel: EMPTY_OPTIONS_BY_MODEL, revision: 0, catalogRevision: 0, clearedThroughRevision: 0, }; +const sortedPendingOptions = ( + optionsByModel: ReadonlyMap, +): ReadonlyArray => + Array.from(optionsByModel.values()).sort((left, right) => left.revision - right.revision); + const toPublicLiveConfigurationSnapshot = ( entry: StoredLiveConfiguration, ): AcpRegistryLiveConfigurationSnapshot => ({ - catalog: entry.catalog === null ? Option.none() : Option.some(entry.catalog.configuration), + catalog: entry.catalog === null ? Option.none() : Option.some(entry.catalog), configuration: entry.configuration, + pendingOptions: sortedPendingOptions(entry.optionsByModel), revision: entry.revision, catalogRevision: entry.catalogRevision, clearedThroughRevision: entry.clearedThroughRevision, @@ -277,6 +294,7 @@ const make = Effect.gen(function* () { if ( current.catalog === null && Option.isNone(current.configuration) && + current.optionsByModel.size === 0 && nextCleared === current.clearedThroughRevision ) { return state; @@ -286,6 +304,7 @@ const make = Effect.gen(function* () { ...current, catalog: null, configuration: Option.none(), + optionsByModel: EMPTY_OPTIONS_BY_MODEL, clearedThroughRevision: nextCleared, }); return next; @@ -312,9 +331,24 @@ const make = Effect.gen(function* () { modelsFromModelSelect: false, }), ); + const nextOptionsByModel: ReadonlyMap< + string | null, + AcpRegistryRevisionedLiveConfiguration + > = Option.isSome(nextConfiguration) + ? new Map([ + [ + nextConfiguration.value.currentModelId, + { configuration: nextConfiguration.value, revision: current.revision }, + ], + ]) + : EMPTY_OPTIONS_BY_MODEL; if ( current.catalog === null && Equal.equals(current.configuration, nextConfiguration) && + Equal.equals( + sortedPendingOptions(current.optionsByModel), + sortedPendingOptions(nextOptionsByModel), + ) && nextCleared === current.clearedThroughRevision ) { return [true, state] as const; @@ -324,6 +358,7 @@ const make = Effect.gen(function* () { ...current, catalog: null, configuration: nextConfiguration, + optionsByModel: nextOptionsByModel, clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -343,13 +378,26 @@ const make = Effect.gen(function* () { const catalogRevision = hasCatalog ? current.catalogRevision + 1 : current.catalogRevision; - // Store the active catalog separately from options-only updates so an - // unrelated session's options update never discards or mutates it. + // Store the active catalog and per-model options separately so an unrelated + // session's options update never discards the catalog or drops earlier models' options. const catalog = hasCatalog ? { configuration, revision } : current.catalog; + const optionsByModel = hasCatalog + ? EMPTY_OPTIONS_BY_MODEL + : (() => { + const updated = new Map(current.optionsByModel); + updated.delete(configuration.currentModelId); + updated.set(configuration.currentModelId, { configuration, revision }); + if (updated.size > MAX_TRACKED_MODEL_OPTIONS) { + const oldestKey = updated.keys().next().value; + if (oldestKey !== undefined) updated.delete(oldestKey); + } + return updated; + })(); const next = new Map(state); next.set(instanceId, { catalog, configuration: Option.some(configuration), + optionsByModel, revision, catalogRevision, clearedThroughRevision: current.clearedThroughRevision, @@ -395,9 +443,10 @@ const make = Effect.gen(function* () { deliveredRevision = current.catalog.revision; yield* onUpdate(current.catalog.configuration, current.catalog.revision); } - if (Option.isSome(current.configuration) && current.revision > deliveredRevision) { - deliveredRevision = current.revision; - yield* onUpdate(current.configuration.value, current.revision); + for (const entry of sortedPendingOptions(current.optionsByModel)) { + if (entry.revision <= deliveredRevision) continue; + deliveredRevision = entry.revision; + yield* onUpdate(entry.configuration, entry.revision); } } yield* Stream.fromSubscription(subscription).pipe( diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index fd45fdd110d23..a8ada607676e2 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1483,7 +1483,15 @@ describe("acpRegistryEnrichmentCache", () => { }), ); - // Drops reasoning when the probe disables it and returns none when no live option survives. + // Drops reasoning when the probe disables it, while keeping currentModelId selection when it differs from probe default. + const selectionOnly = Option.some({ + models: [], + currentModelId: "old-model", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + }); expect( retainAcpRegistryLiveOptionsAfterProbe( { @@ -1503,7 +1511,21 @@ describe("acpRegistryEnrichmentCache", () => { modelOptionIds: new Set(["effort"]), }, ), - ).toEqual(Option.none()); + ).toEqual(selectionOnly); + const appliedSelectionOnly = applyAcpRegistryLiveConfiguration( + probeWithFast(false), + Option.getOrThrow(selectionOnly), + [], + ); + expect(appliedSelectionOnly.models.find((m) => m.slug === "old-model")?.isDefault).toBe(true); + expect( + appliedSelectionOnly.models + .find((m) => m.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["mode", "ask"], + ["fast", false], + ]); // Drops model-specific options when the probe ran directly on that model without them. expect( @@ -1524,7 +1546,8 @@ describe("acpRegistryEnrichmentCache", () => { ), ).toEqual(Option.none()); - // Never promotes a live model-specific option into a probe-shared option across models. + // Never promotes a live model-specific option into a probe-shared option across models, + // retaining only model selection when no options survive on a different probed model. expect( retainAcpRegistryLiveOptionsAfterProbe( { @@ -1544,7 +1567,7 @@ describe("acpRegistryEnrichmentCache", () => { modelOptionIds: new Set(), }, ), - ).toEqual(Option.none()); + ).toEqual(selectionOnly); // Off-current reasoning retention requires matching native option IDs (thinking != effort). expect( @@ -1580,12 +1603,12 @@ describe("acpRegistryEnrichmentCache", () => { modelOptionIds: new Set(["effort"]), }, ), - ).toEqual(Option.none()); + ).toEqual(selectionOnly); }); }); describe("prepareAcpRegistryLiveConfiguration", () => { - it("ignores in-cap selection and effort selector toggles while detecting overflow selection, renames, and projecting newly normalized per-model reasoning", () => { + it("keeps catalogKey stable across selection and effort toggles while carrying overflow selection, detecting renames, and safely projecting per-model reasoning", () => { const modelSelect = ( currentValue: string, options: ReadonlyArray<{ value: string; name: string }>, @@ -1606,9 +1629,55 @@ describe("prepareAcpRegistryLiveConfiguration", () => { const keyM0 = prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).catalogKey; expect(prepareAcpRegistryLiveConfiguration(modelSelect("m1", choices)).catalogKey).toBe(keyM0); - expect(prepareAcpRegistryLiveConfiguration(modelSelect("m256", choices)).catalogKey).not.toBe( - keyM0, + const preparedM256 = prepareAcpRegistryLiveConfiguration(modelSelect("m256", choices)); + expect(preparedM256.catalogKey).toBe(keyM0); + const overflowOptionsOnly = preparedM256.toLiveConfiguration({ includeCatalog: false }); + expect(overflowOptionsOnly.models).toEqual([]); + expect(overflowOptionsOnly.currentModel).toEqual({ + id: "m256", + name: "Model 256", + description: null, + }); + const cappedProvider = providerWithModels( + choices.slice(0, 256).map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + "m0", + ); + const withOverflowSelected = applyAcpRegistryLiveConfiguration( + cappedProvider, + overflowOptionsOnly, + [], + ); + expect(withOverflowSelected.models).toHaveLength(256); + expect(withOverflowSelected.models.at(-1)?.slug).toBe("m256"); + expect(withOverflowSelected.models.at(-1)?.isDefault).toBe(true); + // Switching back to m255 restores m255 into the last slot without re-sending the catalog. + const withM255Restored = applyAcpRegistryLiveConfiguration( + withOverflowSelected, + prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + [], + ); + expect(withM255Restored.models).toHaveLength(256); + expect(withM255Restored.models.at(-1)?.slug).toBe("m255"); + expect(withM255Restored.models.at(-1)?.isDefault).toBe(true); + // A smaller catalog must never absorb an overflow model from another session. + const smallProvider = providerWithModels( + [ + { id: "p0", name: "P0", description: null }, + { id: "p1", name: "P1", description: null }, + ], + "p0", ); + expect( + applyAcpRegistryLiveConfiguration(smallProvider, overflowOptionsOnly, []).models.map( + (model) => model.slug, + ), + ).toEqual(["p0", "p1"]); expect( prepareAcpRegistryLiveConfiguration( modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...choices.slice(1)]), @@ -1668,6 +1737,7 @@ describe("prepareAcpRegistryLiveConfiguration", () => { [ { id: "model-a", name: "Model A", description: null }, { id: "model-b", name: "Model B", description: null }, + { id: "constructor", name: "Constructor", description: null }, ], "model-a", ), @@ -1679,6 +1749,10 @@ describe("prepareAcpRegistryLiveConfiguration", () => { .find((model) => model.slug === "model-b") ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), ).toEqual([["effort", "low"]]); + expect( + appliedToActive.models.find((model) => model.slug === "constructor")?.capabilities + ?.optionDescriptors, + ).toEqual([]); }); }); @@ -1873,159 +1947,167 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }), ); - it.effect("drops cached and session-reported models when its caches are invalidated", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + it.effect( + "supersedes session-reported models on invalidateCaches when a fresh probe finds models, and preserves them when it finds none", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "other-model"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version: "1.0.0", - distribution: "npx", - }), - resolve: () => - Effect.succeed({ - distribution: "npx" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", }), - }), - ); - const modelSlugs = instance.snapshot.streamChanges.pipe( - Stream.map((snapshot) => snapshot.models.map((model) => model.slug)), - ); - const waitForModels = (expected: ReadonlyArray) => - modelSlugs.pipe( - Stream.filter((slugs) => slugs.join() === expected.join()), - Stream.runHead, + resolve: () => + Effect.succeed({ + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), ); + const modelSlugs = instance.snapshot.streamChanges.pipe( + Stream.map((snapshot) => snapshot.models.map((model) => model.slug)), + ); + const waitForModels = (expected: ReadonlyArray) => + modelSlugs.pipe( + Stream.filter((slugs) => slugs.join() === expected.join()), + Stream.runHead, + ); - const probed = yield* waitForModels(["old-model", "other-model"]).pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - yield* Fiber.join(probed); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - normalizeAcpRegistryLiveConfiguration( - [ - { - id: "legacy", - name: "Legacy", - category: "other", - type: "select", - currentValue: "on", - options: [{ value: "on", name: "On" }], - }, - ], - undefined, - { - currentModelId: "old-model", - availableModels: [ - { modelId: "old-model", name: "old-model" }, - { modelId: "session-model", name: "session-model" }, + const probed = yield* waitForModels(["old-model", "other-model"]).pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(probed); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "legacy", + name: "Legacy", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, ], - }, - ), - ); - yield* fileSystem.writeFileString( - modelsPath, - JSON.stringify({ - models: ["old-model", "new-model"], - configOptions: [ + undefined, { - id: "fast", - name: "Fast", - category: "other", - type: "select", - currentValue: "on", - options: [{ value: "on", name: "On" }], + currentModelId: "old-model", + availableModels: [ + { modelId: "old-model", name: "old-model" }, + { modelId: "session-model", name: "session-model" }, + ], }, - ], - }), - ); + ), + ); + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify({ + models: ["old-model", "new-model"], + configOptions: [ + { + id: "fast", + name: "Fast", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ], + }), + ); - const refreshed = yield* waitForModels(["old-model", "new-model"]).pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.invalidateCaches ?? Effect.void; - yield* instance.snapshot.refresh; - expect(Option.isSome(yield* Fiber.join(refreshed))).toBe(true); + const refreshed = yield* waitForModels(["old-model", "new-model"]).pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(refreshed))).toBe(true); - // A still-running session sending an options-only update after invalidateCaches must still - // reconcile against the replacement probe's schema (keeping fast and dropping legacy). - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - prepareAcpRegistryLiveConfiguration( - [ + // A still-running session sending an options-only update after invalidateCaches must still + // reconcile against the replacement probe's schema (keeping fast and dropping legacy). + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + [ + { + id: "legacy", + name: "Legacy", + category: "other", + type: "select", + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ], + undefined, { - id: "legacy", - name: "Legacy", - category: "other", - type: "select", - currentValue: "on", - options: [{ value: "on", name: "On" }], + currentModelId: "old-model", + availableModels: [ + { modelId: "old-model", name: "old-model" }, + { modelId: "session-model", name: "session-model" }, + ], }, - ], - undefined, - { - currentModelId: "old-model", + ).toLiveConfiguration({ includeCatalog: false }), + ); + // Force a cached refresh so the semaphore-serialized watcher has finished before reading. + const synced = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterOptions = Option.getOrThrow(yield* Fiber.join(synced)); + expect(afterOptions.models.map((model) => model.slug)).toEqual(["old-model", "new-model"]); + expect( + afterOptions.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([["fast", "on"]]); + + // When a probe returns no models, invalidateCaches + refresh must preserve the running + // session's catalog instead of dropping to synthetic default. + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "session-x", availableModels: [ - { modelId: "old-model", name: "old-model" }, - { modelId: "session-model", name: "session-model" }, + { modelId: "session-x", name: "session-x" }, + { modelId: "session-y", name: "session-y" }, ], - }, - ).toLiveConfiguration({ includeCatalog: false }), - ); - // Force a cached refresh so the semaphore-serialized watcher has finished before reading. - const synced = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - const afterOptions = Option.getOrThrow(yield* Fiber.join(synced)); - expect(afterOptions.models.map((model) => model.slug)).toEqual(["old-model", "new-model"]); - expect( - afterOptions.models - .find((model) => model.slug === "old-model") - ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), - ).toEqual([["fast", "on"]]); - - // When a probe returns no models, invalidateCaches + refresh must preserve the running - // session's catalog instead of dropping to synthetic default. - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - normalizeAcpRegistryLiveConfiguration([], undefined, { - currentModelId: "session-x", - availableModels: [ - { modelId: "session-x", name: "session-x" }, - { modelId: "session-y", name: "session-y" }, - ], - }), - ); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify([])); - const emptyProbeAfterInvalidate = yield* waitForModels(["session-x", "session-y"]).pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.invalidateCaches ?? Effect.void; - yield* instance.snapshot.refresh; - expect(Option.isSome(yield* Fiber.join(emptyProbeAfterInvalidate))).toBe(true); - }), + }), + ); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify([])); + const emptyProbeAfterInvalidate = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + const afterEmptyProbe = Option.getOrThrow(yield* Fiber.join(emptyProbeAfterInvalidate)); + expect(afterEmptyProbe.models.map((model) => model.slug)).toEqual([ + "session-x", + "session-y", + ]); + }), ); it.effect("keeps a local agent's reported version through the next readiness check", () => @@ -3772,8 +3854,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.await(handoffCallbackBlocked); // Refresh interrupts the blocked watcher; readiness must still have synced acceptedCatalog - // before recording lastObservedLiveRevision, so a subsequent provisional probe keeps it. + // before recording lastObservedLiveRevision, so clearing the coordinator and running a + // subsequent provisional probe still keeps the accepted catalog. yield* instance.snapshot.refresh; + yield* coordinator.clearLiveConfiguration(identity.instanceId); yield* writeModels({ provisional: "placeholder" }); yield* TestClock.adjust("16 minutes"); const afterProvisional = yield* waitForEnriched().pipe( @@ -3795,4 +3879,325 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); }), ); + + it.effect( + "does not revert learned options to an already-applied catalog and replays all blocked per-model options on refresh", + () => + Effect.gen(function* () { + const blockBWatcher = yield* Deferred.make(); + let shouldBlockB = false; + const { coordinator, instance, waitForEnriched } = yield* setupPeriodicDriver({ + prefix: "acp-driver-replay-", + initialModels: ["model-a", "model-b"], + wrapCoordinator: (base) => ({ + ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + shouldBlockB && configuration.currentModelId === "model-b" + ? Effect.sync(() => { + shouldBlockB = false; + }).pipe( + Effect.andThen(Deferred.succeed(blockBWatcher, undefined)), + Effect.andThen(Effect.never), + ) + : onUpdate(configuration, revision), + options, + ), + }), + }); + const effortSelect = (currentValue: "low" | "high") => ({ + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue, + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); + const variantSelect = (currentValue: "v1" | "v2") => ({ + id: "variant", + label: "Variant", + type: "select" as const, + currentValue, + options: [ + { id: "v1", label: "V1" }, + { id: "v2", label: "V2" }, + ], + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish catalog [model-a (effort=low), model-b], then update model-a to effort=high, + // then switch to model-b. A readiness refresh must not relearn effort=low from the catalog. + const waitForEffort = (slug: string, expected: string) => + instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === slug) + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === expected, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + + const sawLow = yield* waitForEffort("model-a", "low"); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null }, + ], + currentModelId: "model-a", + configOptions: [effortSelect("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + yield* Fiber.join(sawLow); + + const sawHigh = yield* waitForEffort("model-a", "high"); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [effortSelect("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawHigh); + + const sawBDefault = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.find((m) => m.slug === "model-b")?.isDefault === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawBDefault); + + const refreshed = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterRefresh = Option.getOrThrow(yield* Fiber.join(refreshed)); + expect( + afterRefresh.models + .find((m) => m.slug === "model-a") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + expect(afterRefresh.models.find((m) => m.slug === "model-b")?.isDefault).toBe(true); + + // Block the watcher on model-b, then publish both model-b (variant=v1) and model-a (effort=low). + // Readiness handoff must replay both pending per-model updates, not only the last one. + shouldBlockB = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [variantSelect("v1")], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }); + yield* Deferred.await(blockBWatcher); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [effortSelect("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + + const handoff = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterHandoff = Option.getOrThrow(yield* Fiber.join(handoff)); + expect( + afterHandoff.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + expect( + afterHandoff.models + .find((m) => m.slug === "model-a") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "low"]]); + }), + ); + + it.effect( + "removes options a live model stops reporting after a superseding probe and preserves concurrent live catalogs", + () => + Effect.gen(function* () { + let injectLiveCatalogAfterClear = false; + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-post-probe-", + initialModels: ["model-a", "model-b"], + wrapCoordinator: (base) => ({ + ...base, + clearLiveConfigurationIfRevision: (instanceId, options) => + base.clearLiveConfigurationIfRevision(instanceId, options).pipe( + Effect.tap((cleared) => + cleared && injectLiveCatalogAfterClear + ? Effect.sync(() => { + injectLiveCatalogAfterClear = false; + }).pipe( + Effect.andThen( + base.publishLiveConfiguration(instanceId, { + models: [ + { id: "live-c", name: "Live C", description: null }, + { id: "live-d", name: "Live D", description: null }, + ], + currentModelId: "live-c", + configOptions: [], + modelsFromModelSelect: true, + }), + ), + Effect.andThen( + base.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "live-c", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }), + ), + ) + : Effect.void, + ), + ), + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish a live catalog so the next probe supersedes a live session and records probeOptions. + const sawPreProbe = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((m) => m.slug === "pre-probe")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "pre-probe", name: "Pre Probe", description: null }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(sawPreProbe); + + yield* writeModels(["model-a", "model-b"]); + yield* TestClock.adjust("16 minutes"); + const superseded = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(superseded); + + // Model B learns variant=v1, then reports no options: variant must be dropped while keeping B default. + const sawVariant = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "variant") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [ + { + id: "variant", + label: "Variant", + type: "select", + currentValue: "v1", + options: [{ id: "v1", label: "V1" }], + }, + ], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawVariant); + + const sawDropped = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.find((m) => m.slug === "model-b")?.isDefault === true && + (snapshot.models.find((m) => m.slug === "model-b")?.capabilities?.optionDescriptors + ?.length ?? 0) === 0, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawDropped); + + const afterDropRefresh = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const droppedSnapshot = Option.getOrThrow(yield* Fiber.join(afterDropRefresh)); + expect(droppedSnapshot.models.find((m) => m.slug === "model-b")?.isDefault).toBe(true); + expect( + droppedSnapshot.models.find((m) => m.slug === "model-b")?.capabilities?.optionDescriptors, + ).toEqual([]); + + // When a fresh live catalog + options-only update arrive right after clearLiveConfigurationIfRevision, + // the probe commit's replay must preserve the new catalog and its options rather than snapping back to probe baseline. + injectLiveCatalogAfterClear = true; + yield* writeModels(["probe-1", "probe-2"]); + yield* TestClock.adjust("16 minutes"); + const concurrentCommit = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const published = Option.getOrThrow(yield* Fiber.join(concurrentCommit)); + expect(published.models.map((m) => m.slug)).toEqual(["live-c", "live-d"]); + expect( + published.models + .find((m) => m.slug === "live-c") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index d28d93c9ccf91..0d1a7eef56061 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -50,6 +50,7 @@ import { type ProviderSnapshotSettings, } from "@t3tools/provider-core/server/snapshotSettings"; import { + ACP_REGISTRY_MAX_MODELS, type AcpRegistryAvailableCommands, type AcpRegistryConfigurationProbe, type AcpRegistryConfigurationProbeResult, @@ -99,6 +100,7 @@ interface AcceptedAcpRegistryCatalog { readonly modelsFromModelSelect: boolean; readonly reasoningDisabledModelSlugs: ReadonlySet; readonly probeOptions: AcpRegistryProbeOptionSchema | null; + readonly probeBaselineModels: ReadonlyArray | null; } const EMPTY_SLUG_SET: ReadonlySet = new Set(); @@ -109,6 +111,7 @@ const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { modelsFromModelSelect: false, reasoningDisabledModelSlugs: EMPTY_SLUG_SET, probeOptions: null, + probeBaselineModels: null, }; function isExplicitSingletonCatalog(catalog: { @@ -257,11 +260,21 @@ function modelWithSpecificOptions( }; } +function readAdvertisedReasoning( + advertisedReasoning: AcpRegistryLiveConfiguration["advertisedReasoning"], + slug: string, +): NonNullable | undefined { + return advertisedReasoning !== undefined && Object.hasOwn(advertisedReasoning, slug) + ? advertisedReasoning[slug] + : undefined; +} + function updateLearnedModelsFromLive( learned: ReadonlyArray, nextModels: ReadonlyArray, configuration: AcpRegistryLiveConfiguration, disabledReasoningSlugs: ReadonlySet = EMPTY_SLUG_SET, + options?: { readonly replaceCurrentLearnedOptions?: boolean }, ): ReadonlyArray { const modelOptionIds = new Set(configuration.modelOptionIds ?? []); const learnedBySlug = new Map( @@ -275,7 +288,7 @@ function updateLearnedModelsFromLive( configuration.currentModelId !== null && model.slug === configuration.currentModelId; const hasAdvertisedReasoning = configuredById.get(model.slug)?.reasoningEffort !== undefined || - configuration.advertisedReasoning?.[model.slug] !== undefined; + readAdvertisedReasoning(configuration.advertisedReasoning, model.slug) !== undefined; const isReasoningDisabled = disabledReasoningSlugs.has(model.slug); if (!isCurrentModel && !hasAdvertisedReasoning && !isReasoningDisabled) continue; const descriptors = model.capabilities?.optionDescriptors ?? []; @@ -283,7 +296,7 @@ function updateLearnedModelsFromLive( const previousDescriptors = previous?.capabilities?.optionDescriptors ?? []; const previousIds = new Set(previousDescriptors.map((descriptor) => descriptor.id)); const specific = isCurrentModel - ? configuration.partialOptions === true + ? configuration.partialOptions === true && options?.replaceCurrentLearnedOptions !== true ? descriptors.filter( (descriptor) => (isModelSpecificDescriptor(descriptor, modelOptionIds) || @@ -339,12 +352,11 @@ export function retainAcpRegistryLiveOptionsAfterProbe( live: AcpRegistryLiveConfiguration, probe: AcpRegistryProbeOptionSchema, ): Option.Option { - if (live.configOptions.length === 0) return Option.none(); - const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); - const liveModelOptionIds = new Set(live.modelOptionIds ?? []); const probedModelById = new Map(probe.models.map((model) => [model.id, model])); const currentProbedModel = live.currentModelId === null ? undefined : probedModelById.get(live.currentModelId); + const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); + const liveModelOptionIds = new Set(live.modelOptionIds ?? []); const probeSharedIds = new Set(); const sharedDescriptors: Array = []; @@ -394,7 +406,21 @@ export function retainAcpRegistryLiveOptionsAfterProbe( } const configOptions = [...sharedDescriptors, ...modelDescriptors]; - if (configOptions.length === 0) return Option.none(); + if (configOptions.length === 0) { + // Keep the running session's model selection moving isDefault even when no + // options survive, unless it already matches the probe's default model. + if (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) { + return Option.none(); + } + return Option.some({ + models: [], + currentModelId: currentProbedModel.id, + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + }); + } return Option.some({ models: [], // Keep live.currentModelId even when removed upstream so overlay does not @@ -412,11 +438,13 @@ function mergeLearnedModelOptions( learned: ReadonlyArray, options?: { readonly currentModelId?: string | null; + readonly skipModelSlugs?: ReadonlySet; readonly reasoningDisabledModelSlugs?: ReadonlySet; }, ): ReadonlyArray { if (learned.length === 0) return models; const currentModelId = options?.currentModelId ?? null; + const skipModelSlugs = options?.skipModelSlugs ?? EMPTY_SLUG_SET; const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; const learnedBySlug = new Map( learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), @@ -424,7 +452,13 @@ function mergeLearnedModelOptions( let changed = false; const merged = models.map((model) => { // The probe already observed its currentModelId in full; do not restore dropped options onto it. - if (model.isCustom || (currentModelId !== null && model.slug === currentModelId)) return model; + if ( + model.isCustom || + (currentModelId !== null && model.slug === currentModelId) || + skipModelSlugs.has(model.slug) + ) { + return model; + } const previousDescriptors = learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; if (previousDescriptors.length === 0) return model; @@ -815,9 +849,17 @@ export function applyAcpRegistryLiveConfiguration( const disabledReasoningSlugs: ReadonlySet = useLiveCatalog ? EMPTY_SLUG_SET : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); + const overflowCurrentModel = + !useLiveCatalog && + configuration.currentModel !== undefined && + probedModels.length >= ACP_REGISTRY_MAX_MODELS && + !probedModels.some((model) => model.slug === configuration.currentModel!.id) + ? configuration.currentModel + : undefined; const liveCurrentModelInProbed = - configuration.currentModelId !== null && - probedModels.some((model) => model.slug === configuration.currentModelId); + overflowCurrentModel !== undefined || + (configuration.currentModelId !== null && + probedModels.some((model) => model.slug === configuration.currentModelId)); const selectedProbedModelId = liveCurrentModelInProbed ? configuration.currentModelId : (probedModels.find((model) => model.isDefault)?.slug ?? null); @@ -856,34 +898,41 @@ export function applyAcpRegistryLiveConfiguration( !useLiveCatalog && configuration.advertisedReasoning !== undefined && Object.keys(configuration.advertisedReasoning).length > 0; + const retainedDiscoveryModels: Array = probedModels.map((model) => { + if (disabledReasoningSlugs.has(model.slug)) { + return { + id: model.slug, + name: model.name, + description: null, + reasoningEffort: null, + }; + } + const advertised = readAdvertisedReasoning(configuration.advertisedReasoning, model.slug); + return { + id: model.slug, + name: model.name, + description: null, + ...(advertised === undefined ? {} : { reasoningEffort: advertised }), + }; + }); + if (overflowCurrentModel !== undefined) { + retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = overflowCurrentModel; + } const discovery = useLiveCatalog ? configuration : { ...configuration, - models: probedModels.map((model) => { - if (disabledReasoningSlugs.has(model.slug)) { - return { - id: model.slug, - name: model.name, - description: null, - reasoningEffort: null, - }; - } - const advertised = configuration.advertisedReasoning?.[model.slug]; - return { - id: model.slug, - name: model.name, - description: null, - ...(advertised === undefined ? {} : { reasoningEffort: advertised }), - }; - }), + models: retainedDiscoveryModels, currentModelId: dropUnmatchedModelOptions ? configuration.currentModelId : selectedProbedModelId, configOptions: effectiveConfigOptions, }; const nextModels = - !useLiveCatalog && effectiveConfigOptions.length === 0 && !hasAdvertisedReasoning + !useLiveCatalog && + effectiveConfigOptions.length === 0 && + !hasAdvertisedReasoning && + overflowCurrentModel === undefined ? stripReasoningForDisabledModels( withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), disabledReasoningSlugs, @@ -1256,6 +1305,12 @@ export const AcpRegistryDriver: ProviderDriver(EMPTY_ACCEPTED_CATALOG); const clearAcceptedCatalog = Ref.set(acceptedCatalog, EMPTY_ACCEPTED_CATALOG); + const lastObservedLiveRevision = yield* Ref.make(0); + const lastAppliedLiveCatalogRevision = yield* Ref.make(0); + const lastAppliedLiveRevision = yield* Ref.make(0); + const resetAppliedLiveRevisions = Ref.set(lastAppliedLiveCatalogRevision, 0).pipe( + Effect.andThen(Ref.set(lastAppliedLiveRevision, 0)), + ); const applyLiveConfiguration = ( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, @@ -1263,6 +1318,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; readonly hasDiscoveredCatalog?: boolean | undefined; + readonly replaceCurrentLearnedOptions?: boolean | undefined; }, ) => Ref.get(acceptedCatalog).pipe( @@ -1285,7 +1341,15 @@ export const AcpRegistryDriver: ProviderDriver model.id === configuration.currentModelId) + ? configuration.currentModelId + : null; + const skipModelSlugs = new Set(); + if (probeOptions.currentModelId !== null) { + skipModelSlugs.add(probeOptions.currentModelId); + } + if (replacedLiveModelId !== null) { + skipModelSlugs.add(replacedLiveModelId); + } + // Rebuild from the pure probe baseline so rejected values restore probe + // defaults and options a live model stops reporting are removed. + const pureBaseline = acceptedBefore.probeBaselineModels ?? acceptedBefore.models; const baselineModels = yield* Ref.get(learnedModels).pipe( Effect.map((learned) => - mergeLearnedModelOptions(acceptedBefore.models, learned, { - currentModelId: acceptedBefore.probeOptions!.currentModelId, + mergeLearnedModelOptions(pureBaseline, learned, { + skipModelSlugs, reasoningDisabledModelSlugs, }), ), ); const baselineProvider = - acceptedBefore.models.length > 0 ? { ...current, models: baselineModels } : current; + pureBaseline.length > 0 ? { ...current, models: baselineModels } : current; const applied = yield* Option.match(effectiveConfiguration, { - onNone: () => Effect.succeed(baselineProvider), + onNone: () => + replacedLiveModelId === null + ? Effect.succeed(baselineProvider) + : Ref.update(learnedModels, (learned) => + updateLearnedModelsFromLive( + learned, + baselineProvider.models, + { + models: [], + currentModelId: replacedLiveModelId, + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }, + reasoningDisabledModelSlugs, + ), + ).pipe(Effect.as(baselineProvider)), onSome: (partial) => applyLiveConfiguration(baselineProvider, partial, { preserveSingleModelCatalog, reasoningDisabledModelSlugs, hasDiscoveredCatalog, + replaceCurrentLearnedOptions: replacedLiveModelId !== null, }), }); + if (options?.updateAcceptedAndCache === true && options.revision !== undefined) { + const appliedRevision = options.revision; + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, appliedRevision)); + } return withPreservedStatus(applied); } @@ -1365,7 +1468,11 @@ export const AcpRegistryDriver: ProviderDriver model.id), ) : acceptedBefore.reasoningDisabledModelSlugs; - if (current.auth.status !== "unauthenticated" || replacesCatalog) { + const savedToAccepted = + current.installed && + (current.auth.status !== "unauthenticated" || replacesCatalog) && + (replacesCatalog || acceptedBefore.models.length > 0); + if (savedToAccepted) { yield* Ref.update(acceptedCatalog, (previous) => replacesCatalog ? { @@ -1374,14 +1481,22 @@ export const AcpRegistryDriver: ProviderDriver 0 - ? { - ...previous, - models: next.models, - } - : previous, + : { + ...previous, + models: next.models, + }, ); + if (options.revision !== undefined) { + const appliedRevision = options.revision; + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, appliedRevision)); + if (configuration.models.length > 0) { + yield* Ref.update(lastAppliedLiveCatalogRevision, (prev) => + Math.max(prev, appliedRevision), + ); + } + } } const now = yield* Clock.currentTimeMillis; yield* Ref.update(enrichmentCache, (cache) => @@ -1399,7 +1514,6 @@ export const AcpRegistryDriver: ProviderDriver = []; - if (Option.isSome(liveConfiguration.catalog)) { - steps.push(liveConfiguration.catalog.value); - } + const accepted = yield* Ref.get(acceptedCatalog); + const appliedCatalogRev = yield* Ref.get(lastAppliedLiveCatalogRevision); + const appliedRev = yield* Ref.get(lastAppliedLiveRevision); + const steps: Array = + []; if ( - Option.isSome(liveConfiguration.configuration) && - (!Option.isSome(liveConfiguration.catalog) || - liveConfiguration.configuration.value !== liveConfiguration.catalog.value) + Option.isSome(liveConfiguration.catalog) && + liveConfiguration.catalog.value.revision > liveConfiguration.clearedThroughRevision && + liveConfiguration.catalog.value.revision > appliedCatalogRev ) { - steps.push(liveConfiguration.configuration.value); + steps.push(liveConfiguration.catalog.value); } + const hasNewCatalogStep = steps.length > 0; + if (accepted.probeOptions !== null && !hasNewCatalogStep) { + for (const entry of liveConfiguration.pendingOptions) { + steps.push(entry); + } + } else { + for (const entry of liveConfiguration.pendingOptions) { + if (entry.revision <= liveConfiguration.clearedThroughRevision) continue; + if (!hasNewCatalogStep && entry.revision <= appliedRev) continue; + steps.push(entry); + } + } + let catalogReplacedInReplay = false; for (const step of steps) { - withConfiguration = yield* applyLiveConfigurationStep(withConfiguration, step, { - preserveSingleModelCatalog: options?.preserveSingleModelCatalog, - reasoningDisabledModelSlugs: options?.reasoningDisabledModelSlugs, - hasDiscoveredCatalog: options?.hasDiscoveredCatalog, - preserveStatus: options?.preserveStatus, - // Readiness records lastObservedLiveRevision before the replacement watcher - // starts, so sync acceptedCatalog and enrichmentCache before skipping it. - updateAcceptedAndCache: options?.recordLiveRevision === true, - }); + const stepAccepted = yield* Ref.get(acceptedCatalog); + const stepReplacesCatalog = liveConfigurationReplacesAcceptedCatalog( + step.configuration, + stepAccepted, + ); + withConfiguration = yield* applyLiveConfigurationStep( + withConfiguration, + step.configuration, + { + preserveSingleModelCatalog: options?.preserveSingleModelCatalog, + reasoningDisabledModelSlugs: options?.reasoningDisabledModelSlugs, + hasDiscoveredCatalog: options?.hasDiscoveredCatalog, + preserveStatus: options?.preserveStatus, + // Readiness records lastObservedLiveRevision before the replacement watcher + // starts, so sync acceptedCatalog and enrichmentCache before skipping it. + updateAcceptedAndCache: options?.recordLiveRevision === true, + ignoreProbeBaseline: catalogReplacedInReplay && !stepReplacesCatalog, + revision: step.revision, + }, + ); + if (stepReplacesCatalog) { + catalogReplacedInReplay = true; + } } if (options?.recordLiveRevision === true) { yield* Ref.set(lastObservedLiveRevision, liveConfiguration.revision); @@ -1610,8 +1752,10 @@ export const AcpRegistryDriver: ProviderDriver - liveConfigurationReplacesAcceptedCatalog(configuration, accepted), + const liveCatalog = Option.filter( + Option.map(liveSnapshot.catalog, (entry) => entry.configuration), + (configuration) => + liveConfigurationReplacesAcceptedCatalog(configuration, accepted), ); const incumbent = Option.match(liveCatalog, { onSome: (configuration) => ({ @@ -1652,11 +1796,7 @@ export const AcpRegistryDriver: ProviderDriver 0 - ) { + if (!probeSupersedesLiveCatalog && accepted.models.length > 0) { resolved = { ...provider, models: accepted.models }; } else { const models = yield* Ref.modify(learnedModels, (learned) => { @@ -1685,12 +1825,15 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshot.revision || accepted.probeOptions !== null; + yield* Ref.set(lastAppliedLiveCatalogRevision, 0); + yield* Ref.set(lastAppliedLiveRevision, afterClear.clearedThroughRevision); yield* Ref.set(acceptedCatalog, { models: resolved.models, builtInModelCount: probedModelCount, modelsFromModelSelect: probedModelsFromModelSelect, reasoningDisabledModelSlugs, probeOptions: supersededLiveSession ? probeOptionSchema : null, + probeBaselineModels: supersededLiveSession ? provider.models : null, }); } const published = yield* withLiveRuntimeState(resolved, { @@ -1730,6 +1873,7 @@ export const AcpRegistryDriver: ProviderDriver> >; + // Selected model beyond MAX_MODELS, carried without re-advertising the capped catalog. + readonly currentModel?: AcpRegistryProbeModel; } export interface PreparedAcpRegistryLiveConfiguration { @@ -266,14 +269,32 @@ export function prepareAcpRegistryLiveConfiguration( metaByModelId.set(info.modelId, info._meta); } } - const advertisedModels = normalizeModels(candidates, boundedCurrentModelId).map((model) => { + const attachReasoning = (model: AcpRegistryProbeModel): AcpRegistryProbeModel => { const reasoningEffort = advertisedReasoningEffort(effortOption, metaByModelId.get(model.id)); return reasoningEffort === undefined ? model : { ...model, reasoningEffort }; - }); + }; + const baseModels = normalizeModels(candidates, null).map(attachReasoning); + const currentInBase = + boundedCurrentModelId !== null && + baseModels.some((model) => model.id === boundedCurrentModelId); + const advertisedModels = + boundedCurrentModelId === null || currentInBase + ? baseModels + : normalizeModels(candidates, boundedCurrentModelId).map(attachReasoning); const currentModel = boundedCurrentModelId === null ? undefined : advertisedModels.find((model) => model.id === boundedCurrentModelId); + const currentInStablePrefix = + boundedCurrentModelId !== null && + baseModels.slice(0, MAX_MODELS - 1).some((model) => model.id === boundedCurrentModelId); + const overflowCurrentModel = + currentModel !== undefined && + baseModels.length === MAX_MODELS && + candidates.length > MAX_MODELS && + !currentInStablePrefix + ? currentModel + : undefined; const stripCurrentReasoning = currentModel?.reasoningEffort === null; const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( (descriptor) => @@ -302,11 +323,11 @@ export function prepareAcpRegistryLiveConfiguration( ? Object.fromEntries(advertisedReasoningEntries) : undefined; return { - // Key on catalog identity and provenance (not per-model reasoning) so toggling - // an effort selector mid-session does not re-send a frozen pre-probe model list. + // Key on the uncapped-selection catalog identity and provenance so neither effort + // toggles nor selecting a model beyond MAX_MODELS re-advertise a frozen list. catalogKey: JSON.stringify([ hasModelSelect, - advertisedModels.map(({ id, name, description }) => [id, name, description]), + baseModels.map(({ id, name, description }) => [id, name, description]), ]), toLiveConfiguration: (options) => { const includeCatalog = options?.includeCatalog !== false; @@ -317,6 +338,9 @@ export function prepareAcpRegistryLiveConfiguration( modelOptionIds, modelsFromModelSelect: includeCatalog && hasModelSelect, ...(!includeCatalog && advertisedReasoning !== undefined ? { advertisedReasoning } : {}), + ...(!includeCatalog && overflowCurrentModel !== undefined + ? { currentModel: overflowCurrentModel } + : {}), }; }, }; From 690ee944e40bf680c5d04fcc5f32edddb48ff571 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 13:45:38 +0000 Subject: [PATCH 14/35] fix(acp-registry): fix post-probe overflow, multi-model clear retention, and cache-hit races --- .../AcpRegistryRuntimeCoordinator.test.ts | 133 +++++- .../server/AcpRegistryRuntimeCoordinator.ts | 81 +++- .../src/server/driver.test.ts | 431 +++++++++++++++++- .../src/server/driver.ts | 212 +++++++-- .../provider-acp-registry/src/server/probe.ts | 80 +++- 5 files changed, 832 insertions(+), 105 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 4bb1528da7bc5..2bcf185e1c11f 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -464,7 +464,6 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v1")); const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); - const second = yield* coordinator.getLiveConfigurationWithRevision(instanceId); // Outdated catalogRevision cannot clear a newer catalog or advance clearedThroughRevision. expect( @@ -476,43 +475,125 @@ describe("AcpRegistryRuntimeCoordinator", () => { (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, ).toBe(0); - // Catalog-scoped clear reconciles newer in-flight options-only updates through retain, - // clears the stored catalog, and advances clearedThroughRevision past them. - const optionsOnlyConfig = { + // Catalog-scoped clear reconciles catalog options plus newer per-model options-only + // updates in revision order, stripping catalog models before passing to retain. + const modeOption = (currentValue: "ask" | "code") => ({ + id: "mode", + label: "Mode", + type: "select" as const, + currentValue, + options: [ + { id: "ask", label: "Ask" }, + { id: "code", label: "Code" }, + ], + }); + const variantOption = { + id: "variant", + label: "Variant", + type: "select" as const, + currentValue: "v1", + options: [{ id: "v1", label: "V1" }], + }; + const multiCatalog = { + models: [ + { id: "model-v1", name: "model-v1", description: null }, + { id: "model-v2", name: "model-v2", description: null }, + { id: "model-v3", name: "model-v3", description: null }, + ], + currentModelId: "model-v3", + configOptions: [modeOption("code"), effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }; + yield* coordinator.publishLiveConfiguration(instanceId, multiCatalog); + const third = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + const modelV1Options = { + models: [], + currentModelId: "model-v1", + configOptions: [modeOption("code"), variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }; + yield* coordinator.publishLiveConfiguration(instanceId, modelV1Options); + const v1Snap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + const modelV2Options = { models: [], currentModelId: "model-v2", - configOptions: [effortOption("high")], + configOptions: [modeOption("ask"), effortOption("high")], modelOptionIds: ["effort"], modelsFromModelSelect: false, }; - yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyConfig); + yield* coordinator.publishLiveConfiguration(instanceId, modelV2Options); const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - const retainedConfig = { - ...optionsOnlyConfig, - configOptions: [effortOption("low")], - }; + + const seenRetainInputs: Array = []; expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: second.catalogRevision, - retain: (live) => - Option.some({ - ...live, - configOptions: [effortOption("low")], - }), + catalogRevision: third.catalogRevision, + retain: (live) => { + seenRetainInputs.push([ + live.currentModelId, + live.models.length, + live.modelsFromModelSelect === true, + ]); + if (live.currentModelId === "model-v2") { + return Option.some({ + ...live, + configOptions: [modeOption("ask"), effortOption("low")], + partialOptions: true, + }); + } + return Option.some({ ...live, partialOptions: true }); + }, }), ).toBe(true); + // Every candidate passed to retain has catalog models and provenance stripped. + expect(seenRetainInputs).toEqual([ + ["model-v3", 0, false], + ["model-v1", 0, false], + ["model-v2", 0, false], + ]); + const retainedV3 = { + models: [], + currentModelId: "model-v3", + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + }; + const retainedV1 = { + models: [], + currentModelId: "model-v1", + configOptions: [variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + }; + const retainedV2 = { + ...modelV2Options, + configOptions: [modeOption("ask"), effortOption("low")], + partialOptions: true, + }; expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, catalog: Option.none(), - configuration: Option.some(retainedConfig), - pendingOptions: [{ configuration: retainedConfig, revision: optionsSnap.revision }], + configuration: Option.some(retainedV2), + pendingOptions: [ + { configuration: retainedV3, revision: third.revision }, + { configuration: retainedV1, revision: v1Snap.revision }, + { configuration: retainedV2, revision: optionsSnap.revision }, + ], clearedThroughRevision: optionsSnap.revision, }); // Omitting retain wipes both catalog and options while keeping clearedThroughRevision. expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: second.catalogRevision, + catalogRevision: third.catalogRevision, }), ).toBe(true); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ @@ -522,6 +603,20 @@ describe("AcpRegistryRuntimeCoordinator", () => { pendingOptions: [], clearedThroughRevision: optionsSnap.revision, }); + + // Per-model pending options are bounded at 256 models, evicting the oldest entry first. + for (let index = 0; index < 257; index += 1) { + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: `m${index}`, + configOptions: [], + modelsFromModelSelect: false, + }); + } + const bounded = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(bounded.pendingOptions).toHaveLength(256); + expect(bounded.pendingOptions[0]?.configuration.currentModelId).toBe("m1"); + expect(bounded.pendingOptions.at(-1)?.configuration.currentModelId).toBe("m256"); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 68d44af45119d..541c1586b8e0a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -321,27 +321,68 @@ const make = Effect.gen(function* () { // Every revision through current.revision is either cleared or reconciled by retain. const nextCleared = Math.max(current.clearedThroughRevision, current.revision); const retain = options.retain; - const nextConfiguration: Option.Option = - retain === undefined - ? Option.none() - : Option.flatMap(current.configuration, (configuration) => - retain({ - ...configuration, - models: [], - modelsFromModelSelect: false, - }), - ); const nextOptionsByModel: ReadonlyMap< string | null, AcpRegistryRevisionedLiveConfiguration - > = Option.isSome(nextConfiguration) - ? new Map([ - [ - nextConfiguration.value.currentModelId, - { configuration: nextConfiguration.value, revision: current.revision }, - ], - ]) - : EMPTY_OPTIONS_BY_MODEL; + > = (() => { + if (retain === undefined) return EMPTY_OPTIONS_BY_MODEL; + const candidates = new Map(); + if (current.catalog !== null) { + candidates.set(current.catalog.configuration.currentModelId, { + configuration: { + ...current.catalog.configuration, + models: [], + modelsFromModelSelect: false, + }, + revision: current.catalog.revision, + }); + } + for (const [key, entry] of current.optionsByModel) { + candidates.set(key, entry); + } + const retained = new Map(); + for (const entry of sortedPendingOptions(candidates)) { + const kept = retain({ + ...entry.configuration, + models: [], + modelsFromModelSelect: false, + }); + if (Option.isNone(kept)) continue; + if (entry.revision < current.revision) { + // Earlier models keep only model-specific options without stealing default selection or shared options. + const modelOptionIds = new Set(kept.value.modelOptionIds ?? []); + const modelOnlyOptions = kept.value.configOptions.filter((descriptor) => + modelOptionIds.has(descriptor.id), + ); + if (modelOnlyOptions.length === 0) continue; + const { + cappedLastModel: _droppedOverflow, + cappedPrefixKey: _droppedPrefix, + ...rest + } = kept.value; + retained.delete(kept.value.currentModelId); + retained.set(kept.value.currentModelId, { + configuration: { + ...rest, + configOptions: modelOnlyOptions, + modelOptionIds: modelOnlyOptions.map((descriptor) => descriptor.id), + preserveDefault: true, + }, + revision: entry.revision, + }); + continue; + } + retained.delete(kept.value.currentModelId); + retained.set(kept.value.currentModelId, { + configuration: kept.value, + revision: entry.revision, + }); + } + return retained.size === 0 ? EMPTY_OPTIONS_BY_MODEL : retained; + })(); + const lastRetained = sortedPendingOptions(nextOptionsByModel).at(-1); + const nextConfiguration: Option.Option = + lastRetained === undefined ? Option.none() : Option.some(lastRetained.configuration); if ( current.catalog === null && Equal.equals(current.configuration, nextConfiguration) && @@ -378,8 +419,8 @@ const make = Effect.gen(function* () { const catalogRevision = hasCatalog ? current.catalogRevision + 1 : current.catalogRevision; - // Store the active catalog and per-model options separately so an unrelated - // session's options update never discards the catalog or drops earlier models' options. + // Keep the active catalog and per-model options separate; a new catalog replaces + // prior per-model options while options-only updates preserve earlier models' entries. const catalog = hasCatalog ? { configuration, revision } : current.catalog; const optionsByModel = hasCatalog ? EMPTY_OPTIONS_BY_MODEL diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index a8ada607676e2..e7655da5e4d7e 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1633,7 +1633,8 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(preparedM256.catalogKey).toBe(keyM0); const overflowOptionsOnly = preparedM256.toLiveConfiguration({ includeCatalog: false }); expect(overflowOptionsOnly.models).toEqual([]); - expect(overflowOptionsOnly.currentModel).toEqual({ + expect(overflowOptionsOnly.cappedPrefixKey).toBeDefined(); + expect(overflowOptionsOnly.cappedLastModel).toEqual({ id: "m256", name: "Model 256", description: null, @@ -1654,7 +1655,18 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(withOverflowSelected.models).toHaveLength(256); expect(withOverflowSelected.models.at(-1)?.slug).toBe("m256"); expect(withOverflowSelected.models.at(-1)?.isDefault).toBe(true); - // Switching back to m255 restores m255 into the last slot without re-sending the catalog. + // Returning to the stable prefix (m0 or m1) restores m255 into the last slot without re-sending the catalog. + const withM0Restored = applyAcpRegistryLiveConfiguration( + withOverflowSelected, + prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + [], + ); + expect(withM0Restored.models).toHaveLength(256); + expect(withM0Restored.models.at(-1)?.slug).toBe("m255"); + expect(withM0Restored.models[0]?.isDefault).toBe(true); + // Switching back to m255 from m256 also restores m255 and marks it default. const withM255Restored = applyAcpRegistryLiveConfiguration( withOverflowSelected, prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ @@ -1665,6 +1677,22 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(withM255Restored.models).toHaveLength(256); expect(withM255Restored.models.at(-1)?.slug).toBe("m255"); expect(withM255Restored.models.at(-1)?.isDefault).toBe(true); + // A different 256-model catalog (mismatched prefix) must never absorb another session's overflow model. + const foreign256Provider = providerWithModels( + Array.from({ length: 256 }, (_, index) => ({ + id: `other-${index}`, + name: `Other ${index}`, + description: null, + })), + "other-0", + ); + const afterForeignOverflow = applyAcpRegistryLiveConfiguration( + foreign256Provider, + overflowOptionsOnly, + [], + ); + expect(afterForeignOverflow.models.at(-1)?.slug).toBe("other-255"); + expect(afterForeignOverflow.models[0]?.isDefault).toBe(true); // A smaller catalog must never absorb an overflow model from another session. const smallProvider = providerWithModels( [ @@ -4200,4 +4228,403 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual([["effort", "high"]]); }), ); + + it.effect( + "preserves post-probe overflow selection, per-model learned values, and multi-model clear retention", + () => + Effect.gen(function* () { + const modelIds = Array.from({ length: 257 }, (_, index) => `m${index}`); + const choices = modelIds.map((value, index) => ({ value, name: `Model ${index}` })); + const modelSelect = (currentValue: string) => [ + { + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: choices, + }, + ]; + const effortSelect = (currentValue: "low" | "high" | "removed") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }); + const variantSelect = { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v1", + options: [{ value: "v1", name: "V1" }], + }; + + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-overflow-post-probe-", + initialModels: { + models: modelIds, + configOptions: [...modelSelect("m0"), effortSelect("low")], + }, + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish initial live catalog for m0, then supersede with a fresh 257-model probe. + const initialLive = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("low"), + ]).toLiveConfiguration({ includeCatalog: true }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, initialLive); + yield* writeModels({ + models: modelIds, + configOptions: [...modelSelect("m0"), effortSelect("low")], + }); + yield* TestClock.adjust("16 minutes"); + const superseded = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(superseded); + + // Selecting overflow model m256 after a superseding probe must swap slot 255 and mark m256 default. + const sawM256 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.at(-1)?.slug === "m256" && snapshot.models.at(-1)?.isDefault === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256"), + variantSelect, + ]).toLiveConfiguration({ includeCatalog: false }), + ); + const afterM256 = Option.getOrThrow(yield* Fiber.join(sawM256)); + expect(afterM256.models).toHaveLength(256); + expect( + afterM256.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + + // Refresh must keep m256 selected in slot 255. + const refreshM256 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const refreshedM256 = Option.getOrThrow(yield* Fiber.join(refreshM256)); + expect(refreshedM256.models.at(-1)?.slug).toBe("m256"); + expect(refreshedM256.models.at(-1)?.isDefault).toBe(true); + + // Returning to m0 with effort=high restores m255 in slot 255 and learns m0 effort=high. + const sawM0High = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models[0]?.isDefault === true && + snapshot.models.at(-1)?.slug === "m255" && + snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("high"), + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM0High); + + // Switching to m1 must keep m0's learned effort=high instead of reverting m0 to probe default low. + const sawM1 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[1]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(modelSelect("m1")).toLiveConfiguration({ + includeCatalog: false, + }), + ); + const afterM1 = Option.getOrThrow(yield* Fiber.join(sawM1)); + expect( + afterM1.models[0]?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + + // Sending an invalid value for probe's default model m0 resets m0 back to probe default low. + const sawM0Reset = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models[0]?.isDefault === true && + snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("removed"), + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM0Reset); + }), + ); + + it.effect( + "retains all models' pending options across probe clear and keeps cache-hit commits consistent with concurrent live updates", + () => + Effect.gen(function* () { + const probeStarted = yield* Deferred.make(); + const releaseProbe = yield* Deferred.make(); + const watcherBlocked = yield* Deferred.make(); + const releaseWatcher = yield* Deferred.make(); + const cacheHitRead = yield* Deferred.make(); + const releaseCacheHit = yield* Deferred.make(); + let gateProbe = false; + let blockWatcher = false; + let gateAfterCacheRead = false; + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-multi-clear-", + initialModels: ["model-a", "model-b"], + wrapCoordinator: (base) => ({ + ...base, + runBackgroundProbe: (agentId, effect) => + base.runBackgroundProbe( + agentId, + gateProbe + ? Effect.sync(() => { + gateProbe = false; + }).pipe( + Effect.andThen(Deferred.succeed(probeStarted, undefined)), + Effect.andThen(Deferred.await(releaseProbe)), + Effect.andThen(effect), + ) + : gateAfterCacheRead + ? Effect.sync(() => { + gateAfterCacheRead = false; + }).pipe( + Effect.andThen(effect), + Effect.tap(() => + Deferred.succeed(cacheHitRead, undefined).pipe( + Effect.andThen(Deferred.await(releaseCacheHit)), + ), + ), + ) + : effect, + ), + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + blockWatcher + ? Effect.sync(() => { + blockWatcher = false; + }).pipe( + Effect.andThen(Deferred.succeed(watcherBlocked, undefined)), + Effect.andThen(Deferred.await(releaseWatcher)), + Effect.andThen(onUpdate(configuration, revision)), + ) + : onUpdate(configuration, revision), + options, + ), + }), + }); + const effortOpt = (currentValue: "low" | "high") => ({ + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue, + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }); + const variantOpt = { + id: "variant", + label: "Variant", + type: "select" as const, + currentValue: "v1", + options: [{ id: "v1", label: "V1" }], + }; + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish live catalog [model-a, model-b], then start a gated superseding probe. + const sawCatalog = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "model-a") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null }, + ], + currentModelId: "model-a", + configOptions: [effortOpt("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + yield* Fiber.join(sawCatalog); + + yield* writeModels({ + models: ["model-a", "model-b"], + configOptions: [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "low", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + }); + yield* TestClock.adjust("16 minutes"); + gateProbe = true; + const probeDone = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(probeStarted); + + // Block the watcher so neither model-b nor model-a is applied before the probe clears. + blockWatcher = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [variantOpt], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }); + yield* Deferred.await(watcherBlocked); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [effortOpt("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + + // Release probe before watcher resumes: clearLiveConfigurationIfRevision must retain + // both model-b (variant=v1) and model-a (effort=high) across commit and later refreshes. + yield* Deferred.succeed(releaseProbe, undefined); + const afterProbe = Option.getOrThrow(yield* Fiber.join(probeDone)); + expect( + afterProbe.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + expect( + afterProbe.models + .find((m) => m.slug === "model-a") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + yield* Deferred.succeed(releaseWatcher, undefined); + + const afterProbeRefresh = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const refreshedAfterProbe = Option.getOrThrow(yield* Fiber.join(afterProbeRefresh)); + expect( + refreshedAfterProbe.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + expect( + refreshedAfterProbe.models + .find((m) => m.slug === "model-a") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + + // Verify a cache-hit commit (probeOptions=null) whose watcher applies effort=high after + // enrichProviderCached reads effort=low still publishes effort=high rather than reverting. + const sawFreshCatalog = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((m) => m.slug === "fresh-b")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "fresh-a", name: "Fresh A", description: null }, + { id: "fresh-b", name: "Fresh B", description: null }, + ], + currentModelId: "fresh-a", + configOptions: [effortOpt("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + yield* Fiber.join(sawFreshCatalog); + + gateAfterCacheRead = true; + const cachedCommitDone = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + // Wait until enrichProviderCached has read effort=low from enrichmentCache, before commitEnrichment runs. + yield* Deferred.await(cacheHitRead); + + const sawFreshHigh = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "fresh-a") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "fresh-a", + configOptions: [effortOpt("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawFreshHigh); + + // Release the cache-hit commit: it must publish effort=high, never reverting to effort=low. + yield* Deferred.succeed(releaseCacheHit, undefined); + const afterCachedCommit = Option.getOrThrow(yield* Fiber.join(cachedCommitDone)); + expect( + afterCachedCommit.models + .find((m) => m.slug === "fresh-a") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 0d1a7eef56061..b65e2be7671ce 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -55,6 +55,7 @@ import { type AcpRegistryConfigurationProbe, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, + cappedAcpRegistryModelPrefixKey, deleteAcpRegistrySession, disableAcpRegistryProvider, listAcpRegistrySessions, @@ -190,7 +191,11 @@ export function updateAcpRegistryEnrichmentCache(input: { configuration, customModels, undefined, - { preserveSingleModelCatalog, reasoningDisabledModelSlugs, hasDiscoveredCatalog }, + { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + }, ); if (Equal.equals(provider, cache.entry.provider)) return cache; const previousBuiltIn = cache.entry.provider.models.filter((model) => !model.isCustom); @@ -353,8 +358,20 @@ export function retainAcpRegistryLiveOptionsAfterProbe( probe: AcpRegistryProbeOptionSchema, ): Option.Option { const probedModelById = new Map(probe.models.map((model) => [model.id, model])); + const matchingCappedLastModel = + live.cappedLastModel !== undefined && + live.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey(probe.models) === live.cappedPrefixKey && + probe.models[ACP_REGISTRY_MAX_MODELS - 1]?.id !== live.cappedLastModel.id + ? live.cappedLastModel + : undefined; const currentProbedModel = - live.currentModelId === null ? undefined : probedModelById.get(live.currentModelId); + live.currentModelId === null + ? undefined + : (probedModelById.get(live.currentModelId) ?? + (matchingCappedLastModel !== undefined && matchingCappedLastModel.id === live.currentModelId + ? matchingCappedLastModel + : undefined)); const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); const liveModelOptionIds = new Set(live.modelOptionIds ?? []); @@ -405,20 +422,28 @@ export function retainAcpRegistryLiveOptionsAfterProbe( } } + const overflowFields = + matchingCappedLastModel !== undefined && live.cappedPrefixKey !== undefined + ? { cappedPrefixKey: live.cappedPrefixKey, cappedLastModel: matchingCappedLastModel } + : {}; const configOptions = [...sharedDescriptors, ...modelDescriptors]; if (configOptions.length === 0) { - // Keep the running session's model selection moving isDefault even when no - // options survive, unless it already matches the probe's default model. - if (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) { + // Keep the running session's model selection moving isDefault (or restoring the + // capped tail slot) even when no options survive, unless nothing differs from probe default. + if ( + matchingCappedLastModel === undefined && + (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) + ) { return Option.none(); } return Option.some({ models: [], - currentModelId: currentProbedModel.id, + currentModelId: currentProbedModel?.id ?? live.currentModelId, configOptions: [], modelOptionIds: [], modelsFromModelSelect: false, partialOptions: true, + ...overflowFields, }); } return Option.some({ @@ -430,6 +455,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelOptionIds: modelDescriptors.map((descriptor) => descriptor.id), modelsFromModelSelect: false, partialOptions: true, + ...overflowFields, }); } @@ -440,12 +466,14 @@ function mergeLearnedModelOptions( readonly currentModelId?: string | null; readonly skipModelSlugs?: ReadonlySet; readonly reasoningDisabledModelSlugs?: ReadonlySet; + readonly overlayLearnedValues?: boolean; }, ): ReadonlyArray { if (learned.length === 0) return models; const currentModelId = options?.currentModelId ?? null; const skipModelSlugs = options?.skipModelSlugs ?? EMPTY_SLUG_SET; const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; + const overlayLearnedValues = options?.overlayLearnedValues === true; const learnedBySlug = new Map( learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), ); @@ -463,6 +491,24 @@ function mergeLearnedModelOptions( learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; if (previousDescriptors.length === 0) return model; const currentDescriptors = model.capabilities?.optionDescriptors ?? []; + const previousById = overlayLearnedValues + ? new Map(previousDescriptors.map((descriptor) => [descriptor.id, descriptor] as const)) + : undefined; + const nextCurrentDescriptors = + previousById === undefined + ? currentDescriptors + : currentDescriptors.map((descriptor) => { + if (reasoningDisabledModelSlugs.has(model.slug) && isReasoningDescriptor(descriptor)) { + return descriptor; + } + const learnedDescriptor = previousById.get(descriptor.id); + return learnedDescriptor === undefined + ? descriptor + : Option.getOrElse( + compatibleLiveOptionValue(descriptor, learnedDescriptor), + () => descriptor, + ); + }); const currentIds = new Set(currentDescriptors.map((descriptor) => descriptor.id)); const hasExplicitReasoningState = reasoningDisabledModelSlugs.has(model.slug) || @@ -476,12 +522,14 @@ function mergeLearnedModelOptions( descriptor.type !== "select" || descriptor.role !== "reasoning"), ); - if (extra.length === 0) return model; + const combined = + extra.length === 0 ? nextCurrentDescriptors : [...nextCurrentDescriptors, ...extra]; + if (Equal.equals(currentDescriptors, combined)) return model; changed = true; return { ...model, capabilities: createModelCapabilities({ - optionDescriptors: [...currentDescriptors, ...extra], + optionDescriptors: combined, }), }; }); @@ -818,7 +866,22 @@ function overlayPartialLiveOptions( : createModelCapabilities({ optionDescriptors: nextDescriptors }), }; }); - return withAcpRegistryDefaultModel(updated, selectedProbedModelId); + return configuration.preserveDefault === true + ? updated + : withAcpRegistryDefaultModel(updated, selectedProbedModelId); +} + +function replaceLastCappedBuiltInModel( + models: ReadonlyArray, + replacement: ServerProviderModel, +): ReadonlyArray { + let builtInIndex = 0; + return models.map((model) => { + if (model.isCustom) return model; + const isTarget = builtInIndex === ACP_REGISTRY_MAX_MODELS - 1; + builtInIndex += 1; + return isTarget ? replacement : model; + }); } export function applyAcpRegistryLiveConfiguration( @@ -830,6 +893,7 @@ export function applyAcpRegistryLiveConfiguration( readonly preserveSingleModelCatalog?: boolean | undefined; readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; readonly hasDiscoveredCatalog?: boolean | undefined; + readonly probeSharedDescriptors?: ReadonlyArray | undefined; }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; @@ -849,29 +913,53 @@ export function applyAcpRegistryLiveConfiguration( const disabledReasoningSlugs: ReadonlySet = useLiveCatalog ? EMPTY_SLUG_SET : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); - const overflowCurrentModel = + const cappedLastModel = !useLiveCatalog && - configuration.currentModel !== undefined && - probedModels.length >= ACP_REGISTRY_MAX_MODELS && - !probedModels.some((model) => model.slug === configuration.currentModel!.id) - ? configuration.currentModel + configuration.cappedLastModel !== undefined && + configuration.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey( + probedModels.map((model) => ({ id: model.slug, name: model.name })), + ) === configuration.cappedPrefixKey + ? configuration.cappedLastModel : undefined; + const replaceLastSlot = + cappedLastModel !== undefined && + probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug !== cappedLastModel.id; const liveCurrentModelInProbed = - overflowCurrentModel !== undefined || + (cappedLastModel !== undefined && configuration.currentModelId === cappedLastModel.id) || (configuration.currentModelId !== null && probedModels.some((model) => model.slug === configuration.currentModelId)); const selectedProbedModelId = liveCurrentModelInProbed ? configuration.currentModelId : (probedModels.find((model) => model.isDefault)?.slug ?? null); if (!useLiveCatalog && configuration.partialOptions === true) { + const modelsForOverlay = + replaceLastSlot && cappedLastModel !== undefined + ? replaceLastCappedBuiltInModel( + provider.models, + modelsFromDiscovery( + { + models: [cappedLastModel], + currentModelId: null, + configOptions: options?.probeSharedDescriptors ?? [], + }, + [], + previousModels.filter((model) => !model.isCustom), + )[0]!, + ) + : provider.models; + const partialDisabledReasoning = + cappedLastModel?.reasoningEffort === null + ? new Set([...disabledReasoningSlugs, cappedLastModel.id]) + : disabledReasoningSlugs; return { ...snapshot, status: provider.enabled ? "ready" : provider.status, models: overlayPartialLiveOptions( - provider.models, + modelsForOverlay, configuration, selectedProbedModelId, - disabledReasoningSlugs, + partialDisabledReasoning, ), }; } @@ -915,8 +1003,8 @@ export function applyAcpRegistryLiveConfiguration( ...(advertised === undefined ? {} : { reasoningEffort: advertised }), }; }); - if (overflowCurrentModel !== undefined) { - retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = overflowCurrentModel; + if (replaceLastSlot && cappedLastModel !== undefined) { + retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = cappedLastModel; } const discovery = useLiveCatalog ? configuration @@ -932,7 +1020,7 @@ export function applyAcpRegistryLiveConfiguration( !useLiveCatalog && effectiveConfigOptions.length === 0 && !hasAdvertisedReasoning && - overflowCurrentModel === undefined + !replaceLastSlot ? stripReasoningForDisabledModels( withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), disabledReasoningSlugs, @@ -1319,6 +1407,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; readonly hasDiscoveredCatalog?: boolean | undefined; readonly replaceCurrentLearnedOptions?: boolean | undefined; + readonly probeSharedDescriptors?: ReadonlyArray | undefined; }, ) => Ref.get(acceptedCatalog).pipe( @@ -1332,12 +1421,23 @@ export const AcpRegistryDriver: ProviderDriver 0 ? EMPTY_SLUG_SET : reasoningDisabledModelSlugs; return Ref.modify(learnedModels, (learned) => { + const basePrevious = learned.length > 0 ? learned : provider.models; + const previousModels = + options?.replaceCurrentLearnedOptions === true && + configuration.currentModelId !== null + ? basePrevious.filter((model) => model.slug !== configuration.currentModelId) + : basePrevious; const next = applyAcpRegistryLiveConfiguration( provider, configuration, effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - { preserveSingleModelCatalog, reasoningDisabledModelSlugs, hasDiscoveredCatalog }, + previousModels, + { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + probeSharedDescriptors: options?.probeSharedDescriptors, + }, ); return [ next, @@ -1397,30 +1497,33 @@ export const AcpRegistryDriver: ProviderDriver model.id === configuration.currentModelId) + (probeOptions.models.some((model) => model.id === configuration.currentModelId) || + (configuration.cappedLastModel !== undefined && + configuration.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey(probeOptions.models) === + configuration.cappedPrefixKey && + configuration.currentModelId === configuration.cappedLastModel.id)) ? configuration.currentModelId : null; - const skipModelSlugs = new Set(); - if (probeOptions.currentModelId !== null) { - skipModelSlugs.add(probeOptions.currentModelId); - } - if (replacedLiveModelId !== null) { - skipModelSlugs.add(replacedLiveModelId); - } - // Rebuild from the pure probe baseline so rejected values restore probe - // defaults and options a live model stops reporting are removed. + const skipModelSlugs = + replacedLiveModelId === null ? EMPTY_SLUG_SET : new Set([replacedLiveModelId]); + // Rebuild from the pure probe baseline so rejected values restore probe defaults, + // other models preserve learned values, and dropped options on the reporting model clear. const pureBaseline = acceptedBefore.probeBaselineModels ?? acceptedBefore.models; const baselineModels = yield* Ref.get(learnedModels).pipe( Effect.map((learned) => mergeLearnedModelOptions(pureBaseline, learned, { skipModelSlugs, reasoningDisabledModelSlugs, + overlayLearnedValues: true, }), ), ); const baselineProvider = pureBaseline.length > 0 ? { ...current, models: baselineModels } : current; + const probeSharedDescriptors = probeOptions.configOptions.filter( + (descriptor) => !isModelSpecificDescriptor(descriptor, probeOptions.modelOptionIds), + ); const applied = yield* Option.match(effectiveConfiguration, { onNone: () => replacedLiveModelId === null @@ -1433,7 +1536,7 @@ export const AcpRegistryDriver: ProviderDriver 0; if (accepted.probeOptions !== null && !hasNewCatalogStep) { for (const entry of liveConfiguration.pendingOptions) { - steps.push(entry); + if (entry.revision > appliedRev) { + steps.push(entry); + } + } + const latestPending = liveConfiguration.pendingOptions.at(-1); + if (latestPending !== undefined && steps.at(-1) !== latestPending) { + steps.push(latestPending); } } else { for (const entry of liveConfiguration.pendingOptions) { @@ -1599,8 +1709,8 @@ export const AcpRegistryDriver: ProviderDriver 0 && + current.entry.provider.enabled && + current.entry.provider.installed + ? { models: accepted.models } + : {}), + }; + } if (fresh && provider.status === "ready") { const accepted = yield* Ref.get(acceptedCatalog); const liveCatalog = Option.filter( @@ -1815,18 +1939,19 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshot.revision || accepted.probeOptions !== null; - yield* Ref.set(lastAppliedLiveCatalogRevision, 0); - yield* Ref.set(lastAppliedLiveRevision, afterClear.clearedThroughRevision); + yield* resetAppliedLiveRevisions; yield* Ref.set(acceptedCatalog, { models: resolved.models, builtInModelCount: probedModelCount, @@ -1848,6 +1973,11 @@ export const AcpRegistryDriver: ProviderDriver 0 : undefined, }); + if (cleared) { + yield* Ref.update(lastAppliedLiveRevision, (prev) => + Math.max(prev, clearedThroughRevision), + ); + } const completedAt = yield* Clock.currentTimeMillis; yield* Ref.set(enrichmentCache, { ...current, @@ -1931,10 +2061,12 @@ export const AcpRegistryDriver: ProviderDriver(); const models: Array = []; for (const candidate of candidates) { - if (models.length === MAX_MODELS) break; + if (models.length === ACP_REGISTRY_MAX_MODELS) break; const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH); if (id === undefined || seen.has(id)) continue; seen.add(id); models.push(normalizedModel(id, candidate)); } // Keep the running model visible even when its advertised position exceeds the cap. - if (currentModelId !== null && models.length === MAX_MODELS && !seen.has(currentModelId)) { + if ( + currentModelId !== null && + models.length === ACP_REGISTRY_MAX_MODELS && + !seen.has(currentModelId) + ) { const current = candidates.find((candidate) => candidate.id === currentModelId); if (current !== undefined) { - models[MAX_MODELS - 1] = normalizedModel(currentModelId, current); + models[ACP_REGISTRY_MAX_MODELS - 1] = normalizedModel(currentModelId, current); } } return models; @@ -216,13 +219,27 @@ export interface AcpRegistryLiveConfiguration { readonly modelsFromModelSelect?: boolean; // Set on retained post-probe overrides so probe-only options stay untouched. readonly partialOptions?: boolean; + // Set on earlier-model retained overrides so they update model-specific options without stealing isDefault. + readonly preserveDefault?: boolean; // Non-current per-model reasoning descriptors normalized from `_meta` when an // effort selector appears mid-session without re-advertising the frozen model list. readonly advertisedReasoning?: Readonly< Record> >; - // Selected model beyond MAX_MODELS, carried without re-advertising the capped catalog. - readonly currentModel?: AcpRegistryProbeModel; + // Stable prefix key (first ACP_REGISTRY_MAX_MODELS - 1 models) for capped overflow updates. + readonly cappedPrefixKey?: string; + // Last visible model slot when candidates exceed ACP_REGISTRY_MAX_MODELS, carrying either + // an overflow selection or the restored tail model when returning to the stable prefix. + readonly cappedLastModel?: AcpRegistryProbeModel; +} + +export function cappedAcpRegistryModelPrefixKey( + models: ReadonlyArray<{ readonly id: string; readonly name: string }>, +): string | undefined { + if (models.length < ACP_REGISTRY_MAX_MODELS) return undefined; + return JSON.stringify( + models.slice(0, ACP_REGISTRY_MAX_MODELS - 1).map(({ id, name }) => [id, name]), + ); } export interface PreparedAcpRegistryLiveConfiguration { @@ -285,16 +302,23 @@ export function prepareAcpRegistryLiveConfiguration( boundedCurrentModelId === null ? undefined : advertisedModels.find((model) => model.id === boundedCurrentModelId); - const currentInStablePrefix = - boundedCurrentModelId !== null && - baseModels.slice(0, MAX_MODELS - 1).some((model) => model.id === boundedCurrentModelId); - const overflowCurrentModel = - currentModel !== undefined && - baseModels.length === MAX_MODELS && - candidates.length > MAX_MODELS && - !currentInStablePrefix - ? currentModel - : undefined; + let hasOverflowCandidates = false; + if ( + baseModels.length === ACP_REGISTRY_MAX_MODELS && + candidates.length > ACP_REGISTRY_MAX_MODELS + ) { + const baseIds = new Set(baseModels.map((model) => model.id)); + for (const candidate of candidates) { + const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH); + if (id !== undefined && !baseIds.has(id)) { + hasOverflowCandidates = true; + break; + } + } + } + const cappedLastModel = hasOverflowCandidates + ? advertisedModels[ACP_REGISTRY_MAX_MODELS - 1] + : undefined; const stripCurrentReasoning = currentModel?.reasoningEffort === null; const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( (descriptor) => @@ -322,13 +346,16 @@ export function prepareAcpRegistryLiveConfiguration( advertisedReasoningEntries.length > 0 ? Object.fromEntries(advertisedReasoningEntries) : undefined; + const catalogKey = JSON.stringify([ + hasModelSelect, + baseModels.map(({ id, name, description }) => [id, name, description]), + ]); + const cappedPrefixKey = + cappedLastModel === undefined ? undefined : cappedAcpRegistryModelPrefixKey(baseModels); return { // Key on the uncapped-selection catalog identity and provenance so neither effort - // toggles nor selecting a model beyond MAX_MODELS re-advertise a frozen list. - catalogKey: JSON.stringify([ - hasModelSelect, - baseModels.map(({ id, name, description }) => [id, name, description]), - ]), + // toggles nor selecting a model beyond ACP_REGISTRY_MAX_MODELS re-advertise a frozen list. + catalogKey, toLiveConfiguration: (options) => { const includeCatalog = options?.includeCatalog !== false; return { @@ -338,8 +365,8 @@ export function prepareAcpRegistryLiveConfiguration( modelOptionIds, modelsFromModelSelect: includeCatalog && hasModelSelect, ...(!includeCatalog && advertisedReasoning !== undefined ? { advertisedReasoning } : {}), - ...(!includeCatalog && overflowCurrentModel !== undefined - ? { currentModel: overflowCurrentModel } + ...(!includeCatalog && cappedLastModel !== undefined && cappedPrefixKey !== undefined + ? { cappedPrefixKey, cappedLastModel } : {}), }; }, @@ -439,7 +466,12 @@ export function acpRegistryProbeResult( canDelete: started.initializeResult.agentCapabilities?.sessionCapabilities?.delete != null, canConfigureProviders: started.initializeResult.agentCapabilities?.providers != null, }, - ...configuration, + models: configuration.models, + currentModelId: configuration.currentModelId, + configOptions: configuration.configOptions, + ...(configuration.modelOptionIds === undefined + ? {} + : { modelOptionIds: configuration.modelOptionIds }), }); } From 8eb439db3cf4c2fe2c5c43042a6526d8ff784b77 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 14:25:52 +0000 Subject: [PATCH 15/35] fix(acp-registry): harden fallback catalog gating, post-probe reasoning, and capped overflow --- .../Adapters/AcpRegistryAdapterV2.test.ts | 2 +- .../AcpRegistryRuntimeCoordinator.test.ts | 45 +- .../server/AcpRegistryRuntimeCoordinator.ts | 14 +- .../src/server/adapter.ts | 12 +- .../src/server/driver.test.ts | 646 +++++++++++++----- .../src/server/driver.ts | 217 +++--- .../provider-acp-registry/src/server/probe.ts | 35 +- 7 files changed, 684 insertions(+), 287 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 246dc7b5e71c5..1adc3c87dae86 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1017,7 +1017,7 @@ describe("AcpRegistryAdapterV2", () => { { models: [], current: null }, { models: ["default"], current: null }, { models: [], current: null }, - { models: ["hermes", "auto", "default"], current: "default" }, + { models: [], current: "default" }, { models: [], current: "hermes" }, ], ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 2bcf185e1c11f..7d7b3f91b8499 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -604,12 +604,22 @@ describe("AcpRegistryRuntimeCoordinator", () => { clearedThroughRevision: optionsSnap.revision, }); - // Per-model pending options are bounded at 256 models, evicting the oldest entry first. + // Per-model pending options are bounded at 256 models, evicting the oldest entry first + // even when clearLiveConfigurationIfRevision also includes catalog options. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [{ id: "catalog-model", name: "catalog-model", description: null }], + currentModelId: "catalog-model", + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + const catalogForCap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); for (let index = 0; index < 257; index += 1) { yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: `m${index}`, - configOptions: [], + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], modelsFromModelSelect: false, }); } @@ -617,6 +627,37 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect(bounded.pendingOptions).toHaveLength(256); expect(bounded.pendingOptions[0]?.configuration.currentModelId).toBe("m1"); expect(bounded.pendingOptions.at(-1)?.configuration.currentModelId).toBe("m256"); + + // Clear retention caps pendingOptions at 256 even when catalog options plus 256 + // per-model updates are all retained (evicting the oldest entry, catalog-model). + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: catalogForCap.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const clearedCap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(clearedCap.pendingOptions).toHaveLength(256); + expect(clearedCap.pendingOptions[0]?.configuration.currentModelId).toBe("m1"); + expect(clearedCap.pendingOptions.at(-1)?.configuration.currentModelId).toBe("m256"); + + // When retain drops the newest update (m256) while earlier models survive with + // preserveDefault, getLiveConfiguration returns none so Copilot does not read an + // earlier model's effort. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: catalogForCap.catalogRevision, + retain: (live) => + live.currentModelId === "m256" + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const clearedEarlierOnly = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(clearedEarlierOnly.configuration).toEqual(Option.none()); + expect(clearedEarlierOnly.pendingOptions).toHaveLength(255); + expect(clearedEarlierOnly.pendingOptions.at(-1)?.configuration.currentModelId).toBe("m255"); + expect(clearedEarlierOnly.pendingOptions.at(-1)?.configuration.preserveDefault).toBe(true); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 541c1586b8e0a..5b9fa9b7332da 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -378,11 +378,18 @@ const make = Effect.gen(function* () { revision: entry.revision, }); } + while (retained.size > MAX_TRACKED_MODEL_OPTIONS) { + const oldestKey = retained.keys().next().value; + if (oldestKey === undefined) break; + retained.delete(oldestKey); + } return retained.size === 0 ? EMPTY_OPTIONS_BY_MODEL : retained; })(); const lastRetained = sortedPendingOptions(nextOptionsByModel).at(-1); const nextConfiguration: Option.Option = - lastRetained === undefined ? Option.none() : Option.some(lastRetained.configuration); + lastRetained === undefined || lastRetained.configuration.preserveDefault === true + ? Option.none() + : Option.some(lastRetained.configuration); if ( current.catalog === null && Equal.equals(current.configuration, nextConfiguration) && @@ -428,9 +435,10 @@ const make = Effect.gen(function* () { const updated = new Map(current.optionsByModel); updated.delete(configuration.currentModelId); updated.set(configuration.currentModelId, { configuration, revision }); - if (updated.size > MAX_TRACKED_MODEL_OPTIONS) { + while (updated.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = updated.keys().next().value; - if (oldestKey !== undefined) updated.delete(oldestKey); + if (oldestKey === undefined) break; + updated.delete(oldestKey); } return updated; })(); diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 71c5bd42bfac6..55ea49ae001ac 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -380,14 +380,18 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu modeState, modelState, ); + const lastCatalogKey = updateOptions?.lastCatalogKey ?? null; + // Only publish a replacement catalog on the first setup update or when an explicit + // model selector changes; losing a selector must not republish frozen setup fallback models. + const includeCatalog = + lastCatalogKey === null || + (prepared.hasModelSelect && lastCatalogKey !== prepared.catalogKey); return runtimeCoordinator .publishLiveConfiguration( options.instanceId, - prepared.toLiveConfiguration({ - includeCatalog: updateOptions?.lastCatalogKey !== prepared.catalogKey, - }), + prepared.toLiveConfiguration({ includeCatalog }), ) - .pipe(Effect.as(prepared.catalogKey)); + .pipe(Effect.as(includeCatalog ? prepared.catalogKey : lastCatalogKey)); }, onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index e7655da5e4d7e..63976652126b9 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1267,6 +1267,7 @@ describe("acpRegistryEnrichmentCache", () => { liveModelsFromModelSelect: true, }), ).toBe(false); + // When neither source advertises models, an empty probe keeps live options on synthetic default. expect( acpRegistryProbeSupersedesLiveCatalog({ probedModelCount: 0, @@ -1274,6 +1275,14 @@ describe("acpRegistryEnrichmentCache", () => { liveModelCount: 0, liveModelsFromModelSelect: false, }), + ).toBe(false); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 0, + liveModelsFromModelSelect: false, + }), ).toBe(true); }); it("retains only compatible live overrides across superseding probes without storing probe defaults or stripping default-model options", () => { @@ -1569,6 +1578,25 @@ describe("acpRegistryEnrichmentCache", () => { ), ).toEqual(selectionOnly); + // Never promotes a live shared option into a probe model-specific option on the probe's current model. + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [fast(true)], + modelOptionIds: [], + modelsFromModelSelect: false, + }, + { + models: [{ id: "old-model", name: "old-model", description: null }], + currentModelId: "old-model", + configOptions: [fast(false)], + modelOptionIds: new Set(["fast"]), + }, + ), + ).toEqual(Option.none()); + // Off-current reasoning retention requires matching native option IDs (thinking != effort). expect( retainAcpRegistryLiveOptionsAfterProbe( @@ -1677,6 +1705,72 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(withM255Restored.models).toHaveLength(256); expect(withM255Restored.models.at(-1)?.slug).toBe("m255"); expect(withM255Restored.models.at(-1)?.isDefault).toBe(true); + // Removing the last overflow choice (257 -> 256 choices, m0 selected) still restores m255. + const afterOverflowRemoved = applyAcpRegistryLiveConfiguration( + withOverflowSelected, + prepareAcpRegistryLiveConfiguration( + modelSelect("m0", choices.slice(0, 256)), + ).toLiveConfiguration({ includeCatalog: false }), + [], + ); + expect(afterOverflowRemoved.models).toHaveLength(256); + expect(afterOverflowRemoved.models.at(-1)?.slug).toBe("m255"); + expect(afterOverflowRemoved.models[0]?.isDefault).toBe(true); + // A custom display-name override on m0 must not block matching overflow updates. + const renamedCappedProvider = { + ...cappedProvider, + models: cappedProvider.models.map((model, index) => + index === 0 ? { ...model, name: "Custom M0" } : model, + ), + }; + const withRenamedOverflow = applyAcpRegistryLiveConfiguration( + renamedCappedProvider, + overflowOptionsOnly, + [], + ); + expect(withRenamedOverflow.models.at(-1)?.slug).toBe("m256"); + expect(withRenamedOverflow.models.at(-1)?.isDefault).toBe(true); + // A shared-prefix probe advertising a different authoritative tail (new-m255) must not + // be overwritten by a stale options-only update selecting m0. + const conflictingTailProvider = providerWithModels( + [ + ...choices.slice(0, 255).map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + { id: "new-m255", name: "New Model 255", description: null }, + ], + "m0", + ); + const afterConflictingTail = applyAcpRegistryLiveConfiguration( + conflictingTailProvider, + prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + [], + ); + expect(afterConflictingTail.models.at(-1)?.slug).toBe("new-m255"); + expect(afterConflictingTail.models[0]?.isDefault).toBe(true); + // When live currentModelId is null and the probe started on m256, keep m256 as default. + const probeOnM256 = providerWithModels( + [ + ...choices.slice(0, 255).map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + { id: "m256", name: "Model 256", description: null }, + ], + "m256", + ); + const liveNullCurrent = prepareAcpRegistryLiveConfiguration([], undefined, { + availableModels: choices.map((choice) => ({ modelId: choice.value, name: choice.name })), + } as never).toLiveConfiguration({ includeCatalog: false }); + expect(liveNullCurrent.cappedLastModel).toBeUndefined(); + const afterNullCurrent = applyAcpRegistryLiveConfiguration(probeOnM256, liveNullCurrent, []); + expect(afterNullCurrent.models.at(-1)?.slug).toBe("m256"); + expect(afterNullCurrent.models.at(-1)?.isDefault).toBe(true); // A different 256-model catalog (mismatched prefix) must never absorb another session's overflow model. const foreign256Provider = providerWithModels( Array.from({ length: 256 }, (_, index) => ({ @@ -1851,19 +1945,23 @@ createInterface({ input: process.stdin }).on("line", (line) => { id, result: { sessionId: "probe-session", - models: { - currentModelId: payload.provisional, - availableModels: [{ modelId: payload.provisional, name: payload.provisional }], - }, + ...(payload.provisional.length === 0 + ? {} + : { + models: { + currentModelId: payload.provisional, + availableModels: [{ modelId: payload.provisional, name: payload.provisional }], + }, + }), configOptions: [ { id: "model", name: "Model", category: "model", type: "select", - currentValue: payload.provisional, + currentValue: payload.provisional || "transient-a", options: [ - { value: payload.provisional, name: payload.provisional }, + { value: payload.provisional || "transient-a", name: payload.provisional || "transient-a" }, { value: "transient-placeholder", name: "transient-placeholder" }, ], }, @@ -2057,7 +2155,10 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = category: "other", type: "select", currentValue: "on", - options: [{ value: "on", name: "On" }], + options: [ + { value: "on", name: "On" }, + { value: "off", name: "Off" }, + ], }, ], }), @@ -2071,11 +2172,33 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = expect(Option.isSome(yield* Fiber.join(refreshed))).toBe(true); // A still-running session sending an options-only update after invalidateCaches must still - // reconcile against the replacement probe's schema (keeping fast and dropping legacy). + // reconcile against the replacement probe's schema (applying fast=off and dropping legacy). + const sawFastOff = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "fast") + ?.currentValue === "off", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); yield* coordinator.publishLiveConfiguration( identity.instanceId, prepareAcpRegistryLiveConfiguration( [ + { + id: "fast", + name: "Fast", + category: "other", + type: "select", + currentValue: "off", + options: [ + { value: "on", name: "On" }, + { value: "off", name: "Off" }, + ], + }, { id: "legacy", name: "Legacy", @@ -2095,20 +2218,13 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }, ).toLiveConfiguration({ includeCatalog: false }), ); - // Force a cached refresh so the semaphore-serialized watcher has finished before reading. - const synced = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - const afterOptions = Option.getOrThrow(yield* Fiber.join(synced)); + const afterOptions = Option.getOrThrow(yield* Fiber.join(sawFastOff)); expect(afterOptions.models.map((model) => model.slug)).toEqual(["old-model", "new-model"]); expect( afterOptions.models .find((model) => model.slug === "old-model") ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), - ).toEqual([["fast", "on"]]); + ).toEqual([["fast", "off"]]); // When a probe returns no models, invalidateCaches + refresh must preserve the running // session's catalog instead of dropping to synthetic default. @@ -4229,164 +4345,199 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); - it.effect( - "preserves post-probe overflow selection, per-model learned values, and multi-model clear retention", - () => - Effect.gen(function* () { - const modelIds = Array.from({ length: 257 }, (_, index) => `m${index}`); - const choices = modelIds.map((value, index) => ({ value, name: `Model ${index}` })); - const modelSelect = (currentValue: string) => [ - { - id: "model", - name: "Model", - category: "model" as const, - type: "select" as const, - currentValue, - options: choices, - }, - ]; - const effortSelect = (currentValue: "low" | "high" | "removed") => ({ - id: "effort", - name: "Effort", - category: "thought_level" as const, + it.effect("preserves post-probe overflow selection and per-model learned values", () => + Effect.gen(function* () { + const modelIds = Array.from({ length: 257 }, (_, index) => `m${index}`); + const choices = modelIds.map((value, index) => ({ value, name: `Model ${index}` })); + const modelSelect = (currentValue: string) => [ + { + id: "model", + name: "Model", + category: "model" as const, type: "select" as const, currentValue, - options: [ - { value: "low", name: "Low" }, - { value: "high", name: "High" }, - ], - }); - const variantSelect = { - id: "variant", - name: "Variant", - category: "model_config" as const, - type: "select" as const, - currentValue: "v1", - options: [{ value: "v1", name: "V1" }], - }; - - const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ - prefix: "acp-driver-overflow-post-probe-", - initialModels: { - models: modelIds, - configOptions: [...modelSelect("m0"), effortSelect("low")], - }, - }); - - const initial = yield* waitForEnriched().pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - yield* Fiber.join(initial); + options: choices, + }, + ]; + const effortSelect = (currentValue: "low" | "high" | "removed") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }); + const variantSelect = { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v1", + options: [{ value: "v1", name: "V1" }], + }; - // Publish initial live catalog for m0, then supersede with a fresh 257-model probe. - const initialLive = prepareAcpRegistryLiveConfiguration([ - ...modelSelect("m0"), - effortSelect("low"), - ]).toLiveConfiguration({ includeCatalog: true }); - yield* coordinator.publishLiveConfiguration(identity.instanceId, initialLive); - yield* writeModels({ + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-overflow-post-probe-", + initialModels: { models: modelIds, configOptions: [...modelSelect("m0"), effortSelect("low")], - }); - yield* TestClock.adjust("16 minutes"); - const superseded = yield* waitForEnriched().pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - yield* Fiber.join(superseded); + }, + }); - // Selecting overflow model m256 after a superseding probe must swap slot 255 and mark m256 default. - const sawM256 = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models.at(-1)?.slug === "m256" && snapshot.models.at(-1)?.isDefault === true, - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - prepareAcpRegistryLiveConfiguration([ - ...modelSelect("m256"), - variantSelect, - ]).toLiveConfiguration({ includeCatalog: false }), - ); - const afterM256 = Option.getOrThrow(yield* Fiber.join(sawM256)); - expect(afterM256.models).toHaveLength(256); - expect( - afterM256.models - .at(-1) - ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), - ).toEqual([["variant", "v1"]]); + const initial = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // Publish initial live catalog for m0, then supersede with a fresh 257-model probe. + const initialLive = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("low"), + ]).toLiveConfiguration({ includeCatalog: true }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, initialLive); + yield* writeModels({ + models: modelIds, + configOptions: [...modelSelect("m0"), effortSelect("low")], + }); + yield* TestClock.adjust("16 minutes"); + const superseded = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(superseded); - // Refresh must keep m256 selected in slot 255. - const refreshM256 = yield* waitForEnriched().pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; - const refreshedM256 = Option.getOrThrow(yield* Fiber.join(refreshM256)); - expect(refreshedM256.models.at(-1)?.slug).toBe("m256"); - expect(refreshedM256.models.at(-1)?.isDefault).toBe(true); + // Selecting overflow model m256 after a superseding probe must swap slot 255 and mark m256 default. + const sawM256 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.at(-1)?.slug === "m256" && snapshot.models.at(-1)?.isDefault === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256"), + variantSelect, + ]).toLiveConfiguration({ includeCatalog: false }), + ); + const afterM256 = Option.getOrThrow(yield* Fiber.join(sawM256)); + expect(afterM256.models).toHaveLength(256); + expect( + afterM256.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + + // Refresh must keep m256 selected in slot 255. + const refreshM256 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const refreshedM256 = Option.getOrThrow(yield* Fiber.join(refreshM256)); + expect(refreshedM256.models.at(-1)?.slug).toBe("m256"); + expect(refreshedM256.models.at(-1)?.isDefault).toBe(true); - // Returning to m0 with effort=high restores m255 in slot 255 and learns m0 effort=high. - const sawM0High = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models[0]?.isDefault === true && - snapshot.models.at(-1)?.slug === "m255" && - snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") - ?.currentValue === "high", - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - prepareAcpRegistryLiveConfiguration([ - ...modelSelect("m0"), - effortSelect("high"), - ]).toLiveConfiguration({ includeCatalog: false }), - ); - yield* Fiber.join(sawM0High); + // Returning to m0 with effort=high restores m255 in slot 255 and learns m0 effort=high. + const sawM0High = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models[0]?.isDefault === true && + snapshot.models.at(-1)?.slug === "m255" && + snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("high"), + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM0High); - // Switching to m1 must keep m0's learned effort=high instead of reverting m0 to probe default low. - const sawM1 = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.models[1]?.isDefault === true), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - prepareAcpRegistryLiveConfiguration(modelSelect("m1")).toLiveConfiguration({ - includeCatalog: false, - }), - ); - const afterM1 = Option.getOrThrow(yield* Fiber.join(sawM1)); - expect( - afterM1.models[0]?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), - ).toEqual([["effort", "high"]]); + // Switching to m1 must keep m0's learned effort=high instead of reverting m0 to probe default low. + const sawM1 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[1]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(modelSelect("m1")).toLiveConfiguration({ + includeCatalog: false, + }), + ); + const afterM1 = Option.getOrThrow(yield* Fiber.join(sawM1)); + expect( + afterM1.models[0]?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); - // Sending an invalid value for probe's default model m0 resets m0 back to probe default low. - const sawM0Reset = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models[0]?.isDefault === true && - snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") - ?.currentValue === "low", - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishLiveConfiguration( - identity.instanceId, - prepareAcpRegistryLiveConfiguration([ - ...modelSelect("m0"), - effortSelect("removed"), - ]).toLiveConfiguration({ includeCatalog: false }), - ); - yield* Fiber.join(sawM0Reset); - }), + // Sending an invalid value for probe's default model m0 resets m0 back to probe default low. + const sawM0Reset = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models[0]?.isDefault === true && + snapshot.models[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0"), + effortSelect("removed"), + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM0Reset); + + // If m255 learns variant=v1 and a later probe starts on overflow m256 (displacing m255 + // from the capped 256-model probe list), m255 keeps its learned variant across re-probes. + const sawM255Variant = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.at(-1)?.slug === "m255" && + snapshot.models.at(-1)?.isDefault === true && + snapshot.models + .at(-1) + ?.capabilities?.optionDescriptors?.some((d) => d.id === "variant") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m255"), + variantSelect, + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM255Variant); + yield* writeModels({ + models: modelIds, + configOptions: [...modelSelect("m256")], + }); + yield* TestClock.adjust("16 minutes"); + const probeOnOverflow = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterOverflowProbe = Option.getOrThrow(yield* Fiber.join(probeOnOverflow)); + expect(afterOverflowProbe.models.at(-1)?.slug).toBe("m255"); + expect( + afterOverflowProbe.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + }), ); it.effect( @@ -4399,14 +4550,23 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const releaseWatcher = yield* Deferred.make(); const cacheHitRead = yield* Deferred.make(); const releaseCacheHit = yield* Deferred.make(); + const cacheHitInCommit = yield* Deferred.make(); let gateProbe = false; let blockWatcher = false; let gateAfterCacheRead = false; + let trackCacheHitCommit = false; const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-multi-clear-", initialModels: ["model-a", "model-b"], wrapCoordinator: (base) => ({ ...base, + getUrlAuthAction: (instanceId) => + (trackCacheHitCommit + ? Effect.sync(() => { + trackCacheHitCommit = false; + }).pipe(Effect.andThen(Deferred.succeed(cacheHitInCommit, undefined))) + : Effect.void + ).pipe(Effect.andThen(base.getUrlAuthAction(instanceId))), runBackgroundProbe: (agentId, effect) => base.runBackgroundProbe( agentId, @@ -4590,9 +4750,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Fiber.join(sawFreshCatalog); gateAfterCacheRead = true; - const cachedCommitDone = yield* waitForEnriched().pipe( - Effect.forkScoped({ startImmediately: true }), - ); yield* instance.snapshot.refresh; // Wait until enrichProviderCached has read effort=low from enrichmentCache, before commitEnrichment runs. yield* Deferred.await(cacheHitRead); @@ -4617,9 +4774,24 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }); yield* Fiber.join(sawFreshHigh); - // Release the cache-hit commit: it must publish effort=high, never reverting to effort=low. + // Release the cache-hit commit, wait until it enters commitEnrichment and drains + // liveSnapshotSemaphore via a follow-up command publish, then inspect getSnapshot. + trackCacheHitCommit = true; yield* Deferred.succeed(releaseCacheHit, undefined); - const afterCachedCommit = Option.getOrThrow(yield* Fiber.join(cachedCommitDone)); + yield* Deferred.await(cacheHitInCommit); + const commitDrained = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "commit-drained"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "commit-drained" }], + skills: [], + }); + yield* Fiber.join(commitDrained); + const afterCachedCommit = yield* instance.snapshot.getSnapshot; expect( afterCachedCommit.models .find((m) => m.slug === "fresh-a") @@ -4627,4 +4799,138 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual([["effort", "high"]]); }), ); + + it.effect( + "preserves post-probe advertisedReasoning on newly appearing effort selectors and keeps live options on model-less probes", + () => + Effect.gen(function* () { + const meta = { + reasoningEfforts: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }; + const ids = ["a", "b", "c"]; + const entries = ids.map((id) => ({ modelId: id, name: id, _meta: meta })); + const modelSelect = (currentValue: string) => ({ + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: ids.map((value) => ({ value, name: value })), + }); + const effortSelect = (currentValue: "low" | "high") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }); + + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-advertised-reasoning-", + initialModels: { + models: entries, + configOptions: [modelSelect("a")], + }, + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([modelSelect("a")], undefined, { + currentModelId: "a", + availableModels: entries, + }).toLiveConfiguration({ includeCatalog: true }), + ); + yield* TestClock.adjust("16 minutes"); + const superseded = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(superseded); + + // After a superseding probe without effort, an options-only update introducing effort + // must project effort=high onto a and advertisedReasoning onto b and c. + const sawAdvertised = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "a") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high" && + snapshot.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort") === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([modelSelect("a"), effortSelect("high")], undefined, { + currentModelId: "a", + availableModels: entries, + }).toLiveConfiguration({ includeCatalog: false }), + ); + const afterAdvertised = Option.getOrThrow(yield* Fiber.join(sawAdvertised)); + expect( + afterAdvertised.models + .find((m) => m.slug === "c") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort"), + ).toBe(true); + + // When neither live state nor a fresh probe advertises models, keep live reasoning + // options on the synthetic default model instead of clearing them. + yield* writeModels({ provisional: "" }); + yield* coordinator.clearLiveConfiguration(identity.instanceId); + yield* instance.invalidateCaches ?? Effect.void; + const modelLessInitial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(modelLessInitial); + + const sawSyntheticEffort = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "default") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([effortSelect("high")]).toLiveConfiguration({ + includeCatalog: false, + }), + ); + yield* Fiber.join(sawSyntheticEffort); + + yield* TestClock.adjust("1 minute"); + const modelLessRetry = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterEmptyRetry = Option.getOrThrow(yield* Fiber.join(modelLessRetry)); + expect( + afterEmptyRetry.models + .find((m) => m.slug === "default") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b65e2be7671ce..b0d22c87cf3d1 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -140,15 +140,13 @@ export function acpRegistryProbeSupersedesLiveCatalog(input: { readonly liveModelCount: number; readonly liveModelsFromModelSelect: boolean; }): boolean { + // Empty disposable probes (e.g. cold-start or pre-catalog agents) keep the + // accepted catalog or live options and retry on the 30s provisional TTL. + if (input.probedModelCount === 0) return false; if (input.liveModelCount === 0) return true; if (input.probedModelCount > 1) return true; - if (input.probedModelCount === 1) { - if (input.probedModelsFromModelSelect) return true; - return input.liveModelCount === 1 && !input.liveModelsFromModelSelect; - } - // Empty disposable probes (e.g. cold-start or pre-catalog agents) keep the - // accepted catalog and retry on the 30s provisional TTL instead of clearing it. - return false; + if (input.probedModelsFromModelSelect) return true; + return input.liveModelCount === 1 && !input.liveModelsFromModelSelect; } export function isAcpRegistryCacheValid( @@ -358,20 +356,19 @@ export function retainAcpRegistryLiveOptionsAfterProbe( probe: AcpRegistryProbeOptionSchema, ): Option.Option { const probedModelById = new Map(probe.models.map((model) => [model.id, model])); - const matchingCappedLastModel = + const matchingCappedOverflow = live.cappedLastModel !== undefined && live.cappedPrefixKey !== undefined && - cappedAcpRegistryModelPrefixKey(probe.models) === live.cappedPrefixKey && + live.currentModelId === live.cappedLastModel.id && + cappedAcpRegistryModelPrefixKey(probe.models.map((model) => model.id)) === + live.cappedPrefixKey && probe.models[ACP_REGISTRY_MAX_MODELS - 1]?.id !== live.cappedLastModel.id - ? live.cappedLastModel + ? { cappedPrefixKey: live.cappedPrefixKey, cappedLastModel: live.cappedLastModel } : undefined; const currentProbedModel = live.currentModelId === null ? undefined - : (probedModelById.get(live.currentModelId) ?? - (matchingCappedLastModel !== undefined && matchingCappedLastModel.id === live.currentModelId - ? matchingCappedLastModel - : undefined)); + : (probedModelById.get(live.currentModelId) ?? matchingCappedOverflow?.cappedLastModel); const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); const liveModelOptionIds = new Set(live.modelOptionIds ?? []); @@ -388,16 +385,60 @@ export function retainAcpRegistryLiveOptionsAfterProbe( if (Option.isSome(retained)) sharedDescriptors.push(retained.value); } + const retainedAdvertisedReasoningEntries: Array< + readonly [string, NonNullable] + > = []; + if (live.advertisedReasoning !== undefined) { + for (const [slug, descriptor] of Object.entries(live.advertisedReasoning)) { + const probedModel = probedModelById.get(slug); + if (probedModel === undefined || probedModel.reasoningEffort === null) continue; + if (probedModel.reasoningEffort !== undefined) { + const retained = compatibleLiveOptionValue(probedModel.reasoningEffort, descriptor); + if (Option.isSome(retained) && retained.value.type === "select") { + retainedAdvertisedReasoningEntries.push([slug, retained.value]); + } + continue; + } + retainedAdvertisedReasoningEntries.push([slug, descriptor]); + } + } + const retainedAdvertisedReasoning = + retainedAdvertisedReasoningEntries.length > 0 + ? Object.fromEntries(retainedAdvertisedReasoningEntries) + : undefined; + const advertisedReasoningIds = new Set( + retainedAdvertisedReasoningEntries.map(([, descriptor]) => descriptor.id), + ); + const modelDescriptors: Array = []; if (currentProbedModel !== undefined) { const reasoningDisabled = currentProbedModel.reasoningEffort === null; if (currentProbedModel.id === probe.currentModelId) { + let probeHasReasoning = false; for (const descriptor of probe.configOptions) { if (!isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; - if (reasoningDisabled && isReasoningDescriptor(descriptor)) continue; - const retained = compatibleLiveOptionValue(descriptor, liveById.get(descriptor.id)); + if (isReasoningDescriptor(descriptor)) { + probeHasReasoning = true; + if (reasoningDisabled) continue; + } + const liveMatch = liveById.get(descriptor.id); + if (liveMatch === undefined || !isModelSpecificDescriptor(liveMatch, liveModelOptionIds)) { + continue; + } + const retained = compatibleLiveOptionValue(descriptor, liveMatch); if (Option.isSome(retained)) modelDescriptors.push(retained.value); } + if (!probeHasReasoning && !reasoningDisabled && advertisedReasoningIds.size > 0) { + for (const descriptor of live.configOptions) { + if ( + !probeSharedIds.has(descriptor.id) && + isReasoningDescriptor(descriptor) && + advertisedReasoningIds.has(descriptor.id) + ) { + modelDescriptors.push(descriptor); + } + } + } } else { const advertisedReasoning = currentProbedModel.reasoningEffort; let addedAdvertisedReasoning = false; @@ -422,16 +463,18 @@ export function retainAcpRegistryLiveOptionsAfterProbe( } } - const overflowFields = - matchingCappedLastModel !== undefined && live.cappedPrefixKey !== undefined - ? { cappedPrefixKey: live.cappedPrefixKey, cappedLastModel: matchingCappedLastModel } - : {}; + const overflowFields = matchingCappedOverflow ?? {}; + const advertisedReasoningFields = + retainedAdvertisedReasoning === undefined + ? {} + : { advertisedReasoning: retainedAdvertisedReasoning }; const configOptions = [...sharedDescriptors, ...modelDescriptors]; if (configOptions.length === 0) { - // Keep the running session's model selection moving isDefault (or restoring the - // capped tail slot) even when no options survive, unless nothing differs from probe default. + // Keep the running session's model selection, overflow swap, or advertised reasoning + // even when no active config options survive, unless nothing differs from probe default. if ( - matchingCappedLastModel === undefined && + matchingCappedOverflow === undefined && + retainedAdvertisedReasoning === undefined && (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) ) { return Option.none(); @@ -444,6 +487,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelsFromModelSelect: false, partialOptions: true, ...overflowFields, + ...advertisedReasoningFields, }); } return Option.some({ @@ -456,6 +500,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelsFromModelSelect: false, partialOptions: true, ...overflowFields, + ...advertisedReasoningFields, }); } @@ -549,8 +594,12 @@ function updateLearnedModelsFromProbe( learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), ); const next: Array = []; + const probedSlugs = new Set(); + let probedBuiltInCount = 0; for (const model of probedModels) { if (model.isCustom) continue; + probedBuiltInCount += 1; + probedSlugs.add(model.slug); if (options.currentModelId !== null && model.slug === options.currentModelId) { const specific = (model.capabilities?.optionDescriptors ?? []).filter((descriptor) => isModelSpecificDescriptor(descriptor, options.modelOptionIds), @@ -574,6 +623,15 @@ function updateLearnedModelsFromProbe( const combined = [...probedReasoning, ...kept]; if (combined.length > 0) next.push(modelWithSpecificOptions(model, combined)); } + // When the probe hits the 256-model cap, keep learned options for displaced models (e.g. m255 + // displaced when the probe started on an overflow model like m256). + if (probedBuiltInCount >= ACP_REGISTRY_MAX_MODELS) { + for (const [slug, previous] of learnedBySlug) { + if (!probedSlugs.has(slug)) { + next.push(previous); + } + } + } return next; } @@ -856,6 +914,18 @@ function overlayPartialLiveOptions( nextDescriptors.push(override); } } + } else if (!model.isCustom && !reasoningDisabled) { + const advertised = readAdvertisedReasoning(configuration.advertisedReasoning, model.slug); + if (advertised !== undefined) { + const existingIndex = nextDescriptors.findIndex((item) => item.id === advertised.id); + if (existingIndex >= 0) { + const currentDescriptor = nextDescriptors[existingIndex]!; + const overlaid = compatibleLiveOptionValue(currentDescriptor, advertised); + nextDescriptors[existingIndex] = Option.getOrElse(overlaid, () => currentDescriptor); + } else if (!nextDescriptors.some(isReasoningDescriptor)) { + nextDescriptors.push(advertised); + } + } } if (Equal.equals(existing, nextDescriptors)) return model; return { @@ -915,18 +985,23 @@ export function applyAcpRegistryLiveConfiguration( : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); const cappedLastModel = !useLiveCatalog && + configuration.currentModelId !== null && configuration.cappedLastModel !== undefined && configuration.cappedPrefixKey !== undefined && - cappedAcpRegistryModelPrefixKey( - probedModels.map((model) => ({ id: model.slug, name: model.name })), - ) === configuration.cappedPrefixKey + cappedAcpRegistryModelPrefixKey(probedModels.map((model) => model.slug)) === + configuration.cappedPrefixKey ? configuration.cappedLastModel : undefined; - const replaceLastSlot = + const tailSlotReplacement = cappedLastModel !== undefined && - probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug !== cappedLastModel.id; + probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug !== cappedLastModel.id && + (configuration.currentModelId === cappedLastModel.id || + probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.isDefault === true) + ? cappedLastModel + : undefined; const liveCurrentModelInProbed = - (cappedLastModel !== undefined && configuration.currentModelId === cappedLastModel.id) || + (tailSlotReplacement !== undefined && + configuration.currentModelId === tailSlotReplacement.id) || (configuration.currentModelId !== null && probedModels.some((model) => model.slug === configuration.currentModelId)); const selectedProbedModelId = liveCurrentModelInProbed @@ -934,12 +1009,12 @@ export function applyAcpRegistryLiveConfiguration( : (probedModels.find((model) => model.isDefault)?.slug ?? null); if (!useLiveCatalog && configuration.partialOptions === true) { const modelsForOverlay = - replaceLastSlot && cappedLastModel !== undefined + tailSlotReplacement !== undefined ? replaceLastCappedBuiltInModel( provider.models, modelsFromDiscovery( { - models: [cappedLastModel], + models: [tailSlotReplacement], currentModelId: null, configOptions: options?.probeSharedDescriptors ?? [], }, @@ -949,8 +1024,8 @@ export function applyAcpRegistryLiveConfiguration( ) : provider.models; const partialDisabledReasoning = - cappedLastModel?.reasoningEffort === null - ? new Set([...disabledReasoningSlugs, cappedLastModel.id]) + tailSlotReplacement?.reasoningEffort === null + ? new Set([...disabledReasoningSlugs, tailSlotReplacement.id]) : disabledReasoningSlugs; return { ...snapshot, @@ -1003,8 +1078,8 @@ export function applyAcpRegistryLiveConfiguration( ...(advertised === undefined ? {} : { reasoningEffort: advertised }), }; }); - if (replaceLastSlot && cappedLastModel !== undefined) { - retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = cappedLastModel; + if (tailSlotReplacement !== undefined) { + retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = tailSlotReplacement; } const discovery = useLiveCatalog ? configuration @@ -1020,7 +1095,7 @@ export function applyAcpRegistryLiveConfiguration( !useLiveCatalog && effectiveConfigOptions.length === 0 && !hasAdvertisedReasoning && - !replaceLastSlot + tailSlotReplacement === undefined ? stripReasoningForDisabledModels( withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), disabledReasoningSlugs, @@ -1458,14 +1533,11 @@ export const AcpRegistryDriver: ProviderDriver | undefined; - readonly hasDiscoveredCatalog?: boolean | undefined; + options: { readonly preserveStatus?: boolean | undefined; readonly updateAcceptedAndCache?: boolean | undefined; readonly ignoreProbeBaseline?: boolean | undefined; - readonly revision?: number | undefined; + readonly revision: number; }, ) { const acceptedBefore = yield* Ref.get(acceptedCatalog); @@ -1473,14 +1545,11 @@ export const AcpRegistryDriver: ProviderDriver 0; + const preserveSingleModelCatalog = isExplicitSingletonCatalog(acceptedBefore); + const reasoningDisabledModelSlugs = acceptedBefore.reasoningDisabledModelSlugs; + const hasDiscoveredCatalog = acceptedBefore.builtInModelCount > 0; const withPreservedStatus = (applied: ServerProvider) => - options?.preserveStatus === true + options.preserveStatus === true ? { ...applied, status: current.status, @@ -1489,7 +1558,7 @@ export const AcpRegistryDriver: ProviderDriver model.id === configuration.currentModelId) || (configuration.cappedLastModel !== undefined && configuration.cappedPrefixKey !== undefined && - cappedAcpRegistryModelPrefixKey(probeOptions.models) === + cappedAcpRegistryModelPrefixKey(probeOptions.models.map((model) => model.id)) === configuration.cappedPrefixKey && configuration.currentModelId === configuration.cappedLastModel.id)) ? configuration.currentModelId @@ -1551,9 +1620,8 @@ export const AcpRegistryDriver: ProviderDriver Math.max(prev, appliedRevision)); + if (options.updateAcceptedAndCache === true) { + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); } return withPreservedStatus(applied); } @@ -1564,7 +1632,7 @@ export const AcpRegistryDriver: ProviderDriver Math.max(prev, appliedRevision)); - if (configuration.models.length > 0) { - yield* Ref.update(lastAppliedLiveCatalogRevision, (prev) => - Math.max(prev, appliedRevision), - ); - } + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); + if (configuration.models.length > 0) { + yield* Ref.update(lastAppliedLiveCatalogRevision, (prev) => + Math.max(prev, options.revision), + ); } } const now = yield* Clock.currentTimeMillis; @@ -1625,9 +1690,6 @@ export const AcpRegistryDriver: ProviderDriver | undefined; - readonly hasDiscoveredCatalog?: boolean | undefined; readonly preserveStatus?: boolean; }, ) { @@ -1705,9 +1767,6 @@ export const AcpRegistryDriver: ProviderDriver 0 : undefined, - }); + const published = yield* withLiveRuntimeState(resolved); if (cleared) { yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, clearedThroughRevision), @@ -2000,7 +2048,10 @@ export const AcpRegistryDriver: ProviderDriver, + modelIds: ReadonlyArray, ): string | undefined { - if (models.length < ACP_REGISTRY_MAX_MODELS) return undefined; - return JSON.stringify( - models.slice(0, ACP_REGISTRY_MAX_MODELS - 1).map(({ id, name }) => [id, name]), - ); + if (modelIds.length < ACP_REGISTRY_MAX_MODELS) return undefined; + return JSON.stringify(modelIds.slice(0, ACP_REGISTRY_MAX_MODELS - 1)); } export interface PreparedAcpRegistryLiveConfiguration { readonly catalogKey: string; + readonly hasModelSelect: boolean; readonly toLiveConfiguration: (options?: { readonly includeCatalog?: boolean; }) => AcpRegistryLiveConfiguration; @@ -302,23 +301,10 @@ export function prepareAcpRegistryLiveConfiguration( boundedCurrentModelId === null ? undefined : advertisedModels.find((model) => model.id === boundedCurrentModelId); - let hasOverflowCandidates = false; - if ( - baseModels.length === ACP_REGISTRY_MAX_MODELS && - candidates.length > ACP_REGISTRY_MAX_MODELS - ) { - const baseIds = new Set(baseModels.map((model) => model.id)); - for (const candidate of candidates) { - const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH); - if (id !== undefined && !baseIds.has(id)) { - hasOverflowCandidates = true; - break; - } - } - } - const cappedLastModel = hasOverflowCandidates - ? advertisedModels[ACP_REGISTRY_MAX_MODELS - 1] - : undefined; + const cappedLastModel = + currentModel !== undefined && baseModels.length === ACP_REGISTRY_MAX_MODELS + ? advertisedModels[ACP_REGISTRY_MAX_MODELS - 1] + : undefined; const stripCurrentReasoning = currentModel?.reasoningEffort === null; const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( (descriptor) => @@ -351,11 +337,14 @@ export function prepareAcpRegistryLiveConfiguration( baseModels.map(({ id, name, description }) => [id, name, description]), ]); const cappedPrefixKey = - cappedLastModel === undefined ? undefined : cappedAcpRegistryModelPrefixKey(baseModels); + cappedLastModel === undefined + ? undefined + : cappedAcpRegistryModelPrefixKey(baseModels.map((model) => model.id)); return { // Key on the uncapped-selection catalog identity and provenance so neither effort // toggles nor selecting a model beyond ACP_REGISTRY_MAX_MODELS re-advertise a frozen list. catalogKey, + hasModelSelect, toLiveConfiguration: (options) => { const includeCatalog = options?.includeCatalog !== false; return { From f5b8c5b577d69536d5c5f4a44b0f6934a467592f Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 14:58:56 +0000 Subject: [PATCH 16/35] fix(acp-registry): track overflow tails, merge custom overflow models, and bound displaced learned options --- .../AcpRegistryRuntimeCoordinator.test.ts | 78 ++++++ .../server/AcpRegistryRuntimeCoordinator.ts | 18 +- .../src/server/driver.test.ts | 245 +++++++++++++++++- .../src/server/driver.ts | 209 +++++++++++---- .../provider-acp-registry/src/server/probe.ts | 17 +- packages/provider-acp/src/server/adapter.ts | 5 +- 6 files changed, 485 insertions(+), 87 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 7d7b3f91b8499..0a7c24c880a44 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -658,6 +658,84 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect(clearedEarlierOnly.pendingOptions).toHaveLength(255); expect(clearedEarlierOnly.pendingOptions.at(-1)?.configuration.currentModelId).toBe("m255"); expect(clearedEarlierOnly.pendingOptions.at(-1)?.configuration.preserveDefault).toBe(true); + + // An earlier update with no current-model options still survives clear when it carries + // retained advertisedReasoning (stripping shared options and preserving default). + const advertisedC = effortOption("low"); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null }, + { id: "model-c", name: "Model C", description: null }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const advertisedCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-c": advertisedC }, + }); + const bAdvSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: advertisedCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterAdvClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(afterAdvClear.pendingOptions).toEqual([ + { + revision: bAdvSnap.revision, + configuration: { + models: [], + currentModelId: "model-b", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + advertisedReasoning: { "model-c": advertisedC }, + }, + }, + { + revision: afterAdvClear.revision, + configuration: { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + }, + }, + ]); + // If retain strips advertisedReasoning (e.g. probe disabled reasoning for model-c) + // and model-b has no model-specific options, the earlier entry is dropped. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: advertisedCatalog.catalogRevision, + retain: (live) => { + const { advertisedReasoning: _dropped, ...rest } = live; + return Option.some({ ...rest, partialOptions: true }); + }, + }), + ).toBe(true); + const afterDisabledClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(afterDisabledClear.pendingOptions).toHaveLength(1); + expect(afterDisabledClear.pendingOptions[0]?.configuration.currentModelId).toBe("model-a"); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 5b9fa9b7332da..131c976dc885b 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -328,14 +328,7 @@ const make = Effect.gen(function* () { if (retain === undefined) return EMPTY_OPTIONS_BY_MODEL; const candidates = new Map(); if (current.catalog !== null) { - candidates.set(current.catalog.configuration.currentModelId, { - configuration: { - ...current.catalog.configuration, - models: [], - modelsFromModelSelect: false, - }, - revision: current.catalog.revision, - }); + candidates.set(current.catalog.configuration.currentModelId, current.catalog); } for (const [key, entry] of current.optionsByModel) { candidates.set(key, entry); @@ -349,15 +342,20 @@ const make = Effect.gen(function* () { }); if (Option.isNone(kept)) continue; if (entry.revision < current.revision) { - // Earlier models keep only model-specific options without stealing default selection or shared options. + // Earlier models keep only model-specific options and advertised reasoning + // without stealing default selection or shared options. const modelOptionIds = new Set(kept.value.modelOptionIds ?? []); const modelOnlyOptions = kept.value.configOptions.filter((descriptor) => modelOptionIds.has(descriptor.id), ); - if (modelOnlyOptions.length === 0) continue; + const hasAdvertisedReasoning = + kept.value.advertisedReasoning !== undefined && + Object.keys(kept.value.advertisedReasoning).length > 0; + if (modelOnlyOptions.length === 0 && !hasAdvertisedReasoning) continue; const { cappedLastModel: _droppedOverflow, cappedPrefixKey: _droppedPrefix, + cappedTailIsOverflow: _droppedOverflowFlag, ...rest } = kept.value; retained.delete(kept.value.currentModelId); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 63976652126b9..2d3f1de616978 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -27,6 +27,7 @@ import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator. import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import { AcpRegistryDriver, + MAX_DISPLACED_LEARNED_MODELS, acpRegistryProbeSupersedesLiveCatalog, applyAcpRegistryAvailableCommands, applyAcpRegistryLiveConfiguration, @@ -36,6 +37,7 @@ import { isAcpRegistryCacheValid, retainAcpRegistryLiveOptionsAfterProbe, updateAcpRegistryEnrichmentCache, + updateAcpRegistryLearnedModelsFromProbe, } from "./driver.ts"; import { acpRegistryAdvertisesModelCatalog, @@ -1730,19 +1732,141 @@ describe("prepareAcpRegistryLiveConfiguration", () => { ); expect(withRenamedOverflow.models.at(-1)?.slug).toBe("m256"); expect(withRenamedOverflow.models.at(-1)?.isDefault).toBe(true); - // A shared-prefix probe advertising a different authoritative tail (new-m255) must not - // be overwritten by a stale options-only update selecting m0. - const conflictingTailProvider = providerWithModels( - [ - ...choices.slice(0, 255).map((choice) => ({ - id: choice.value, - name: choice.name, - description: null, - })), - { id: "new-m255", name: "New Model 255", description: null }, + // An overflow model that is also configured as custom must appear once with its custom + // display name in partial overlays, and reappear as custom when m255 returns to slot 255. + const customM256 = [ + toCustomModelSetting({ slug: "m256", name: "Custom M256", capabilities: null }), + ]; + const effortOption = (currentValue: "low" | "high") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, ], - "m0", + }); + const probeM0Config = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0", choices), + effortOption("low"), + ]).toLiveConfiguration({ includeCatalog: true }); + const cappedWithCustom = buildCheckedAcpRegistrySnapshot({ + ...identity, + settings: decodeSettings({ agentId: "test-agent", customModels: customM256 }), + checkedAt: "2026-08-13T10:00:00.000Z", + inspection: { status: "ready", agentId: "test-agent", version: "1.0.0", distribution: "npx" }, + probe: { + probe: { + instanceId: identity.instanceId, + ready: true, + icon: null, + authMethods: [], + sessionManagement: noSessionManagement, + models: probeM0Config.models, + currentModelId: probeM0Config.currentModelId, + configOptions: probeM0Config.configOptions, + ...(probeM0Config.modelOptionIds === undefined + ? {} + : { modelOptionIds: probeM0Config.modelOptionIds }), + }, + slashCommands: [], + skills: [], + }, + }); + const probeM0Schema = { + models: probeM0Config.models, + currentModelId: probeM0Config.currentModelId, + configOptions: probeM0Config.configOptions, + modelOptionIds: new Set(probeM0Config.modelOptionIds ?? []), + }; + const retainedCustomOverflow = Option.getOrThrow( + retainAcpRegistryLiveOptionsAfterProbe( + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256", choices), + effortOption("high"), + ]).toLiveConfiguration({ includeCatalog: false }), + probeM0Schema, + ), + ); + const partialCustomOverflow = applyAcpRegistryLiveConfiguration( + cappedWithCustom, + retainedCustomOverflow, + customM256, + cappedWithCustom.models, + { probeConfigOptions: probeM0Config.configOptions }, ); + const overflowMatches = partialCustomOverflow.models.filter((model) => model.slug === "m256"); + expect(overflowMatches).toHaveLength(1); + expect(overflowMatches[0]).toMatchObject({ + slug: "m256", + name: "Custom M256", + isCustom: false, + isDefault: true, + }); + expect( + overflowMatches[0]?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue, + ).toBe("high"); + const restoredAfterCustomOverflow = applyAcpRegistryLiveConfiguration( + partialCustomOverflow, + { + ...prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + partialOptions: true, + }, + customM256, + partialCustomOverflow.models, + { probeConfigOptions: probeM0Config.configOptions }, + ); + expect(restoredAfterCustomOverflow.models.filter((m) => !m.isCustom).at(-1)?.slug).toBe("m255"); + const restoredCustomM256 = restoredAfterCustomOverflow.models.filter((m) => m.slug === "m256"); + expect(restoredCustomM256).toHaveLength(1); + expect(restoredCustomM256[0]).toMatchObject({ + slug: "m256", + name: "Custom M256", + isCustom: true, + }); + // A session initialized directly on an overflow model (includeCatalog: true) keeps its + // overflow metadata so a superseding probe on m0 retains the overflow model and its options. + const choices300 = Array.from({ length: 300 }, (_, index) => ({ + value: `m${index}`, + name: `Model ${index}`, + })); + const catalogOnM299 = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m299", choices300), + effortOption("high"), + ]).toLiveConfiguration({ includeCatalog: true }); + expect(catalogOnM299.cappedPrefixKey).toBeDefined(); + expect(catalogOnM299.cappedLastModel?.id).toBe("m299"); + expect(catalogOnM299.cappedTailIsOverflow).toBe(true); + const retainedM299 = Option.getOrThrow( + retainAcpRegistryLiveOptionsAfterProbe( + { ...catalogOnM299, models: [], modelsFromModelSelect: false }, + probeM0Schema, + ), + ); + const appliedM299 = applyAcpRegistryLiveConfiguration(cappedProvider, retainedM299, []); + expect(appliedM299.models.at(-1)?.slug).toBe("m299"); + expect(appliedM299.models.at(-1)?.isDefault).toBe(true); + expect( + appliedM299.models.at(-1)?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue, + ).toBe("high"); + // A shared-prefix probe advertising a different authoritative tail (new-m255) must not + // be overwritten by a stale options-only update selecting m0 or removed m255, even when + // new-m255 is the probe's default model. + const conflictingTailModels = [ + ...choices.slice(0, 255).map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + { id: "new-m255", name: "New Model 255", description: null }, + ]; + const conflictingTailProvider = providerWithModels(conflictingTailModels, "m0"); const afterConflictingTail = applyAcpRegistryLiveConfiguration( conflictingTailProvider, prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ @@ -1752,6 +1876,25 @@ describe("prepareAcpRegistryLiveConfiguration", () => { ); expect(afterConflictingTail.models.at(-1)?.slug).toBe("new-m255"); expect(afterConflictingTail.models[0]?.isDefault).toBe(true); + const conflictingDefaultTailProvider = providerWithModels(conflictingTailModels, "new-m255"); + const afterConflictingDefaultTailM0 = applyAcpRegistryLiveConfiguration( + conflictingDefaultTailProvider, + prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + [], + ); + expect(afterConflictingDefaultTailM0.models.at(-1)?.slug).toBe("new-m255"); + expect(afterConflictingDefaultTailM0.models[0]?.isDefault).toBe(true); + const afterConflictingDefaultTailM255 = applyAcpRegistryLiveConfiguration( + conflictingDefaultTailProvider, + prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + [], + ); + expect(afterConflictingDefaultTailM255.models.at(-1)?.slug).toBe("new-m255"); + expect(afterConflictingDefaultTailM255.models.at(-1)?.isDefault).toBe(true); // When live currentModelId is null and the probe started on m256, keep m256 as default. const probeOnM256 = providerWithModels( [ @@ -1805,6 +1948,67 @@ describe("prepareAcpRegistryLiveConfiguration", () => { modelSelect("m0", [{ value: "m0", name: "Model 0 Renamed" }, ...choices.slice(1)]), ).catalogKey, ).not.toBe(keyM0); + // Capped probes bound displaced learned-model history while keeping recently seen models + // (such as m255 displaced by an overflow probe on m256) ahead of older displaced entries. + const variantCapabilities = { + optionDescriptors: [ + { + id: "variant", + label: "Variant", + type: "select" as const, + currentValue: "v1", + options: [{ id: "v1", label: "V1" }], + }, + ], + }; + const absentLearned = Array.from({ length: MAX_DISPLACED_LEARNED_MODELS + 10 }, (_, index) => ({ + slug: `old-${index}`, + name: `Old ${index}`, + isCustom: false, + capabilities: variantCapabilities, + })); + const m255Learned = { + slug: "m255", + name: "Model 255", + isCustom: false, + capabilities: variantCapabilities, + }; + const probeWithM255 = cappedProvider.models; + const probeDisplacingM255 = providerWithModels( + [ + ...choices.slice(0, 255).map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + { id: "m256", name: "Model 256", description: null }, + ], + "m256", + ).models; + const learnedAfterProbe1 = updateAcpRegistryLearnedModelsFromProbe( + [...absentLearned, m255Learned], + probeWithM255, + { + currentModelId: "m0", + modelOptionIds: new Set(["variant"]), + reasoningDisabledModelSlugs: new Set(), + }, + ); + expect(learnedAfterProbe1).toHaveLength(MAX_DISPLACED_LEARNED_MODELS + 1); + expect(learnedAfterProbe1[0]?.slug).toBe("old-10"); + expect(learnedAfterProbe1.at(-1)?.slug).toBe("m255"); + const learnedAfterProbe2 = updateAcpRegistryLearnedModelsFromProbe( + learnedAfterProbe1, + probeDisplacingM255, + { + currentModelId: "m256", + modelOptionIds: new Set(["variant"]), + reasoningDisabledModelSlugs: new Set(), + }, + ); + expect(learnedAfterProbe2).toHaveLength(MAX_DISPLACED_LEARNED_MODELS); + expect(learnedAfterProbe2[0]?.slug).toBe("old-11"); + expect(learnedAfterProbe2.at(-1)?.slug).toBe("m255"); // Toggling an effort selector on a session with a fixed modelState must keep catalogKey // stable (so frozen lists never re-advertise over a newer probe) while projecting newly @@ -4521,6 +4725,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ]).toLiveConfiguration({ includeCatalog: false }), ); yield* Fiber.join(sawM255Variant); + // Clear only coordinator state so m255's variant can only survive via learnedModels. + yield* coordinator.clearLiveConfiguration(identity.instanceId); yield* writeModels({ models: modelIds, configOptions: [...modelSelect("m256")], @@ -4531,9 +4737,22 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* instance.snapshot.refresh; const afterOverflowProbe = Option.getOrThrow(yield* Fiber.join(probeOnOverflow)); - expect(afterOverflowProbe.models.at(-1)?.slug).toBe("m255"); + expect(afterOverflowProbe.models.at(-1)?.slug).toBe("m256"); + + yield* writeModels({ + models: modelIds, + configOptions: [...modelSelect("m0")], + }); + yield* TestClock.adjust("16 minutes"); + const probeRestored = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterRestoreProbe = Option.getOrThrow(yield* Fiber.join(probeRestored)); + expect(afterRestoreProbe.models.at(-1)?.slug).toBe("m255"); + expect(afterRestoreProbe.models[0]?.isDefault).toBe(true); expect( - afterOverflowProbe.models + afterRestoreProbe.models .at(-1) ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["variant", "v1"]]); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b0d22c87cf3d1..ef03c3eabae7a 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -74,6 +74,40 @@ const decodeSettings = Schema.decodeSync(AcpRegistrySettings); // Cache only successful authenticated probes so sign-in changes remain visible. const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000; const PROBE_PROVISIONAL_TTL_MS = 30 * 1_000; +export const MAX_DISPLACED_LEARNED_MODELS = 64; + +const cappedOverflowTailByModels = new WeakMap, string>(); + +function markCappedOverflowTail( + models: ReadonlyArray, + slug: string | undefined, +): ReadonlyArray { + if (slug !== undefined) { + cappedOverflowTailByModels.set(models, slug); + } + return models; +} + +function preserveCappedOverflowTail( + source: ReadonlyArray, + target: ReadonlyArray, +): ReadonlyArray { + const slug = cappedOverflowTailByModels.get(source); + if (slug !== undefined && target !== source) { + const builtInTail = target.filter((model) => !model.isCustom)[ACP_REGISTRY_MAX_MODELS - 1]; + if (builtInTail?.slug === slug) { + cappedOverflowTailByModels.set(target, slug); + } + } + return target; +} + +function hasCappedOverflowTail( + models: ReadonlyArray, + tailSlug: string | undefined, +): boolean { + return tailSlug !== undefined && cappedOverflowTailByModels.get(models) === tailSlug; +} function acpRegistryProbeTtlMs(provider: ServerProvider): number { const discoveredModels = provider.models.filter((model) => !model.isCustom); @@ -93,6 +127,7 @@ interface AcpRegistryProbeOptionSchema { readonly currentModelId: string | null; readonly configOptions: ReadonlyArray; readonly modelOptionIds: ReadonlySet; + readonly cappedTailIsOverflow?: boolean; } interface AcceptedAcpRegistryCatalog { @@ -320,10 +355,18 @@ function updateLearnedModelsFromLive( } const updated = modelWithSpecificOptions(model, specific); if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { + learnedBySlug.delete(model.slug); learnedBySlug.set(model.slug, updated); changed = true; } } + const maxLearnedModels = ACP_REGISTRY_MAX_MODELS + MAX_DISPLACED_LEARNED_MODELS; + while (learnedBySlug.size > maxLearnedModels) { + const oldestKey = learnedBySlug.keys().next().value; + if (oldestKey === undefined) break; + learnedBySlug.delete(oldestKey); + changed = true; + } return changed ? Array.from(learnedBySlug.values()) : learned; } @@ -356,19 +399,28 @@ export function retainAcpRegistryLiveOptionsAfterProbe( probe: AcpRegistryProbeOptionSchema, ): Option.Option { const probedModelById = new Map(probe.models.map((model) => [model.id, model])); - const matchingCappedOverflow = + const matchingCappedTail = live.cappedLastModel !== undefined && live.cappedPrefixKey !== undefined && - live.currentModelId === live.cappedLastModel.id && cappedAcpRegistryModelPrefixKey(probe.models.map((model) => model.id)) === live.cappedPrefixKey && - probe.models[ACP_REGISTRY_MAX_MODELS - 1]?.id !== live.cappedLastModel.id - ? { cappedPrefixKey: live.cappedPrefixKey, cappedLastModel: live.cappedLastModel } + probe.models[ACP_REGISTRY_MAX_MODELS - 1]?.id !== live.cappedLastModel.id && + (live.cappedTailIsOverflow === true + ? live.currentModelId === live.cappedLastModel.id + : probe.cappedTailIsOverflow === true) + ? { + cappedPrefixKey: live.cappedPrefixKey, + cappedLastModel: live.cappedLastModel, + ...(live.cappedTailIsOverflow === true ? { cappedTailIsOverflow: true } : {}), + } : undefined; const currentProbedModel = live.currentModelId === null ? undefined - : (probedModelById.get(live.currentModelId) ?? matchingCappedOverflow?.cappedLastModel); + : (probedModelById.get(live.currentModelId) ?? + (matchingCappedTail?.cappedLastModel.id === live.currentModelId + ? matchingCappedTail.cappedLastModel + : undefined)); const liveById = new Map(live.configOptions.map((descriptor) => [descriptor.id, descriptor])); const liveModelOptionIds = new Set(live.modelOptionIds ?? []); @@ -463,7 +515,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( } } - const overflowFields = matchingCappedOverflow ?? {}; + const overflowFields = matchingCappedTail ?? {}; const advertisedReasoningFields = retainedAdvertisedReasoning === undefined ? {} @@ -473,7 +525,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( // Keep the running session's model selection, overflow swap, or advertised reasoning // even when no active config options survive, unless nothing differs from probe default. if ( - matchingCappedOverflow === undefined && + matchingCappedTail === undefined && retainedAdvertisedReasoning === undefined && (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) ) { @@ -481,7 +533,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( } return Option.some({ models: [], - currentModelId: currentProbedModel?.id ?? live.currentModelId, + currentModelId: live.currentModelId, configOptions: [], modelOptionIds: [], modelsFromModelSelect: false, @@ -578,10 +630,10 @@ function mergeLearnedModelOptions( }), }; }); - return changed ? merged : models; + return changed ? preserveCappedOverflowTail(models, merged) : models; } -function updateLearnedModelsFromProbe( +export function updateAcpRegistryLearnedModelsFromProbe( learned: ReadonlyArray, probedModels: ReadonlyArray, options: { @@ -623,14 +675,22 @@ function updateLearnedModelsFromProbe( const combined = [...probedReasoning, ...kept]; if (combined.length > 0) next.push(modelWithSpecificOptions(model, combined)); } - // When the probe hits the 256-model cap, keep learned options for displaced models (e.g. m255 - // displaced when the probe started on an overflow model like m256). + // When the probe hits the 256-model cap, keep a bounded window of displaced learned models + // (oldest first so models seen in this probe stay newest on subsequent rotations). if (probedBuiltInCount >= ACP_REGISTRY_MAX_MODELS) { + const displaced: Array = []; for (const [slug, previous] of learnedBySlug) { if (!probedSlugs.has(slug)) { - next.push(previous); + displaced.push(previous); } } + const retainedDisplaced = + displaced.length > MAX_DISPLACED_LEARNED_MODELS + ? displaced.slice(displaced.length - MAX_DISPLACED_LEARNED_MODELS) + : displaced; + if (retainedDisplaced.length > 0) { + return [...retainedDisplaced, ...next]; + } } return next; } @@ -812,7 +872,12 @@ function baseSnapshot( : input.settings.agentId.length > 0), }, ...(input.message ? { message: input.message } : {}), - models: modelsFromDiscovery(input.probe?.probe, input.settings.customModels), + models: markCappedOverflowTail( + modelsFromDiscovery(input.probe?.probe, input.settings.customModels), + input.probe?.cappedTailIsOverflow === true + ? (input.probe.probe.currentModelId ?? undefined) + : undefined, + ), ...(input.probe === undefined ? {} : { @@ -861,7 +926,7 @@ function stripReasoningForDisabledModels( : createModelCapabilities({ optionDescriptors: filtered }), }; }); - return changed ? next : models; + return changed ? preserveCappedOverflowTail(models, next) : models; } function overlayPartialLiveOptions( @@ -936,22 +1001,10 @@ function overlayPartialLiveOptions( : createModelCapabilities({ optionDescriptors: nextDescriptors }), }; }); + const overlaid = preserveCappedOverflowTail(models, updated); return configuration.preserveDefault === true - ? updated - : withAcpRegistryDefaultModel(updated, selectedProbedModelId); -} - -function replaceLastCappedBuiltInModel( - models: ReadonlyArray, - replacement: ServerProviderModel, -): ReadonlyArray { - let builtInIndex = 0; - return models.map((model) => { - if (model.isCustom) return model; - const isTarget = builtInIndex === ACP_REGISTRY_MAX_MODELS - 1; - builtInIndex += 1; - return isTarget ? replacement : model; - }); + ? overlaid + : withAcpRegistryDefaultModel(overlaid, selectedProbedModelId); } export function applyAcpRegistryLiveConfiguration( @@ -964,6 +1017,7 @@ export function applyAcpRegistryLiveConfiguration( readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; readonly hasDiscoveredCatalog?: boolean | undefined; readonly probeSharedDescriptors?: ReadonlyArray | undefined; + readonly probeConfigOptions?: ReadonlyArray | undefined; }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; @@ -992,13 +1046,27 @@ export function applyAcpRegistryLiveConfiguration( configuration.cappedPrefixKey ? configuration.cappedLastModel : undefined; + const currentTailSlug = probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug; + const providerHasOverflowTail = hasCappedOverflowTail(provider.models, currentTailSlug); const tailSlotReplacement = cappedLastModel !== undefined && - probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug !== cappedLastModel.id && - (configuration.currentModelId === cappedLastModel.id || - probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.isDefault === true) + currentTailSlug !== cappedLastModel.id && + (configuration.cappedTailIsOverflow === true + ? configuration.currentModelId === cappedLastModel.id + : providerHasOverflowTail) ? cappedLastModel : undefined; + const nextOverflowTailSlug = useLiveCatalog + ? configuration.cappedTailIsOverflow === true + ? (configuration.currentModelId ?? undefined) + : undefined + : tailSlotReplacement !== undefined + ? configuration.cappedTailIsOverflow === true + ? tailSlotReplacement.id + : undefined + : providerHasOverflowTail + ? currentTailSlug + : undefined; const liveCurrentModelInProbed = (tailSlotReplacement !== undefined && configuration.currentModelId === tailSlotReplacement.id) || @@ -1008,21 +1076,31 @@ export function applyAcpRegistryLiveConfiguration( ? configuration.currentModelId : (probedModels.find((model) => model.isDefault)?.slug ?? null); if (!useLiveCatalog && configuration.partialOptions === true) { - const modelsForOverlay = - tailSlotReplacement !== undefined - ? replaceLastCappedBuiltInModel( - provider.models, - modelsFromDiscovery( - { - models: [tailSlotReplacement], - currentModelId: null, - configOptions: options?.probeSharedDescriptors ?? [], - }, - [], - previousModels.filter((model) => !model.isCustom), - )[0]!, - ) - : provider.models; + const modelsForOverlay = (() => { + if (tailSlotReplacement === undefined) return provider.models; + const replacementBuiltIn = modelsFromDiscovery( + { + models: [tailSlotReplacement], + currentModelId: null, + configOptions: options?.probeSharedDescriptors ?? [], + }, + [], + previousModels.filter((model) => !model.isCustom), + )[0]!; + const nextBuiltInModels = probedModels.map((model, index) => + index === ACP_REGISTRY_MAX_MODELS - 1 ? replacementBuiltIn : model, + ); + const customModelCapabilities = + options?.probeConfigOptions !== undefined + ? options.probeConfigOptions.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: options.probeConfigOptions }) + : (provider.models.find((model) => model.isCustom)?.capabilities ?? + (options?.probeSharedDescriptors && options.probeSharedDescriptors.length > 0 + ? createModelCapabilities({ optionDescriptors: options.probeSharedDescriptors }) + : EMPTY_CAPABILITIES)); + return providerModelsFromSettings(nextBuiltInModels, customModels, customModelCapabilities); + })(); const partialDisabledReasoning = tailSlotReplacement?.reasoningEffort === null ? new Set([...disabledReasoningSlugs, tailSlotReplacement.id]) @@ -1030,11 +1108,14 @@ export function applyAcpRegistryLiveConfiguration( return { ...snapshot, status: provider.enabled ? "ready" : provider.status, - models: overlayPartialLiveOptions( - modelsForOverlay, - configuration, - selectedProbedModelId, - partialDisabledReasoning, + models: markCappedOverflowTail( + overlayPartialLiveOptions( + modelsForOverlay, + configuration, + selectedProbedModelId, + partialDisabledReasoning, + ), + nextOverflowTailSlug, ), }; } @@ -1108,10 +1189,12 @@ export function applyAcpRegistryLiveConfiguration( return { ...snapshot, status: provider.enabled ? "ready" : provider.status, - models: + models: markCappedOverflowTail( dropUnmatchedModelOptions && (effectiveConfigOptions.length > 0 || hasAdvertisedReasoning) ? withAcpRegistryDefaultModel(nextModels, selectedProbedModelId) : nextModels, + nextOverflowTailSlug, + ), }; } @@ -1129,7 +1212,7 @@ function withAcpRegistryDefaultModel( const { isDefault: _previous, ...rest } = model; return isDefault ? { ...rest, isDefault: true } : rest; }); - return changed ? next : models; + return changed ? preserveCappedOverflowTail(models, next) : models; } function applyAcpRegistryUrlAuthAction( @@ -1233,6 +1316,7 @@ interface DetailedAcpRegistryProviderStatus { readonly probedConfigOptions: ReadonlyArray; readonly probedModelCount: number; readonly probedModelsFromModelSelect: boolean; + readonly probedCappedTailIsOverflow: boolean; readonly probedCurrentModelId: string | null; readonly probedModelOptionIds: ReadonlySet; readonly reasoningDisabledModelSlugs: ReadonlySet; @@ -1259,6 +1343,7 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( probedConfigOptions: [], probedModelCount: 0, probedModelsFromModelSelect: false, + probedCappedTailIsOverflow: false, probedCurrentModelId: null, probedModelOptionIds: EMPTY_SLUG_SET, reasoningDisabledModelSlugs: EMPTY_SLUG_SET, @@ -1317,6 +1402,7 @@ const checkAcpRegistryProviderStatusDetailed = Effect.fn( probedConfigOptions: probed.success.probe.configOptions, probedModelCount: probed.success.probe.models.length, probedModelsFromModelSelect: probed.success.modelsFromModelSelect === true, + probedCappedTailIsOverflow: probed.success.cappedTailIsOverflow === true, probedCurrentModelId: probed.success.probe.currentModelId, probedModelOptionIds: new Set(probed.success.probe.modelOptionIds ?? []), reasoningDisabledModelSlugs: new Set( @@ -1483,6 +1569,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; + readonly probeConfigOptions?: ReadonlyArray | undefined; }, ) => Ref.get(acceptedCatalog).pipe( @@ -1512,6 +1599,7 @@ export const AcpRegistryDriver: ProviderDriver model.id)) === configuration.cappedPrefixKey && - configuration.currentModelId === configuration.cappedLastModel.id)) + configuration.currentModelId === configuration.cappedLastModel.id && + (configuration.cappedTailIsOverflow === true || + probeOptions.cappedTailIsOverflow === true))) ? configuration.currentModelId : null; const skipModelSlugs = @@ -1618,6 +1708,7 @@ export const AcpRegistryDriver: ProviderDriver; // Stable prefix key (first ACP_REGISTRY_MAX_MODELS - 1 models) for capped overflow updates. readonly cappedPrefixKey?: string; - // Last visible model slot when candidates exceed ACP_REGISTRY_MAX_MODELS, carrying either - // an overflow selection or the restored tail model when returning to the stable prefix. + // Last visible model slot when the catalog hits ACP_REGISTRY_MAX_MODELS and a current model + // is resolved, carrying either an overflow selection or the base tail model. readonly cappedLastModel?: AcpRegistryProbeModel; + // True when cappedLastModel was promoted into slot ACP_REGISTRY_MAX_MODELS - 1 from beyond the cap. + readonly cappedTailIsOverflow?: boolean; } export function cappedAcpRegistryModelPrefixKey( @@ -305,6 +307,7 @@ export function prepareAcpRegistryLiveConfiguration( currentModel !== undefined && baseModels.length === ACP_REGISTRY_MAX_MODELS ? advertisedModels[ACP_REGISTRY_MAX_MODELS - 1] : undefined; + const cappedTailIsOverflow = cappedLastModel !== undefined && !currentInBase; const stripCurrentReasoning = currentModel?.reasoningEffort === null; const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }).filter( (descriptor) => @@ -354,8 +357,12 @@ export function prepareAcpRegistryLiveConfiguration( modelOptionIds, modelsFromModelSelect: includeCatalog && hasModelSelect, ...(!includeCatalog && advertisedReasoning !== undefined ? { advertisedReasoning } : {}), - ...(!includeCatalog && cappedLastModel !== undefined && cappedPrefixKey !== undefined - ? { cappedPrefixKey, cappedLastModel } + ...(cappedLastModel !== undefined && cappedPrefixKey !== undefined + ? { + cappedPrefixKey, + cappedLastModel, + ...(cappedTailIsOverflow ? { cappedTailIsOverflow: true } : {}), + } : {}), }; }, @@ -498,6 +505,7 @@ export interface AcpRegistryConfigurationProbeResult { readonly slashCommands: ReadonlyArray; readonly skills: ReadonlyArray; readonly modelsFromModelSelect?: boolean; + readonly cappedTailIsOverflow?: boolean; } export type AcpRegistryConfigurationProbe = ( @@ -748,6 +756,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo slashCommands: result.commands.slashCommands, skills: result.commands.skills, modelsFromModelSelect: result.liveConfiguration.modelsFromModelSelect === true, + cappedTailIsOverflow: result.liveConfiguration.cappedTailIsOverflow === true, }; }, ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 54522fb163eb7..fc7a50158b1be 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2284,9 +2284,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); - // Track the model catalog last published per session so mid-session option - // updates do not re-advertise a frozen catalog over a newer periodic probe; - // cache invalidation relies on the follow-up probe rather than session replay. + // Track the last published catalog key per session so mid-session option updates + // do not re-advertise an unchanged model list over a fresher catalog. const lastPublishedCatalogKey = yield* Ref.make<{ readonly epoch: number; readonly key: string | null; From 792b6b5913a23d73f7bfbedf880ceaedcff1c712 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 15:24:58 +0000 Subject: [PATCH 17/35] fix(acp-registry): preserve overflow tags, catalog reasoning, earlier overflow options, and updated option schemas --- .../AcpRegistryRuntimeCoordinator.test.ts | 76 +++++ .../server/AcpRegistryRuntimeCoordinator.ts | 36 +- .../src/server/driver.test.ts | 320 +++++++++++++++++- .../src/server/driver.ts | 157 ++++++++- 4 files changed, 569 insertions(+), 20 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 0a7c24c880a44..1d501454cce83 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -736,6 +736,82 @@ describe("AcpRegistryRuntimeCoordinator", () => { const afterDisabledClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(afterDisabledClear.pendingOptions).toHaveLength(1); expect(afterDisabledClear.pendingOptions[0]?.configuration.currentModelId).toBe("model-a"); + + // Stripping a catalog entry extracts non-current models' reasoningEffort into + // advertisedReasoning for retain, while excluding currentModelId and reasoningEffort: null. + const highEffort = effortOption("high"); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: highEffort }, + { id: "model-c", name: "Model C", description: null, reasoningEffort: null }, + ], + currentModelId: "model-a", + configOptions: [effortOption("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + const reasoningCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: reasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterCatalogReasoningClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterCatalogReasoningClear.pendingOptions[0]?.configuration.advertisedReasoning, + ).toEqual({ + "model-b": highEffort, + }); + + // An earlier overflow model update keeps its overflow metadata alongside preserveDefault + // so the driver can learn its options on replay without swapping slot 255 or default. + const overflowModel = { id: "m256", name: "Model 256", description: null }; + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "m256", + configOptions: [modeOption("code"), variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + cappedPrefixKey: "prefix-255", + cappedLastModel: overflowModel, + cappedTailIsOverflow: true, + }); + const overflowSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "m0", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + cappedPrefixKey: "prefix-255", + cappedLastModel: { id: "m255", name: "Model 255", description: null }, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: reasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterOverflowClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterOverflowClear.pendingOptions.find( + (entry) => entry.revision === overflowSnap.revision, + )?.configuration, + ).toEqual({ + models: [], + currentModelId: "m256", + configOptions: [variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + cappedPrefixKey: "prefix-255", + cappedLastModel: overflowModel, + cappedTailIsOverflow: true, + }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 131c976dc885b..d454106a024c5 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -335,10 +335,33 @@ const make = Effect.gen(function* () { } const retained = new Map(); for (const entry of sortedPendingOptions(candidates)) { + const catalogAdvertisedReasoning = (() => { + if (entry.configuration.advertisedReasoning !== undefined) { + return entry.configuration.advertisedReasoning; + } + const entries: Array< + readonly [ + string, + NonNullable, + ] + > = []; + for (const model of entry.configuration.models) { + if ( + model.id !== entry.configuration.currentModelId && + model.reasoningEffort != null + ) { + entries.push([model.id, model.reasoningEffort]); + } + } + return entries.length > 0 ? Object.fromEntries(entries) : undefined; + })(); const kept = retain({ ...entry.configuration, models: [], modelsFromModelSelect: false, + ...(catalogAdvertisedReasoning === undefined + ? {} + : { advertisedReasoning: catalogAdvertisedReasoning }), }); if (Option.isNone(kept)) continue; if (entry.revision < current.revision) { @@ -352,9 +375,15 @@ const make = Effect.gen(function* () { kept.value.advertisedReasoning !== undefined && Object.keys(kept.value.advertisedReasoning).length > 0; if (modelOnlyOptions.length === 0 && !hasAdvertisedReasoning) continue; + const keepOverflowModel = + kept.value.cappedTailIsOverflow === true && + kept.value.cappedLastModel !== undefined && + kept.value.cappedPrefixKey !== undefined && + kept.value.cappedLastModel.id === kept.value.currentModelId && + modelOnlyOptions.length > 0; const { - cappedLastModel: _droppedOverflow, - cappedPrefixKey: _droppedPrefix, + cappedLastModel, + cappedPrefixKey, cappedTailIsOverflow: _droppedOverflowFlag, ...rest } = kept.value; @@ -365,6 +394,9 @@ const make = Effect.gen(function* () { configOptions: modelOnlyOptions, modelOptionIds: modelOnlyOptions.map((descriptor) => descriptor.id), preserveDefault: true, + ...(keepOverflowModel + ? { cappedPrefixKey, cappedLastModel, cappedTailIsOverflow: true } + : {}), }, revision: entry.revision, }); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 2d3f1de616978..6281db7444fe8 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -37,9 +37,11 @@ import { isAcpRegistryCacheValid, retainAcpRegistryLiveOptionsAfterProbe, updateAcpRegistryEnrichmentCache, + updateAcpRegistryLearnedModelsFromLive, updateAcpRegistryLearnedModelsFromProbe, } from "./driver.ts"; import { + ACP_REGISTRY_MAX_MODELS, acpRegistryAdvertisesModelCatalog, acpRegistryProbeResult, normalizeAcpRegistryLiveConfiguration, @@ -1733,8 +1735,16 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(withRenamedOverflow.models.at(-1)?.slug).toBe("m256"); expect(withRenamedOverflow.models.at(-1)?.isDefault).toBe(true); // An overflow model that is also configured as custom must appear once with its custom - // display name in partial overlays, and reappear as custom when m255 returns to slot 255. + // display name in partial overlays, and reappear as custom when m255 returns to slot 255 + // without inheriting another custom model's bespoke capabilities. const customM256 = [ + toCustomModelSetting({ + slug: "gateway/fast", + name: "Fast", + capabilities: { + optionDescriptors: [{ id: "fast", label: "Fast", type: "boolean" }], + }, + }), toCustomModelSetting({ slug: "m256", name: "Custom M256", capabilities: null }), ]; const effortOption = (currentValue: "low" | "high") => ({ @@ -1829,6 +1839,190 @@ describe("prepareAcpRegistryLiveConfiguration", () => { name: "Custom M256", isCustom: true, }); + const restoredWithoutProbeCaps = applyAcpRegistryLiveConfiguration( + partialCustomOverflow, + { + ...prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + partialOptions: true, + }, + customM256, + partialCustomOverflow.models, + ); + expect( + restoredWithoutProbeCaps.models + .find((m) => m.slug === "m256" && m.isCustom) + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toEqual([]); + // Retained overflow options replace an older learned schema for the same ID while keeping + // unrelated learned options and validating shared descriptors against the probe. + const modeSelect = (currentValue: "ask" | "code", values: ReadonlyArray<"ask" | "code">) => ({ + id: "mode", + name: "Mode", + category: "mode" as const, + type: "select" as const, + currentValue, + options: values.map((value) => ({ value, name: value })), + }); + const probeModeOnly = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0", choices), + modeSelect("ask", ["ask"]), + ]).toLiveConfiguration({ includeCatalog: true }); + const retainedV2Overflow = Option.getOrThrow( + retainAcpRegistryLiveOptionsAfterProbe( + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256", choices), + modeSelect("code", ["ask", "code"]), + { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v2", + options: [{ value: "v2", name: "V2" }], + }, + ]).toLiveConfiguration({ includeCatalog: false }), + { + models: probeModeOnly.models, + currentModelId: probeModeOnly.currentModelId, + configOptions: probeModeOnly.configOptions, + modelOptionIds: new Set(probeModeOnly.modelOptionIds ?? []), + }, + ), + ); + const oldLearnedM256 = [ + { + slug: "m256", + name: "Model 256", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "variant", + label: "Variant", + type: "select" as const, + currentValue: "v1", + options: [{ id: "v1", label: "V1" }], + }, + { + id: "style", + label: "Style", + type: "select" as const, + currentValue: "s1", + options: [{ id: "s1", label: "S1" }], + }, + ], + }, + }, + ]; + const appliedV2Overflow = applyAcpRegistryLiveConfiguration( + cappedProvider, + retainedV2Overflow, + [], + oldLearnedM256, + { probeSharedDescriptors: probeModeOnly.configOptions }, + ); + expect( + appliedV2Overflow.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["mode", "ask"], + ["style", "s1"], + ["variant", "v2"], + ]); + // A probe starting on overflow m256 tags its tail so retained live updates on m5 or m255 + // restore m255 into slot 255 while keeping the running session's default and effort. + const probeOverflowM256 = prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256", choices), + effortOption("low"), + ]).toLiveConfiguration({ includeCatalog: true }); + expect(probeOverflowM256.cappedTailIsOverflow).toBe(true); + const probeOverflowSnapshot = buildCheckedAcpRegistrySnapshot({ + ...identity, + settings: decodeSettings({ agentId: "test-agent" }), + checkedAt: "2026-08-13T10:00:00.000Z", + inspection: { status: "ready", agentId: "test-agent", version: "1.0.0", distribution: "npx" }, + probe: { + probe: { + instanceId: identity.instanceId, + ready: true, + icon: null, + authMethods: [], + sessionManagement: noSessionManagement, + models: probeOverflowM256.models, + currentModelId: probeOverflowM256.currentModelId, + configOptions: probeOverflowM256.configOptions, + ...(probeOverflowM256.modelOptionIds === undefined + ? {} + : { modelOptionIds: probeOverflowM256.modelOptionIds }), + }, + slashCommands: [], + skills: [], + cappedTailIsOverflow: true, + }, + }); + const probeOverflowSchema = { + models: probeOverflowM256.models, + currentModelId: probeOverflowM256.currentModelId, + configOptions: probeOverflowM256.configOptions, + modelOptionIds: new Set(probeOverflowM256.modelOptionIds ?? []), + cappedTailIsOverflow: true, + }; + for (const activeSlug of ["m5", "m255"] as const) { + const retainedOverOverflowProbe = Option.getOrThrow( + retainAcpRegistryLiveOptionsAfterProbe( + prepareAcpRegistryLiveConfiguration([ + ...modelSelect(activeSlug, choices), + effortOption("high"), + ]).toLiveConfiguration({ includeCatalog: false }), + probeOverflowSchema, + ), + ); + const appliedOverOverflowProbe = applyAcpRegistryLiveConfiguration( + probeOverflowSnapshot, + retainedOverOverflowProbe, + [], + probeOverflowSnapshot.models, + { probeConfigOptions: probeOverflowM256.configOptions }, + ); + expect(appliedOverOverflowProbe.models.at(-1)?.slug).toBe("m255"); + const defaultModel = appliedOverOverflowProbe.models.find((m) => m.isDefault); + expect(defaultModel?.slug).toBe(activeSlug); + expect( + defaultModel?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue, + ).toBe("high"); + } + // Cache equality shortcuts must not drop an overflow-tail tag change when a model is + // inserted at index 255 while keeping the same visible list [m0..m254, m256]. + const catalogWithoutM255 = [...choices.slice(0, 255), choices[256]!]; + const untaggedM256Snapshot = providerWithModels( + catalogWithoutM255.map((choice) => ({ + id: choice.value, + name: choice.name, + description: null, + })), + "m256", + ); + const cacheAfterOverflowTag = updateAcpRegistryEnrichmentCache({ + cache: { generation: 1, entry: { provider: untaggedM256Snapshot, expiresAt: 100_000 } }, + configuration: prepareAcpRegistryLiveConfiguration( + modelSelect("m256", choices), + ).toLiveConfiguration({ includeCatalog: true }), + customModels: [], + now: 1_000, + }); + expect(cacheAfterOverflowTag.generation).toBe(2); + const cacheAfterM0Restore = updateAcpRegistryEnrichmentCache({ + cache: cacheAfterOverflowTag, + configuration: prepareAcpRegistryLiveConfiguration( + modelSelect("m0", choices), + ).toLiveConfiguration({ includeCatalog: false }), + customModels: [], + now: 2_000, + }); + expect(cacheAfterM0Restore.entry?.provider.models.at(-1)?.slug).toBe("m255"); // A session initialized directly on an overflow model (includeCatalog: true) keeps its // overflow metadata so a superseding probe on m0 retains the overflow model and its options. const choices300 = Array.from({ length: 300 }, (_, index) => ({ @@ -2009,6 +2203,79 @@ describe("prepareAcpRegistryLiveConfiguration", () => { expect(learnedAfterProbe2).toHaveLength(MAX_DISPLACED_LEARNED_MODELS); expect(learnedAfterProbe2[0]?.slug).toBe("old-11"); expect(learnedAfterProbe2.at(-1)?.slug).toBe("m255"); + // An earlier-model overflow entry with preserveDefault does not swap slot 255 or default, + // yet updateAcpRegistryLearnedModelsFromLive still learns its validated options for m256. + const earlierOverflowEntry = { + ...prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m256", choices), + { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v2", + options: [{ value: "v2", name: "V2" }], + }, + ]).toLiveConfiguration({ includeCatalog: false }), + partialOptions: true, + preserveDefault: true, + }; + const afterEarlierOverflow = applyAcpRegistryLiveConfiguration( + cappedProvider, + earlierOverflowEntry, + [], + ); + expect(afterEarlierOverflow.models.at(-1)?.slug).toBe("m255"); + expect(afterEarlierOverflow.models[0]?.isDefault).toBe(true); + const learnedWithEarlierOverflow = updateAcpRegistryLearnedModelsFromLive( + [], + afterEarlierOverflow.models, + earlierOverflowEntry, + ); + expect( + learnedWithEarlierOverflow + .find((m) => m.slug === "m256") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v2"]]); + // Live learning caps total entries at 256 + MAX_DISPLACED_LEARNED_MODELS and refreshes LRU + // order when an unchanged model is observed again so older untouched models evict first. + const maxLiveLearned = ACP_REGISTRY_MAX_MODELS + MAX_DISPLACED_LEARNED_MODELS; + const fullLearned = Array.from({ length: maxLiveLearned }, (_, index) => ({ + slug: `live-${index}`, + name: `Live ${index}`, + isCustom: false, + capabilities: variantCapabilities, + })); + const touchedOldest = updateAcpRegistryLearnedModelsFromLive(fullLearned, [fullLearned[0]!], { + models: [], + currentModelId: "live-0", + configOptions: variantCapabilities.optionDescriptors, + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }); + expect(touchedOldest.at(-1)?.slug).toBe("live-0"); + const afterLiveCap = updateAcpRegistryLearnedModelsFromLive( + touchedOldest, + [ + { + slug: "live-new", + name: "Live New", + isCustom: false, + capabilities: variantCapabilities, + }, + ], + { + models: [], + currentModelId: "live-new", + configOptions: variantCapabilities.optionDescriptors, + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }, + ); + expect(afterLiveCap).toHaveLength(maxLiveLearned); + expect(afterLiveCap.some((m) => m.slug === "live-0")).toBe(true); + expect(afterLiveCap.some((m) => m.slug === "live-1")).toBe(false); + expect(afterLiveCap.at(-1)?.slug).toBe("live-new"); // Toggling an effort selector on a session with a fixed modelState must keep catalogKey // stable (so frozen lists never re-advertise over a newer probe) while projecting newly @@ -4756,6 +5023,57 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .at(-1) ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["variant", "v1"]]); + + // When a probe itself starts on overflow m256 while a live session is on m255, + // probedCappedTailIsOverflow lets m255 stay visible and clears dropped options on update. + const sawM255Selected = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.at(-1)?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m255"), + variantSelect, + ]).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawM255Selected); + yield* writeModels({ + models: modelIds, + configOptions: [...modelSelect("m256")], + }); + yield* TestClock.adjust("16 minutes"); + const probeOverflowWhileLiveM255 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterProbeOverflowWhileLiveM255 = Option.getOrThrow( + yield* Fiber.join(probeOverflowWhileLiveM255), + ); + expect(afterProbeOverflowWhileLiveM255.models.at(-1)?.slug).toBe("m255"); + expect(afterProbeOverflowWhileLiveM255.models.at(-1)?.isDefault).toBe(true); + expect( + afterProbeOverflowWhileLiveM255.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); + const sawVariantCleared = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.at(-1)?.slug === "m255" && + (snapshot.models.at(-1)?.capabilities?.optionDescriptors?.length ?? 0) === 0, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(modelSelect("m255")).toLiveConfiguration({ + includeCatalog: false, + }), + ); + yield* Fiber.join(sawVariantCleared); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index ef03c3eabae7a..a2f2f9d205846 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -230,12 +230,16 @@ export function updateAcpRegistryEnrichmentCache(input: { hasDiscoveredCatalog, }, ); - if (Equal.equals(provider, cache.entry.provider)) return cache; + const overflowTailChanged = + cappedOverflowTailByModels.get(cache.entry.provider.models) !== + cappedOverflowTailByModels.get(provider.models); + if (!overflowTailChanged && Equal.equals(provider, cache.entry.provider)) return cache; const previousBuiltIn = cache.entry.provider.models.filter((model) => !model.isCustom); const nextBuiltIn = provider.models.filter((model) => !model.isCustom); const catalogChanged = configuration.models.length > 0 && - (previousBuiltIn.length !== nextBuiltIn.length || + (overflowTailChanged || + previousBuiltIn.length !== nextBuiltIn.length || nextBuiltIn.some((model, index) => model.slug !== previousBuiltIn[index]?.slug)); return { ...cache, @@ -307,7 +311,7 @@ function readAdvertisedReasoning( : undefined; } -function updateLearnedModelsFromLive( +export function updateAcpRegistryLearnedModelsFromLive( learned: ReadonlyArray, nextModels: ReadonlyArray, configuration: AcpRegistryLiveConfiguration, @@ -319,6 +323,7 @@ function updateLearnedModelsFromLive( learned.filter((model) => !model.isCustom).map((model) => [model.slug, model] as const), ); const configuredById = new Map(configuration.models.map((model) => [model.id, model] as const)); + let lastLearnedSlug = learned.findLast((model) => !model.isCustom)?.slug; let changed = false; for (const model of nextModels) { if (model.isCustom) continue; @@ -349,6 +354,7 @@ function updateLearnedModelsFromLive( if (specific.length === 0) { if (previous !== undefined) { learnedBySlug.delete(model.slug); + if (model.slug === lastLearnedSlug) lastLearnedSlug = undefined; changed = true; } continue; @@ -357,9 +363,65 @@ function updateLearnedModelsFromLive( if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { learnedBySlug.delete(model.slug); learnedBySlug.set(model.slug, updated); + lastLearnedSlug = model.slug; + changed = true; + } else if (model.slug !== lastLearnedSlug) { + learnedBySlug.delete(model.slug); + learnedBySlug.set(model.slug, previous); + lastLearnedSlug = model.slug; changed = true; } } + // Earlier-model retained updates for a capped overflow model do not swap the visible tail, + // but still record their validated model-specific options into learnedModels. + if ( + configuration.preserveDefault === true && + configuration.cappedTailIsOverflow === true && + configuration.cappedLastModel !== undefined && + configuration.cappedPrefixKey !== undefined && + configuration.currentModelId === configuration.cappedLastModel.id && + cappedAcpRegistryModelPrefixKey( + nextModels.filter((model) => !model.isCustom).map((model) => model.slug), + ) === configuration.cappedPrefixKey && + !nextModels.some((model) => !model.isCustom && model.slug === configuration.currentModelId) + ) { + const slug = configuration.cappedLastModel.id; + const isReasoningDisabled = + disabledReasoningSlugs.has(slug) || configuration.cappedLastModel.reasoningEffort === null; + const incoming = configuration.configOptions.filter( + (descriptor) => + isModelSpecificDescriptor(descriptor, modelOptionIds) && + (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), + ); + if (incoming.length > 0) { + const incomingIds = new Set(incoming.map((descriptor) => descriptor.id)); + const previous = learnedBySlug.get(slug); + const preservedPrevious = (previous?.capabilities?.optionDescriptors ?? []).filter( + (descriptor) => + !incomingIds.has(descriptor.id) && + (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), + ); + const updated: ServerProviderModel = { + slug, + name: configuration.cappedLastModel.name, + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [...preservedPrevious, ...incoming], + }), + }; + if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { + learnedBySlug.delete(slug); + learnedBySlug.set(slug, updated); + lastLearnedSlug = slug; + changed = true; + } else if (slug !== lastLearnedSlug) { + learnedBySlug.delete(slug); + learnedBySlug.set(slug, previous); + lastLearnedSlug = slug; + changed = true; + } + } + } const maxLearnedModels = ACP_REGISTRY_MAX_MODELS + MAX_DISPLACED_LEARNED_MODELS; while (learnedBySlug.size > maxLearnedModels) { const oldestKey = learnedBySlug.keys().next().value; @@ -522,7 +584,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( : { advertisedReasoning: retainedAdvertisedReasoning }; const configOptions = [...sharedDescriptors, ...modelDescriptors]; if (configOptions.length === 0) { - // Keep the running session's model selection, overflow swap, or advertised reasoning + // Keep the running session's model selection, capped tail update, or advertised reasoning // even when no active config options survive, unless nothing differs from probe default. if ( matchingCappedTail === undefined && @@ -562,6 +624,10 @@ function mergeLearnedModelOptions( options?: { readonly currentModelId?: string | null; readonly skipModelSlugs?: ReadonlySet; + readonly skipOptionsForModel?: { + readonly slug: string; + readonly optionIds: ReadonlySet; + }; readonly reasoningDisabledModelSlugs?: ReadonlySet; readonly overlayLearnedValues?: boolean; }, @@ -569,6 +635,7 @@ function mergeLearnedModelOptions( if (learned.length === 0) return models; const currentModelId = options?.currentModelId ?? null; const skipModelSlugs = options?.skipModelSlugs ?? EMPTY_SLUG_SET; + const skipOptionsForModel = options?.skipOptionsForModel; const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; const overlayLearnedValues = options?.overlayLearnedValues === true; const learnedBySlug = new Map( @@ -584,8 +651,14 @@ function mergeLearnedModelOptions( ) { return model; } - const previousDescriptors = + const rawPreviousDescriptors = learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; + const previousDescriptors = + skipOptionsForModel !== undefined && skipOptionsForModel.slug === model.slug + ? rawPreviousDescriptors.filter( + (descriptor) => !skipOptionsForModel.optionIds.has(descriptor.id), + ) + : rawPreviousDescriptors; if (previousDescriptors.length === 0) return model; const currentDescriptors = model.capabilities?.optionDescriptors ?? []; const previousById = overlayLearnedValues @@ -1018,6 +1091,7 @@ export function applyAcpRegistryLiveConfiguration( readonly hasDiscoveredCatalog?: boolean | undefined; readonly probeSharedDescriptors?: ReadonlyArray | undefined; readonly probeConfigOptions?: ReadonlyArray | undefined; + readonly providerHasOverflowTail?: boolean | undefined; }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; @@ -1039,6 +1113,7 @@ export function applyAcpRegistryLiveConfiguration( : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); const cappedLastModel = !useLiveCatalog && + configuration.preserveDefault !== true && configuration.currentModelId !== null && configuration.cappedLastModel !== undefined && configuration.cappedPrefixKey !== undefined && @@ -1047,7 +1122,8 @@ export function applyAcpRegistryLiveConfiguration( ? configuration.cappedLastModel : undefined; const currentTailSlug = probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug; - const providerHasOverflowTail = hasCappedOverflowTail(provider.models, currentTailSlug); + const providerHasOverflowTail = + options?.providerHasOverflowTail ?? hasCappedOverflowTail(provider.models, currentTailSlug); const tailSlotReplacement = cappedLastModel !== undefined && currentTailSlug !== cappedLastModel.id && @@ -1078,6 +1154,29 @@ export function applyAcpRegistryLiveConfiguration( if (!useLiveCatalog && configuration.partialOptions === true) { const modelsForOverlay = (() => { if (tailSlotReplacement === undefined) return provider.models; + const partialModelOptionIds = new Set(configuration.modelOptionIds ?? []); + const partialOverrideModelIds = new Set( + configuration.configOptions + .filter((descriptor) => isModelSpecificDescriptor(descriptor, partialModelOptionIds)) + .map((descriptor) => descriptor.id), + ); + const learnedPreviousModels = previousModels + .filter((model) => !model.isCustom) + .map((model) => { + if ( + model.slug !== tailSlotReplacement.id || + partialOverrideModelIds.size === 0 || + !model.capabilities?.optionDescriptors?.length + ) { + return model; + } + const kept = model.capabilities.optionDescriptors.filter( + (descriptor) => !partialOverrideModelIds.has(descriptor.id), + ); + return kept.length === model.capabilities.optionDescriptors.length + ? model + : modelWithSpecificOptions(model, kept); + }); const replacementBuiltIn = modelsFromDiscovery( { models: [tailSlotReplacement], @@ -1085,20 +1184,17 @@ export function applyAcpRegistryLiveConfiguration( configOptions: options?.probeSharedDescriptors ?? [], }, [], - previousModels.filter((model) => !model.isCustom), + learnedPreviousModels, )[0]!; const nextBuiltInModels = probedModels.map((model, index) => index === ACP_REGISTRY_MAX_MODELS - 1 ? replacementBuiltIn : model, ); + const fallbackCustomDescriptors = + options?.probeConfigOptions ?? options?.probeSharedDescriptors ?? []; const customModelCapabilities = - options?.probeConfigOptions !== undefined - ? options.probeConfigOptions.length === 0 - ? EMPTY_CAPABILITIES - : createModelCapabilities({ optionDescriptors: options.probeConfigOptions }) - : (provider.models.find((model) => model.isCustom)?.capabilities ?? - (options?.probeSharedDescriptors && options.probeSharedDescriptors.length > 0 - ? createModelCapabilities({ optionDescriptors: options.probeSharedDescriptors }) - : EMPTY_CAPABILITIES)); + fallbackCustomDescriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: fallbackCustomDescriptors }); return providerModelsFromSettings(nextBuiltInModels, customModels, customModelCapabilities); })(); const partialDisabledReasoning = @@ -1589,6 +1685,15 @@ export const AcpRegistryDriver: ProviderDriver model.slug !== configuration.currentModelId) : basePrevious; + const currentTailSlug = provider.models + .filter((model) => !model.isCustom) + .at(ACP_REGISTRY_MAX_MODELS - 1)?.slug; + const providerHasOverflowTail = + accepted.probeOptions === null && + accepted.models.length > 0 && + Equal.equals(provider.models, accepted.models) + ? hasCappedOverflowTail(accepted.models, currentTailSlug) + : undefined; const next = applyAcpRegistryLiveConfiguration( provider, configuration, @@ -1600,11 +1705,12 @@ export const AcpRegistryDriver: ProviderDriver { + if (replacedLiveModelId !== null || Option.isNone(effectiveConfiguration)) { + return undefined; + } + const partial = effectiveConfiguration.value; + if (partial.currentModelId === null) return undefined; + const partialModelOptionIds = new Set(partial.modelOptionIds ?? []); + const optionIds = new Set( + partial.configOptions + .filter((descriptor) => + isModelSpecificDescriptor(descriptor, partialModelOptionIds), + ) + .map((descriptor) => descriptor.id), + ); + return optionIds.size > 0 ? { slug: partial.currentModelId, optionIds } : undefined; + })(); // Rebuild from the pure probe baseline so rejected values restore probe defaults, // other models preserve learned values, and dropped options on the reporting model clear. const pureBaseline = acceptedBefore.probeBaselineModels ?? acceptedBefore.models; @@ -1673,6 +1795,7 @@ export const AcpRegistryDriver: ProviderDriver mergeLearnedModelOptions(pureBaseline, learned, { skipModelSlugs, + ...(skipOptionsForModel === undefined ? {} : { skipOptionsForModel }), reasoningDisabledModelSlugs, overlayLearnedValues: true, }), @@ -1688,7 +1811,7 @@ export const AcpRegistryDriver: ProviderDriver - updateLearnedModelsFromLive( + updateAcpRegistryLearnedModelsFromLive( learned, baselineProvider.models, { From 394758e2bff7b27f7e31eb3a862a62990727efda Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 15:51:48 +0000 Subject: [PATCH 18/35] fix(acp-registry): handle displaced ordinary tails, catalog reasoning merges, and bidirectional overflow tag sync --- .../AcpRegistryRuntimeCoordinator.test.ts | 93 ++++++- .../server/AcpRegistryRuntimeCoordinator.ts | 85 +++--- .../src/server/driver.test.ts | 256 +++++++++++++++++- .../src/server/driver.ts | 112 ++++---- 4 files changed, 462 insertions(+), 84 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 1d501454cce83..c0acbda2c6e7d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -766,9 +766,47 @@ describe("AcpRegistryRuntimeCoordinator", () => { "model-b": highEffort, }); - // An earlier overflow model update keeps its overflow metadata alongside preserveDefault - // so the driver can learn its options on replay without swapping slot 255 or default. + // A same-model options-only update for model-a overrides model-a's own options without + // discarding model-b's compatible reasoning metadata from the catalog on clear. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: highEffort }, + { id: "model-c", name: "Model C", description: null, reasoningEffort: null }, + ], + currentModelId: "model-a", + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: true, + }); + const sameModelCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: sameModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterSameModelClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(afterSameModelClear.pendingOptions).toHaveLength(1); + expect(afterSameModelClear.pendingOptions[0]?.configuration.configOptions).toEqual([ + modeOption("ask"), + ]); + expect(afterSameModelClear.pendingOptions[0]?.configuration.advertisedReasoning).toEqual({ + "model-b": highEffort, + }); + + // Earlier displaced tail updates (both overflow m256 and displaced ordinary tail m255) + // keep their tail metadata alongside preserveDefault so the driver can learn their options + // off-screen without swapping slot 255 or default, while non-tail models (m1) drop it. const overflowModel = { id: "m256", name: "Model 256", description: null }; + const ordinaryTailModel = { id: "m255", name: "Model 255", description: null }; yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "m256", @@ -780,6 +818,26 @@ describe("AcpRegistryRuntimeCoordinator", () => { cappedTailIsOverflow: true, }); const overflowSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "m255", + configOptions: [modeOption("code"), variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + cappedPrefixKey: "prefix-255", + cappedLastModel: ordinaryTailModel, + }); + const ordinaryTailSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "m1", + configOptions: [variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + cappedPrefixKey: "prefix-255", + cappedLastModel: ordinaryTailModel, + }); + const nonTailSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "m0", @@ -787,11 +845,11 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelOptionIds: [], modelsFromModelSelect: false, cappedPrefixKey: "prefix-255", - cappedLastModel: { id: "m255", name: "Model 255", description: null }, + cappedLastModel: ordinaryTailModel, }); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: reasoningCatalog.catalogRevision, + catalogRevision: sameModelCatalog.catalogRevision, retain: (live) => Option.some({ ...live, partialOptions: true }), }), ).toBe(true); @@ -812,6 +870,33 @@ describe("AcpRegistryRuntimeCoordinator", () => { cappedLastModel: overflowModel, cappedTailIsOverflow: true, }); + expect( + afterOverflowClear.pendingOptions.find( + (entry) => entry.revision === ordinaryTailSnap.revision, + )?.configuration, + ).toEqual({ + models: [], + currentModelId: "m255", + configOptions: [variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + cappedPrefixKey: "prefix-255", + cappedLastModel: ordinaryTailModel, + }); + expect( + afterOverflowClear.pendingOptions.find((entry) => entry.revision === nonTailSnap.revision) + ?.configuration, + ).toEqual({ + models: [], + currentModelId: "m1", + configOptions: [variantOption], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + }); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index d454106a024c5..2ddbc5fb7f6ad 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -326,35 +326,57 @@ const make = Effect.gen(function* () { AcpRegistryRevisionedLiveConfiguration > = (() => { if (retain === undefined) return EMPTY_OPTIONS_BY_MODEL; + const extractAdvertisedReasoning = ( + configuration: AcpRegistryLiveConfiguration, + ): AcpRegistryLiveConfiguration["advertisedReasoning"] => { + if (configuration.advertisedReasoning !== undefined) { + return configuration.advertisedReasoning; + } + const entries: Array< + readonly [ + string, + NonNullable, + ] + > = []; + for (const model of configuration.models) { + if (model.id !== configuration.currentModelId && model.reasoningEffort != null) { + entries.push([model.id, model.reasoningEffort]); + } + } + return entries.length > 0 ? Object.fromEntries(entries) : undefined; + }; const candidates = new Map(); + const catalogReasoning = + current.catalog === null + ? undefined + : extractAdvertisedReasoning(current.catalog.configuration); if (current.catalog !== null) { candidates.set(current.catalog.configuration.currentModelId, current.catalog); } for (const [key, entry] of current.optionsByModel) { + if ( + catalogReasoning !== undefined && + current.catalog !== null && + key === current.catalog.configuration.currentModelId + ) { + const mergedAdvertisedReasoning = { + ...catalogReasoning, + ...entry.configuration.advertisedReasoning, + }; + candidates.set(key, { + revision: entry.revision, + configuration: { + ...entry.configuration, + advertisedReasoning: mergedAdvertisedReasoning, + }, + }); + continue; + } candidates.set(key, entry); } const retained = new Map(); for (const entry of sortedPendingOptions(candidates)) { - const catalogAdvertisedReasoning = (() => { - if (entry.configuration.advertisedReasoning !== undefined) { - return entry.configuration.advertisedReasoning; - } - const entries: Array< - readonly [ - string, - NonNullable, - ] - > = []; - for (const model of entry.configuration.models) { - if ( - model.id !== entry.configuration.currentModelId && - model.reasoningEffort != null - ) { - entries.push([model.id, model.reasoningEffort]); - } - } - return entries.length > 0 ? Object.fromEntries(entries) : undefined; - })(); + const catalogAdvertisedReasoning = extractAdvertisedReasoning(entry.configuration); const kept = retain({ ...entry.configuration, models: [], @@ -365,8 +387,8 @@ const make = Effect.gen(function* () { }); if (Option.isNone(kept)) continue; if (entry.revision < current.revision) { - // Earlier models keep only model-specific options and advertised reasoning - // without stealing default selection or shared options. + // Earlier models keep only model-specific options, advertised reasoning, and + // displaced-tail metadata without stealing default selection or shared options. const modelOptionIds = new Set(kept.value.modelOptionIds ?? []); const modelOnlyOptions = kept.value.configOptions.filter((descriptor) => modelOptionIds.has(descriptor.id), @@ -375,18 +397,13 @@ const make = Effect.gen(function* () { kept.value.advertisedReasoning !== undefined && Object.keys(kept.value.advertisedReasoning).length > 0; if (modelOnlyOptions.length === 0 && !hasAdvertisedReasoning) continue; - const keepOverflowModel = - kept.value.cappedTailIsOverflow === true && + const keepDisplacedTailModel = kept.value.cappedLastModel !== undefined && kept.value.cappedPrefixKey !== undefined && kept.value.cappedLastModel.id === kept.value.currentModelId && modelOnlyOptions.length > 0; - const { - cappedLastModel, - cappedPrefixKey, - cappedTailIsOverflow: _droppedOverflowFlag, - ...rest - } = kept.value; + const { cappedLastModel, cappedPrefixKey, cappedTailIsOverflow, ...rest } = + kept.value; retained.delete(kept.value.currentModelId); retained.set(kept.value.currentModelId, { configuration: { @@ -394,8 +411,12 @@ const make = Effect.gen(function* () { configOptions: modelOnlyOptions, modelOptionIds: modelOnlyOptions.map((descriptor) => descriptor.id), preserveDefault: true, - ...(keepOverflowModel - ? { cappedPrefixKey, cappedLastModel, cappedTailIsOverflow: true } + ...(keepDisplacedTailModel + ? { + cappedPrefixKey, + cappedLastModel, + ...(cappedTailIsOverflow === true ? { cappedTailIsOverflow: true } : {}), + } : {}), }, revision: entry.revision, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 6281db7444fe8..09af3481113d7 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2237,8 +2237,71 @@ describe("prepareAcpRegistryLiveConfiguration", () => { .find((m) => m.slug === "m256") ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["variant", "v2"]]); - // Live learning caps total entries at 256 + MAX_DISPLACED_LEARNED_MODELS and refreshes LRU - // order when an unchanged model is observed again so older untouched models evict first. + // Displaced ordinary tail (m255 when probe started on overflow m256) is also learned + // off-screen without swapping slot 255 or stealing default. + const earlierOrdinaryTailEntry = { + ...prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m255", choices), + { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v2", + options: [{ value: "v2", name: "V2" }], + }, + ]).toLiveConfiguration({ includeCatalog: false }), + partialOptions: true, + preserveDefault: true, + }; + const afterEarlierOrdinaryTail = applyAcpRegistryLiveConfiguration( + probeOverflowSnapshot, + earlierOrdinaryTailEntry, + [], + ); + expect(afterEarlierOrdinaryTail.models.at(-1)?.slug).toBe("m256"); + expect(afterEarlierOrdinaryTail.models.at(-1)?.isDefault).toBe(true); + const learnedWithEarlierOrdinaryTail = updateAcpRegistryLearnedModelsFromLive( + [], + afterEarlierOrdinaryTail.models, + earlierOrdinaryTailEntry, + ); + expect( + learnedWithEarlierOrdinaryTail + .find((m) => m.slug === "m255") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v2"]]); + // Live learning caps total entries at 256 + MAX_DISPLACED_LEARNED_MODELS, refreshes LRU + // order when an unchanged model is observed again, and avoids rebuilding when order matches. + const stableEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; + const stableModels = ["a", "b", "c"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { optionDescriptors: [stableEffort] }, + })); + const stableCfg = { + models: [], + currentModelId: "a", + configOptions: [stableEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + advertisedReasoning: { b: stableEffort, c: stableEffort }, + }; + const stableLearned = updateAcpRegistryLearnedModelsFromLive([], stableModels, stableCfg); + expect(updateAcpRegistryLearnedModelsFromLive(stableLearned, stableModels, stableCfg)).toBe( + stableLearned, + ); const maxLiveLearned = ACP_REGISTRY_MAX_MODELS + MAX_DISPLACED_LEARNED_MODELS; const fullLearned = Array.from({ length: maxLiveLearned }, (_, index) => ({ slug: `live-${index}`, @@ -5074,6 +5137,101 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); yield* Fiber.join(sawVariantCleared); + + // Sync overflow-tail tag with acceptedCatalog in both directions when managedProvider + // deduplicates a structurally equal catalog publish ([m0..m254, m256]). + const fullChoices = modelIds.map((value, index) => ({ value, name: `Model ${index}` })); + const withoutM255Choices = fullChoices.filter((choice) => choice.value !== "m255"); + const selectFrom = ( + currentValue: string, + options: ReadonlyArray<{ value: string; name: string }>, + ) => [ + { + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: [...options], + }, + ]; + // Untagged base m256 -> tagged overflow m256 (deduplicated) -> m0 must restore m255. + const sawBaseM256 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.at(-1)?.slug === "m256"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m256", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: true }), + ); + yield* Fiber.join(sawBaseM256); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m256", fullChoices)).toLiveConfiguration({ + includeCatalog: true, + }), + ); + const sawRestoredM255 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[0]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m0", fullChoices)).toLiveConfiguration({ + includeCatalog: false, + }), + ); + expect(Option.getOrThrow(yield* Fiber.join(sawRestoredM255)).models.at(-1)?.slug).toBe( + "m255", + ); + + // Tagged overflow m256 -> untagged base m256 (deduplicated) -> m0 -> stale C1 m1 keeps m256. + const sawOverflowM256 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.at(-1)?.slug === "m256"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m256", fullChoices)).toLiveConfiguration({ + includeCatalog: true, + }), + ); + yield* Fiber.join(sawOverflowM256); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m256", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: true }), + ); + const sawUntaggedM0 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[0]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m0", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: false }), + ); + yield* Fiber.join(sawUntaggedM0); + const sawUntaggedM1 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[1]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m1", fullChoices)).toLiveConfiguration({ + includeCatalog: false, + }), + ); + expect(Option.getOrThrow(yield* Fiber.join(sawUntaggedM1)).models.at(-1)?.slug).toBe("m256"); }), ); @@ -5092,11 +5250,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { let blockWatcher = false; let gateAfterCacheRead = false; let trackCacheHitCommit = false; + let beforeClearHook: Effect.Effect | null = null; const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-multi-clear-", initialModels: ["model-a", "model-b"], wrapCoordinator: (base) => ({ ...base, + clearLiveConfigurationIfRevision: (instanceId, options) => { + const hook = beforeClearHook; + beforeClearHook = null; + return (hook ?? Effect.void).pipe( + Effect.andThen(base.clearLiveConfigurationIfRevision(instanceId, options)), + ); + }, getUrlAuthAction: (instanceId) => (trackCacheHitCommit ? Effect.sync(() => { @@ -5267,6 +5433,92 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["effort", "high"]]); + // Pre-learn effort=[low] on model-b, then run a superseding probe without reasoning on + // model-b while blocked updates widen model-b's variant to [v1, v2] (v2) and advertise + // effort=[high] on model-b; older learned schemas must not reject either retained update. + const effortLowOnly = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "low", + options: [{ id: "low", label: "Low" }], + }; + const effortHighOnly = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "high", + options: [{ id: "high", label: "High" }], + }; + const variantWidened = { + id: "variant", + label: "Variant", + type: "select" as const, + currentValue: "v2", + options: [ + { id: "v1", label: "V1" }, + { id: "v2", label: "V2" }, + ], + }; + const sawLearnedBLow = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [effortOpt("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": effortLowOnly }, + }); + yield* Fiber.join(sawLearnedBLow); + + yield* writeModels(["model-a", "model-b"]); + yield* TestClock.adjust("16 minutes"); + beforeClearHook = coordinator + .publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [variantWidened], + modelOptionIds: ["variant"], + modelsFromModelSelect: false, + }) + .pipe( + Effect.andThen( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": effortHighOnly }, + }), + ), + ); + const secondProbeDone = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterWidenedProbe = Option.getOrThrow(yield* Fiber.join(secondProbeDone)); + expect( + afterWidenedProbe.models + .find((m) => m.slug === "model-b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["variant", "v2"], + ["effort", "high"], + ]); + // Verify a cache-hit commit (probeOptions=null) whose watcher applies effort=high after // enrichProviderCached reads effort=low still publishes effort=high rather than reverting. const sawFreshCatalog = yield* instance.snapshot.streamChanges.pipe( diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index a2f2f9d205846..4406dba615d18 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -324,7 +324,8 @@ export function updateAcpRegistryLearnedModelsFromLive( ); const configuredById = new Map(configuration.models.map((model) => [model.id, model] as const)); let lastLearnedSlug = learned.findLast((model) => !model.isCustom)?.slug; - let changed = false; + let dataChanged = false; + let orderTouched = false; for (const model of nextModels) { if (model.isCustom) continue; const isCurrentModel = @@ -355,7 +356,7 @@ export function updateAcpRegistryLearnedModelsFromLive( if (previous !== undefined) { learnedBySlug.delete(model.slug); if (model.slug === lastLearnedSlug) lastLearnedSlug = undefined; - changed = true; + dataChanged = true; } continue; } @@ -364,19 +365,18 @@ export function updateAcpRegistryLearnedModelsFromLive( learnedBySlug.delete(model.slug); learnedBySlug.set(model.slug, updated); lastLearnedSlug = model.slug; - changed = true; + dataChanged = true; } else if (model.slug !== lastLearnedSlug) { learnedBySlug.delete(model.slug); learnedBySlug.set(model.slug, previous); lastLearnedSlug = model.slug; - changed = true; + orderTouched = true; } } - // Earlier-model retained updates for a capped overflow model do not swap the visible tail, - // but still record their validated model-specific options into learnedModels. + // Earlier-model retained updates for a displaced capped tail do not swap the visible tail, + // but still record their retained model-specific options into learnedModels. if ( configuration.preserveDefault === true && - configuration.cappedTailIsOverflow === true && configuration.cappedLastModel !== undefined && configuration.cappedPrefixKey !== undefined && configuration.currentModelId === configuration.cappedLastModel.id && @@ -413,12 +413,12 @@ export function updateAcpRegistryLearnedModelsFromLive( learnedBySlug.delete(slug); learnedBySlug.set(slug, updated); lastLearnedSlug = slug; - changed = true; + dataChanged = true; } else if (slug !== lastLearnedSlug) { learnedBySlug.delete(slug); learnedBySlug.set(slug, previous); lastLearnedSlug = slug; - changed = true; + orderTouched = true; } } } @@ -427,9 +427,24 @@ export function updateAcpRegistryLearnedModelsFromLive( const oldestKey = learnedBySlug.keys().next().value; if (oldestKey === undefined) break; learnedBySlug.delete(oldestKey); - changed = true; + dataChanged = true; } - return changed ? Array.from(learnedBySlug.values()) : learned; + if (!dataChanged) { + if (!orderTouched) return learned; + if (learnedBySlug.size === learned.length) { + let index = 0; + let sameOrder = true; + for (const slug of learnedBySlug.keys()) { + if (learned[index]?.slug !== slug) { + sameOrder = false; + break; + } + index += 1; + } + if (sameOrder) return learned; + } + } + return Array.from(learnedBySlug.values()); } function compatibleLiveOptionValue( @@ -624,10 +639,7 @@ function mergeLearnedModelOptions( options?: { readonly currentModelId?: string | null; readonly skipModelSlugs?: ReadonlySet; - readonly skipOptionsForModel?: { - readonly slug: string; - readonly optionIds: ReadonlySet; - }; + readonly skipOptionIdsByModel?: ReadonlyMap>; readonly reasoningDisabledModelSlugs?: ReadonlySet; readonly overlayLearnedValues?: boolean; }, @@ -635,7 +647,7 @@ function mergeLearnedModelOptions( if (learned.length === 0) return models; const currentModelId = options?.currentModelId ?? null; const skipModelSlugs = options?.skipModelSlugs ?? EMPTY_SLUG_SET; - const skipOptionsForModel = options?.skipOptionsForModel; + const skipOptionIdsByModel = options?.skipOptionIdsByModel; const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; const overlayLearnedValues = options?.overlayLearnedValues === true; const learnedBySlug = new Map( @@ -653,11 +665,10 @@ function mergeLearnedModelOptions( } const rawPreviousDescriptors = learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; + const skippedOptionIds = skipOptionIdsByModel?.get(model.slug); const previousDescriptors = - skipOptionsForModel !== undefined && skipOptionsForModel.slug === model.slug - ? rawPreviousDescriptors.filter( - (descriptor) => !skipOptionsForModel.optionIds.has(descriptor.id), - ) + skippedOptionIds !== undefined + ? rawPreviousDescriptors.filter((descriptor) => !skippedOptionIds.has(descriptor.id)) : rawPreviousDescriptors; if (previousDescriptors.length === 0) return model; const currentDescriptors = model.capabilities?.optionDescriptors ?? []; @@ -1091,7 +1102,6 @@ export function applyAcpRegistryLiveConfiguration( readonly hasDiscoveredCatalog?: boolean | undefined; readonly probeSharedDescriptors?: ReadonlyArray | undefined; readonly probeConfigOptions?: ReadonlyArray | undefined; - readonly providerHasOverflowTail?: boolean | undefined; }, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; @@ -1122,8 +1132,7 @@ export function applyAcpRegistryLiveConfiguration( ? configuration.cappedLastModel : undefined; const currentTailSlug = probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug; - const providerHasOverflowTail = - options?.providerHasOverflowTail ?? hasCappedOverflowTail(provider.models, currentTailSlug); + const providerHasOverflowTail = hasCappedOverflowTail(provider.models, currentTailSlug); const tailSlotReplacement = cappedLastModel !== undefined && currentTailSlug !== cappedLastModel.id && @@ -1685,17 +1694,16 @@ export const AcpRegistryDriver: ProviderDriver model.slug !== configuration.currentModelId) : basePrevious; - const currentTailSlug = provider.models - .filter((model) => !model.isCustom) - .at(ACP_REGISTRY_MAX_MODELS - 1)?.slug; - const providerHasOverflowTail = + // Sync models array identity with acceptedCatalog when managedProvider deduplicated + // a structurally equal snapshot whose overflow-tail tag changed. + const syncedProvider = accepted.probeOptions === null && accepted.models.length > 0 && Equal.equals(provider.models, accepted.models) - ? hasCappedOverflowTail(accepted.models, currentTailSlug) - : undefined; + ? { ...provider, models: accepted.models } + : provider; const next = applyAcpRegistryLiveConfiguration( - provider, + syncedProvider, configuration, effectiveConfig.customModels, previousModels, @@ -1705,7 +1713,6 @@ export const AcpRegistryDriver: ProviderDriver { - if (replacedLiveModelId !== null || Option.isNone(effectiveConfiguration)) { - return undefined; - } + const skipOptionIdsByModel = (() => { + if (Option.isNone(effectiveConfiguration)) return undefined; const partial = effectiveConfiguration.value; - if (partial.currentModelId === null) return undefined; - const partialModelOptionIds = new Set(partial.modelOptionIds ?? []); - const optionIds = new Set( - partial.configOptions - .filter((descriptor) => - isModelSpecificDescriptor(descriptor, partialModelOptionIds), - ) - .map((descriptor) => descriptor.id), - ); - return optionIds.size > 0 ? { slug: partial.currentModelId, optionIds } : undefined; + const byModel = new Map>(); + const add = (slug: string, optionId: string) => { + let ids = byModel.get(slug); + if (ids === undefined) { + ids = new Set(); + byModel.set(slug, ids); + } + ids.add(optionId); + }; + if (replacedLiveModelId === null && partial.currentModelId !== null) { + const partialModelOptionIds = new Set(partial.modelOptionIds ?? []); + for (const descriptor of partial.configOptions) { + if (isModelSpecificDescriptor(descriptor, partialModelOptionIds)) { + add(partial.currentModelId, descriptor.id); + } + } + } + if (partial.advertisedReasoning !== undefined) { + for (const [slug, descriptor] of Object.entries(partial.advertisedReasoning)) { + if (slug !== replacedLiveModelId) { + add(slug, descriptor.id); + } + } + } + return byModel.size > 0 ? byModel : undefined; })(); // Rebuild from the pure probe baseline so rejected values restore probe defaults, // other models preserve learned values, and dropped options on the reporting model clear. @@ -1795,7 +1815,7 @@ export const AcpRegistryDriver: ProviderDriver mergeLearnedModelOptions(pureBaseline, learned, { skipModelSlugs, - ...(skipOptionsForModel === undefined ? {} : { skipOptionsForModel }), + ...(skipOptionIdsByModel === undefined ? {} : { skipOptionIdsByModel }), reasoningDisabledModelSlugs, overlayLearnedValues: true, }), From b9d67a734f366b7db52fb7552222416f1edbfb78 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 16:16:14 +0000 Subject: [PATCH 19/35] fix(acp-registry): scope tail option stripping, isolate overflow-tag sync to watcher, and guard catalog reasoning merge --- .../AcpRegistryRuntimeCoordinator.test.ts | 36 ++++-- .../server/AcpRegistryRuntimeCoordinator.ts | 67 ++++++----- .../src/server/driver.test.ts | 108 ++++++++++++++++++ .../src/server/driver.ts | 54 +++++---- .../provider-acp-registry/src/server/probe.ts | 30 +++-- packages/provider-acp/src/server/adapter.ts | 4 +- 6 files changed, 229 insertions(+), 70 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index c0acbda2c6e7d..821ec93276cd4 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -767,12 +767,14 @@ describe("AcpRegistryRuntimeCoordinator", () => { }); // A same-model options-only update for model-a overrides model-a's own options without - // discarding model-b's compatible reasoning metadata from the catalog on clear. + // discarding catalog reasoning for untouched models (model-c), while never carrying older + // catalog reasoning over a model updated at an intervening revision (model-b). + const lowEffort = effortOption("low"); yield* coordinator.publishLiveConfiguration(instanceId, { models: [ { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, - { id: "model-b", name: "Model B", description: null, reasoningEffort: highEffort }, - { id: "model-c", name: "Model C", description: null, reasoningEffort: null }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: lowEffort }, + { id: "model-c", name: "Model C", description: null, reasoningEffort: lowEffort }, ], currentModelId: "model-a", configOptions: [effortOption("high")], @@ -780,6 +782,14 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: true, }); const sameModelCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [highEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const modelBHigherSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "model-a", @@ -794,12 +804,24 @@ describe("AcpRegistryRuntimeCoordinator", () => { }), ).toBe(true); const afterSameModelClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); - expect(afterSameModelClear.pendingOptions).toHaveLength(1); - expect(afterSameModelClear.pendingOptions[0]?.configuration.configOptions).toEqual([ + expect(afterSameModelClear.pendingOptions).toHaveLength(2); + expect(afterSameModelClear.pendingOptions[0]).toEqual({ + revision: modelBHigherSnap.revision, + configuration: { + models: [], + currentModelId: "model-b", + configOptions: [highEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + }, + }); + expect(afterSameModelClear.pendingOptions[1]?.configuration.configOptions).toEqual([ modeOption("ask"), ]); - expect(afterSameModelClear.pendingOptions[0]?.configuration.advertisedReasoning).toEqual({ - "model-b": highEffort, + expect(afterSameModelClear.pendingOptions[1]?.configuration.advertisedReasoning).toEqual({ + "model-c": lowEffort, }); // Earlier displaced tail updates (both overflow m256 and displaced ordinary tail m255) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 2ddbc5fb7f6ad..90b38ea1e43f4 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -16,7 +16,20 @@ import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; -import type { AcpRegistryAvailableCommands, AcpRegistryLiveConfiguration } from "./probe.ts"; +import { + extractAcpRegistryAdvertisedReasoning, + type AcpRegistryAvailableCommands, + type AcpRegistryLiveConfiguration, +} from "./probe.ts"; + +function extractAdvertisedReasoning( + configuration: AcpRegistryLiveConfiguration, +): AcpRegistryLiveConfiguration["advertisedReasoning"] { + return ( + configuration.advertisedReasoning ?? + extractAcpRegistryAdvertisedReasoning(configuration.models, configuration.currentModelId) + ); +} interface AvailableCommandsUpdate { readonly instanceId: ProviderInstanceId; @@ -326,32 +339,25 @@ const make = Effect.gen(function* () { AcpRegistryRevisionedLiveConfiguration > = (() => { if (retain === undefined) return EMPTY_OPTIONS_BY_MODEL; - const extractAdvertisedReasoning = ( - configuration: AcpRegistryLiveConfiguration, - ): AcpRegistryLiveConfiguration["advertisedReasoning"] => { - if (configuration.advertisedReasoning !== undefined) { - return configuration.advertisedReasoning; - } - const entries: Array< - readonly [ - string, - NonNullable, - ] - > = []; - for (const model of configuration.models) { - if (model.id !== configuration.currentModelId && model.reasoningEffort != null) { - entries.push([model.id, model.reasoningEffort]); - } - } - return entries.length > 0 ? Object.fromEntries(entries) : undefined; - }; const candidates = new Map(); const catalogReasoning = current.catalog === null ? undefined : extractAdvertisedReasoning(current.catalog.configuration); + const modelsUpdatedAfterCatalog = new Set(); if (current.catalog !== null) { candidates.set(current.catalog.configuration.currentModelId, current.catalog); + for (const entry of current.optionsByModel.values()) { + if (entry.revision <= current.catalog.revision) continue; + if (entry.configuration.currentModelId !== null) { + modelsUpdatedAfterCatalog.add(entry.configuration.currentModelId); + } + if (entry.configuration.advertisedReasoning !== undefined) { + for (const slug of Object.keys(entry.configuration.advertisedReasoning)) { + modelsUpdatedAfterCatalog.add(slug); + } + } + } } for (const [key, entry] of current.optionsByModel) { if ( @@ -359,15 +365,23 @@ const make = Effect.gen(function* () { current.catalog !== null && key === current.catalog.configuration.currentModelId ) { - const mergedAdvertisedReasoning = { - ...catalogReasoning, - ...entry.configuration.advertisedReasoning, - }; + const preservedCatalogEntries = Object.entries(catalogReasoning).filter( + ([slug]) => !modelsUpdatedAfterCatalog.has(slug), + ); + const mergedAdvertisedReasoning = + preservedCatalogEntries.length === 0 + ? entry.configuration.advertisedReasoning + : { + ...Object.fromEntries(preservedCatalogEntries), + ...entry.configuration.advertisedReasoning, + }; candidates.set(key, { revision: entry.revision, configuration: { ...entry.configuration, - advertisedReasoning: mergedAdvertisedReasoning, + ...(mergedAdvertisedReasoning === undefined + ? {} + : { advertisedReasoning: mergedAdvertisedReasoning }), }, }); continue; @@ -400,8 +414,7 @@ const make = Effect.gen(function* () { const keepDisplacedTailModel = kept.value.cappedLastModel !== undefined && kept.value.cappedPrefixKey !== undefined && - kept.value.cappedLastModel.id === kept.value.currentModelId && - modelOnlyOptions.length > 0; + kept.value.cappedLastModel.id === kept.value.currentModelId; const { cappedLastModel, cappedPrefixKey, cappedTailIsOverflow, ...rest } = kept.value; retained.delete(kept.value.currentModelId); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 09af3481113d7..de6ba81a800ab 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2271,6 +2271,41 @@ describe("prepareAcpRegistryLiveConfiguration", () => { .find((m) => m.slug === "m255") ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["variant", "v2"]]); + // Restoring m255 into slot 255 while a different model (m0) is current with its own + // `variant` option must keep m255's off-screen learned `variant=v2` intact. + const m0RestoringM255 = { + ...prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m0", choices), + { + id: "variant", + name: "Variant", + category: "model_config" as const, + type: "select" as const, + currentValue: "v1", + options: [{ value: "v1", name: "V1" }], + }, + ]).toLiveConfiguration({ includeCatalog: false }), + partialOptions: true, + }; + const afterM0RestoredM255 = applyAcpRegistryLiveConfiguration( + probeOverflowSnapshot, + m0RestoringM255, + [], + learnedWithEarlierOrdinaryTail, + ); + expect(afterM0RestoredM255.models.at(-1)?.slug).toBe("m255"); + expect(afterM0RestoredM255.models[0]?.isDefault).toBe(true); + expect( + afterM0RestoredM255.models[0]?.capabilities?.optionDescriptors?.map((d) => [ + d.id, + d.currentValue, + ]), + ).toEqual([["variant", "v1"]]); + expect( + afterM0RestoredM255.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v2"]]); // Live learning caps total entries at 256 + MAX_DISPLACED_LEARNED_MODELS, refreshes LRU // order when an unchanged model is observed again, and avoids rebuilding when order matches. const stableEffort = { @@ -4913,12 +4948,43 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { options: [{ value: "v1", name: "V1" }], }; + let blockOverflowWatcher = false; + const releaseOverflowWatcher = yield* Deferred.make(); + let afterOverflowCacheReadHook: Effect.Effect | null = null; const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-overflow-post-probe-", initialModels: { models: modelIds, configOptions: [...modelSelect("m0"), effortSelect("low")], }, + wrapCoordinator: (base) => ({ + ...base, + runBackgroundProbe: (agentId, effect) => + base.runBackgroundProbe( + agentId, + effect.pipe( + Effect.tap(() => { + const hook = afterOverflowCacheReadHook; + afterOverflowCacheReadHook = null; + return hook ?? Effect.void; + }), + ), + ), + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + blockOverflowWatcher + ? Effect.sync(() => { + blockOverflowWatcher = false; + }).pipe( + Effect.andThen(Deferred.await(releaseOverflowWatcher)), + Effect.andThen(onUpdate(configuration, revision)), + ) + : onUpdate(configuration, revision), + options, + ), + }), }); const initial = yield* waitForEnriched().pipe(Effect.forkScoped({ startImmediately: true })); @@ -5232,6 +5298,48 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); expect(Option.getOrThrow(yield* Fiber.join(sawUntaggedM1)).models.at(-1)?.slug).toBe("m256"); + + // Non-recording replay during commitEnrichment must not revert a freshly tagged catalog + // back to an older untagged acceptedCatalog entry before replaying a follow-up m0 update. + const sawBaseM256BeforeReplay = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.at(-1)?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m256", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: true }), + ); + yield* Fiber.join(sawBaseM256BeforeReplay); + const firstM0DuringCommit = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[0]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + blockOverflowWatcher = true; + afterOverflowCacheReadHook = coordinator + .publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m256", fullChoices)).toLiveConfiguration({ + includeCatalog: true, + }), + ) + .pipe( + Effect.andThen( + coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m0", fullChoices), + ).toLiveConfiguration({ includeCatalog: false }), + ), + ), + ); + yield* instance.snapshot.refresh; + const replayedM0 = Option.getOrThrow(yield* Fiber.join(firstM0DuringCommit)); + expect(replayedM0.models.at(-1)?.slug).toBe("m255"); + yield* Deferred.succeed(releaseOverflowWatcher, undefined); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 4406dba615d18..9f45c5eb94109 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1163,24 +1163,35 @@ export function applyAcpRegistryLiveConfiguration( if (!useLiveCatalog && configuration.partialOptions === true) { const modelsForOverlay = (() => { if (tailSlotReplacement === undefined) return provider.models; - const partialModelOptionIds = new Set(configuration.modelOptionIds ?? []); - const partialOverrideModelIds = new Set( - configuration.configOptions - .filter((descriptor) => isModelSpecificDescriptor(descriptor, partialModelOptionIds)) - .map((descriptor) => descriptor.id), - ); + const partialOverrideIds = new Set(); + if (configuration.currentModelId === tailSlotReplacement.id) { + const partialModelOptionIds = new Set(configuration.modelOptionIds ?? []); + for (const descriptor of configuration.configOptions) { + if (isModelSpecificDescriptor(descriptor, partialModelOptionIds)) { + partialOverrideIds.add(descriptor.id); + } + } + } else { + const advertisedForTail = readAdvertisedReasoning( + configuration.advertisedReasoning, + tailSlotReplacement.id, + ); + if (advertisedForTail !== undefined) { + partialOverrideIds.add(advertisedForTail.id); + } + } const learnedPreviousModels = previousModels .filter((model) => !model.isCustom) .map((model) => { if ( model.slug !== tailSlotReplacement.id || - partialOverrideModelIds.size === 0 || + partialOverrideIds.size === 0 || !model.capabilities?.optionDescriptors?.length ) { return model; } const kept = model.capabilities.optionDescriptors.filter( - (descriptor) => !partialOverrideModelIds.has(descriptor.id), + (descriptor) => !partialOverrideIds.has(descriptor.id), ); return kept.length === model.capabilities.optionDescriptors.length ? model @@ -1694,16 +1705,8 @@ export const AcpRegistryDriver: ProviderDriver model.slug !== configuration.currentModelId) : basePrevious; - // Sync models array identity with acceptedCatalog when managedProvider deduplicated - // a structurally equal snapshot whose overflow-tail tag changed. - const syncedProvider = - accepted.probeOptions === null && - accepted.models.length > 0 && - Equal.equals(provider.models, accepted.models) - ? { ...provider, models: accepted.models } - : provider; const next = applyAcpRegistryLiveConfiguration( - syncedProvider, + provider, configuration, effectiveConfig.customModels, previousModels, @@ -1791,7 +1794,7 @@ export const AcpRegistryDriver: ProviderDriver 0 ? byModel : undefined; @@ -2357,7 +2358,16 @@ export const AcpRegistryDriver: ProviderDriver 0 && + Equal.equals(rawCurrent.models, accepted.models) + ? { ...rawCurrent, models: accepted.models } + : rawCurrent; if ( !current.installed || (current.auth.status === "unauthenticated" && diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 093bddba9c87e..fc4a8bb1e6827 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -235,6 +235,20 @@ export interface AcpRegistryLiveConfiguration { readonly cappedTailIsOverflow?: boolean; } +export function extractAcpRegistryAdvertisedReasoning( + models: ReadonlyArray, + currentModelId: string | null, +): AcpRegistryLiveConfiguration["advertisedReasoning"] { + const entries: Array]> = + []; + for (const model of models) { + if (model.id !== currentModelId && model.reasoningEffort != null) { + entries.push([model.id, model.reasoningEffort]); + } + } + return entries.length > 0 ? Object.fromEntries(entries) : undefined; +} + export function cappedAcpRegistryModelPrefixKey( modelIds: ReadonlyArray, ): string | undefined { @@ -323,18 +337,10 @@ export function prepareAcpRegistryLiveConfiguration( .map((descriptor) => descriptor.id); const hasModelSelect = modelOption !== undefined; const resolvedCurrentModelId = currentModel === undefined ? null : currentModel.id; - const advertisedReasoningEntries: Array< - readonly [string, NonNullable] - > = []; - for (const model of advertisedModels) { - if (model.id !== resolvedCurrentModelId && model.reasoningEffort != null) { - advertisedReasoningEntries.push([model.id, model.reasoningEffort]); - } - } - const advertisedReasoning = - advertisedReasoningEntries.length > 0 - ? Object.fromEntries(advertisedReasoningEntries) - : undefined; + const advertisedReasoning = extractAcpRegistryAdvertisedReasoning( + advertisedModels, + resolvedCurrentModelId, + ); const catalogKey = JSON.stringify([ hasModelSelect, baseModels.map(({ id, name, description }) => [id, name, description]), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index fc7a50158b1be..6ce8ab6df7349 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2338,8 +2338,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rootForegroundWork = undefined; agentRequests.clear(); nativeChildren.clear(); - yield* resetPublishedCatalogKey; yield* Ref.set(activeSessionSetup, setup); + yield* resetPublishedCatalogKey; }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); @@ -7254,8 +7254,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (current === null || current.sessionId !== result.sessionId) { return; } - yield* resetPublishedCatalogKey; yield* Ref.set(activeSessionSetup, result); + yield* resetPublishedCatalogKey; // The selection was configured against the provisional setup's // options, so the next turn re-applies it against the real ones. yield* Ref.set(activeSelection, null); From 1991b77056735b146234185c91ab60f1054cde79 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 16:42:59 +0000 Subject: [PATCH 20/35] fix(acp-registry): track per-model reasoning, carry replayed reasoning rules, and persist replayed live steps --- .../AcpRegistryRuntimeCoordinator.test.ts | 101 +++++++++- .../server/AcpRegistryRuntimeCoordinator.ts | 184 +++++++++++++++--- .../src/server/driver.test.ts | 34 +++- .../src/server/driver.ts | 39 ++-- packages/provider-acp/src/server/adapter.ts | 2 +- 5 files changed, 309 insertions(+), 51 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 821ec93276cd4..daa855232359a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -824,6 +824,105 @@ describe("AcpRegistryRuntimeCoordinator", () => { "model-c": lowEffort, }); + // Cross-model advertisedReasoning supersedes older catalog reasoning even when a + // subsequent same-model update replaces the publishing model's pending entry without + // repeating that metadata (preserving the newer high value alongside untouched catalog models). + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: lowEffort }, + { id: "model-d", name: "Model D", description: null, reasoningEffort: lowEffort }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const crossModelCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + // Case 1: model-x advertises model-b: high and stays in optionsByModel; model-a update + // must not carry older catalog model-b: low over model-x's newer observation. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-x", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + const modelXSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: crossModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterCrossModelClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterCrossModelClear.pendingOptions.find((e) => e.revision === modelXSnap.revision) + ?.configuration.advertisedReasoning, + ).toEqual({ "model-b": highEffort }); + expect( + afterCrossModelClear.pendingOptions.at(-1)?.configuration.advertisedReasoning, + ).toEqual({ "model-d": lowEffort }); + + // Case 2: model-c advertises model-b: high, then another session replaces model-c without + // model-b metadata before model-a updates and a probe clears; model-b keeps high (never low). + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: lowEffort }, + { id: "model-d", name: "Model D", description: null, reasoningEffort: lowEffort }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const replacedCrossCatalog = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterReplacedCrossClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterReplacedCrossClear.pendingOptions.at(-1)?.configuration.advertisedReasoning, + ).toEqual({ + "model-b": highEffort, + "model-d": lowEffort, + }); + // Earlier displaced tail updates (both overflow m256 and displaced ordinary tail m255) // keep their tail metadata alongside preserveDefault so the driver can learn their options // off-screen without swapping slot 255 or default, while non-tail models (m1) drop it. @@ -871,7 +970,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { }); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: sameModelCatalog.catalogRevision, + catalogRevision: replacedCrossCatalog.catalogRevision, retain: (live) => Option.some({ ...live, partialOptions: true }), }), ).toBe(true); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 90b38ea1e43f4..2ee2bcee94b6e 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -56,10 +56,24 @@ export interface AcpRegistryLiveConfigurationSnapshot { readonly clearedThroughRevision: number; } +type AcpRegistryAdvertisedReasoningDescriptor = NonNullable< + AcpRegistryLiveConfiguration["models"][number]["reasoningEffort"] +>; + +interface StoredAdvertisedReasoning { + readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor; + readonly revision: number; +} + interface StoredLiveConfiguration { readonly catalog: AcpRegistryRevisionedLiveConfiguration | null; readonly configuration: Option.Option; readonly optionsByModel: ReadonlyMap; + // Latest cross-model advertisedReasoning per model slug, independent of replaceable + // optionsByModel entries keyed by currentModelId. + readonly reasoningByModel: ReadonlyMap; + // Catalog-reasoning slugs superseded by a newer live observation. + readonly catalogReasoningSupersededSlugs: ReadonlySet; readonly revision: number; readonly catalogRevision: number; readonly clearedThroughRevision: number; @@ -69,6 +83,8 @@ const MAX_TRACKED_MODEL_OPTIONS = 256; const EMPTY_OPTIONS_BY_MODEL: ReadonlyMap = new Map(); +const EMPTY_REASONING_BY_MODEL: ReadonlyMap = new Map(); +const EMPTY_SLUG_SET: ReadonlySet = new Set(); export const EMPTY_LIVE_CONFIGURATION_SNAPSHOT: AcpRegistryLiveConfigurationSnapshot = { catalog: Option.none(), @@ -83,6 +99,8 @@ const EMPTY_STORED_LIVE_CONFIGURATION: StoredLiveConfiguration = { catalog: null, configuration: Option.none(), optionsByModel: EMPTY_OPTIONS_BY_MODEL, + reasoningByModel: EMPTY_REASONING_BY_MODEL, + catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, revision: 0, catalogRevision: 0, clearedThroughRevision: 0, @@ -308,6 +326,8 @@ const make = Effect.gen(function* () { current.catalog === null && Option.isNone(current.configuration) && current.optionsByModel.size === 0 && + current.reasoningByModel.size === 0 && + current.catalogReasoningSupersededSlugs.size === 0 && nextCleared === current.clearedThroughRevision ) { return state; @@ -318,6 +338,8 @@ const make = Effect.gen(function* () { catalog: null, configuration: Option.none(), optionsByModel: EMPTY_OPTIONS_BY_MODEL, + reasoningByModel: EMPTY_REASONING_BY_MODEL, + catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, clearedThroughRevision: nextCleared, }); return next; @@ -344,60 +366,90 @@ const make = Effect.gen(function* () { current.catalog === null ? undefined : extractAdvertisedReasoning(current.catalog.configuration); - const modelsUpdatedAfterCatalog = new Set(); + const preservedCatalogReasoning = (() => { + if (catalogReasoning === undefined) return undefined; + const entries = Object.entries(catalogReasoning).filter( + ([slug]) => !current.catalogReasoningSupersededSlugs.has(slug), + ); + return entries.length > 0 ? Object.fromEntries(entries) : undefined; + })(); if (current.catalog !== null) { - candidates.set(current.catalog.configuration.currentModelId, current.catalog); - for (const entry of current.optionsByModel.values()) { - if (entry.revision <= current.catalog.revision) continue; - if (entry.configuration.currentModelId !== null) { - modelsUpdatedAfterCatalog.add(entry.configuration.currentModelId); - } - if (entry.configuration.advertisedReasoning !== undefined) { - for (const slug of Object.keys(entry.configuration.advertisedReasoning)) { - modelsUpdatedAfterCatalog.add(slug); - } - } - } + const { advertisedReasoning: _droppedCatalogReasoning, ...catalogRest } = + current.catalog.configuration; + candidates.set(current.catalog.configuration.currentModelId, { + revision: current.catalog.revision, + configuration: { + ...catalogRest, + models: [], + modelsFromModelSelect: false, + ...(preservedCatalogReasoning === undefined + ? {} + : { advertisedReasoning: preservedCatalogReasoning }), + }, + }); } for (const [key, entry] of current.optionsByModel) { if ( - catalogReasoning !== undefined && + preservedCatalogReasoning !== undefined && current.catalog !== null && key === current.catalog.configuration.currentModelId ) { - const preservedCatalogEntries = Object.entries(catalogReasoning).filter( - ([slug]) => !modelsUpdatedAfterCatalog.has(slug), - ); - const mergedAdvertisedReasoning = - preservedCatalogEntries.length === 0 - ? entry.configuration.advertisedReasoning - : { - ...Object.fromEntries(preservedCatalogEntries), - ...entry.configuration.advertisedReasoning, - }; candidates.set(key, { revision: entry.revision, configuration: { ...entry.configuration, - ...(mergedAdvertisedReasoning === undefined - ? {} - : { advertisedReasoning: mergedAdvertisedReasoning }), + advertisedReasoning: { + ...preservedCatalogReasoning, + ...entry.configuration.advertisedReasoning, + }, }, }); continue; } candidates.set(key, entry); } + if (current.reasoningByModel.size > 0) { + const coveredReasoningSlugs = new Set(); + for (const entry of candidates.values()) { + const reasoning = entry.configuration.advertisedReasoning; + if (reasoning === undefined) continue; + for (const slug of Object.keys(reasoning)) { + const tracked = current.reasoningByModel.get(slug); + if (tracked !== undefined && entry.revision >= tracked.revision) { + coveredReasoningSlugs.add(slug); + } + } + } + const orphanedEntries: Array< + readonly [string, AcpRegistryAdvertisedReasoningDescriptor] + > = []; + for (const [slug, tracked] of current.reasoningByModel) { + if (!coveredReasoningSlugs.has(slug)) { + orphanedEntries.push([slug, tracked.descriptor]); + } + } + if (orphanedEntries.length > 0) { + const latestCandidate = sortedPendingOptions(candidates).at(-1); + if (latestCandidate !== undefined) { + candidates.set(latestCandidate.configuration.currentModelId, { + revision: latestCandidate.revision, + configuration: { + ...latestCandidate.configuration, + advertisedReasoning: { + ...Object.fromEntries(orphanedEntries), + ...latestCandidate.configuration.advertisedReasoning, + }, + }, + }); + } + } + } const retained = new Map(); for (const entry of sortedPendingOptions(candidates)) { - const catalogAdvertisedReasoning = extractAdvertisedReasoning(entry.configuration); const kept = retain({ ...entry.configuration, models: [], modelsFromModelSelect: false, - ...(catalogAdvertisedReasoning === undefined - ? {} - : { advertisedReasoning: catalogAdvertisedReasoning }), }); if (Option.isNone(kept)) continue; if (entry.revision < current.revision) { @@ -456,6 +508,8 @@ const make = Effect.gen(function* () { : Option.some(lastRetained.configuration); if ( current.catalog === null && + current.reasoningByModel.size === 0 && + current.catalogReasoningSupersededSlugs.size === 0 && Equal.equals(current.configuration, nextConfiguration) && Equal.equals( sortedPendingOptions(current.optionsByModel), @@ -471,6 +525,8 @@ const make = Effect.gen(function* () { catalog: null, configuration: nextConfiguration, optionsByModel: nextOptionsByModel, + reasoningByModel: EMPTY_REASONING_BY_MODEL, + catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, clearedThroughRevision: nextCleared, }); return [true, next] as const; @@ -506,11 +562,77 @@ const make = Effect.gen(function* () { } return updated; })(); + const reasoningByModel = hasCatalog + ? EMPTY_REASONING_BY_MODEL + : (() => { + const hasSelfToDelete = + configuration.currentModelId !== null && + current.reasoningByModel.has(configuration.currentModelId); + const incoming = configuration.advertisedReasoning; + const incomingEntries = + incoming === undefined + ? [] + : Object.entries(incoming).filter( + ([slug]) => slug !== configuration.currentModelId, + ); + if (!hasSelfToDelete && incomingEntries.length === 0) { + return current.reasoningByModel; + } + const updated = new Map(current.reasoningByModel); + if (configuration.currentModelId !== null) { + updated.delete(configuration.currentModelId); + } + for (const [slug, descriptor] of incomingEntries) { + updated.delete(slug); + updated.set(slug, { descriptor, revision }); + } + while (updated.size > MAX_TRACKED_MODEL_OPTIONS) { + const oldestKey = updated.keys().next().value; + if (oldestKey === undefined) break; + updated.delete(oldestKey); + } + return updated.size === 0 ? EMPTY_REASONING_BY_MODEL : updated; + })(); + const catalogReasoningSupersededSlugs = hasCatalog + ? EMPTY_SLUG_SET + : (() => { + const catalogReasoning = + current.catalog === null + ? undefined + : extractAdvertisedReasoning(current.catalog.configuration); + if (catalogReasoning === undefined) { + return current.catalogReasoningSupersededSlugs; + } + const added: Array = []; + if ( + configuration.currentModelId !== null && + Object.hasOwn(catalogReasoning, configuration.currentModelId) && + !current.catalogReasoningSupersededSlugs.has(configuration.currentModelId) + ) { + added.push(configuration.currentModelId); + } + if (configuration.advertisedReasoning !== undefined) { + for (const slug of Object.keys(configuration.advertisedReasoning)) { + if ( + Object.hasOwn(catalogReasoning, slug) && + !current.catalogReasoningSupersededSlugs.has(slug) + ) { + added.push(slug); + } + } + } + if (added.length === 0) return current.catalogReasoningSupersededSlugs; + const updated = new Set(current.catalogReasoningSupersededSlugs); + for (const slug of added) updated.add(slug); + return updated; + })(); const next = new Map(state); next.set(instanceId, { catalog, configuration: Option.some(configuration), optionsByModel, + reasoningByModel, + catalogReasoningSupersededSlugs, revision, catalogRevision, clearedThroughRevision: current.clearedThroughRevision, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index de6ba81a800ab..0ce030f802804 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -4896,9 +4896,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toEqual([]); // When a fresh live catalog + options-only update arrive right after clearLiveConfigurationIfRevision, - // the probe commit's replay must preserve the new catalog and its options rather than snapping back to probe baseline. + // the probe commit's replay must preserve the new catalog and its options (using the replayed + // catalog's reasoning rules rather than the probe's disabled-model set or baseline). injectLiveCatalogAfterClear = true; - yield* writeModels(["probe-1", "probe-2"]); + yield* writeModels({ + models: [ + { modelId: "live-c", name: "Live C", _meta: { supportsReasoningEffort: false } }, + { modelId: "probe-2", name: "Probe 2" }, + ], + }); yield* TestClock.adjust("16 minutes"); const concurrentCommit = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), @@ -5339,7 +5345,31 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; const replayedM0 = Option.getOrThrow(yield* Fiber.join(firstM0DuringCommit)); expect(replayedM0.models.at(-1)?.slug).toBe("m255"); + // Releasing the blocked watcher must not flicker back to the older m256 revision already + // superseded by the cache-hit replay; only newer revisions (m1) should publish afterward. + const seenAfterRelease: Array = []; + const sawDrainedM1 = yield* instance.snapshot.streamChanges.pipe( + Stream.tap((snapshot) => + Effect.sync(() => { + seenAfterRelease.push([ + snapshot.models.find((m) => m.isDefault === true)?.slug, + snapshot.models.at(-1)?.slug, + ]); + }), + ), + Stream.filter((snapshot) => snapshot.models[1]?.isDefault === true), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); yield* Deferred.succeed(releaseOverflowWatcher, undefined); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m1", fullChoices)).toLiveConfiguration({ + includeCatalog: false, + }), + ); + yield* Fiber.join(sawDrainedM1); + expect(seenAfterRelease).toEqual([["m1", "m255"]]); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 9f45c5eb94109..d3d8b5ca6b0ca 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1171,14 +1171,6 @@ export function applyAcpRegistryLiveConfiguration( partialOverrideIds.add(descriptor.id); } } - } else { - const advertisedForTail = readAdvertisedReasoning( - configuration.advertisedReasoning, - tailSlotReplacement.id, - ); - if (advertisedForTail !== undefined) { - partialOverrideIds.add(advertisedForTail.id); - } } const learnedPreviousModels = previousModels .filter((model) => !model.isCustom) @@ -1741,6 +1733,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; readonly revision: number; }, ) { @@ -1750,7 +1743,8 @@ export const AcpRegistryDriver: ProviderDriver 0; const withPreservedStatus = (applied: ServerProvider) => options.preserveStatus === true @@ -1924,6 +1918,7 @@ export const AcpRegistryDriver: ProviderDriver | undefined; for (const step of steps) { const stepAccepted = yield* Ref.get(acceptedCatalog); const stepReplacesCatalog = liveConfigurationReplacesAcceptedCatalog( @@ -2003,15 +2001,21 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) + .map((model) => model.id), + ); } } if (options?.recordLiveRevision === true) { @@ -2259,15 +2263,17 @@ export const AcpRegistryDriver: ProviderDriver Math.max(prev, clearedThroughRevision), ); } const completedAt = yield* Clock.currentTimeMillis; - yield* Ref.set(enrichmentCache, { - ...current, + yield* Ref.update(enrichmentCache, (latestCache) => ({ + ...latestCache, entry: { // Cache the winning catalog while keeping the retry TTL from the fresh probe. provider: !probeSupersedesLiveCatalog @@ -2275,7 +2281,7 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 17:18:43 +0000 Subject: [PATCH 21/35] fix(acp-registry): unify live reasoning replay, drop superseded pending reasoning, and always persist replayed steps --- .../AcpRegistryRuntimeCoordinator.test.ts | 325 +++++++++++++++++- .../server/AcpRegistryRuntimeCoordinator.ts | 297 ++++++++++++---- .../src/server/driver.test.ts | 181 ++++++++++ .../src/server/driver.ts | 177 +++++----- 4 files changed, 815 insertions(+), 165 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index daa855232359a..958c22b752316 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -872,8 +872,42 @@ describe("AcpRegistryRuntimeCoordinator", () => { afterCrossModelClear.pendingOptions.at(-1)?.configuration.advertisedReasoning, ).toEqual({ "model-d": lowEffort }); + // Second probe clear: if model-x later republishes without model-b metadata and a second + // clear runs, model-b's retained highEffort must still survive in reasoningByModel. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-x", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: crossModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterSecondCrossClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterSecondCrossClear.pendingOptions.find((e) => e.revision === modelXSnap.revision), + ).toEqual({ + revision: modelXSnap.revision, + configuration: { + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: { "model-b": highEffort }, + partialOptions: true, + preserveDefault: true, + }, + }); + // Case 2: model-c advertises model-b: high, then another session replaces model-c without - // model-b metadata before model-a updates and a probe clears; model-b keeps high (never low). + // model-b metadata before model-a updates and a probe clears; both live replay (snapshot & + // watcher catch-up) and post-clear retention keep model-b: high at its original revision + // with preserveDefault: true so default selection is untouched. yield* coordinator.publishLiveConfiguration(instanceId, { models: [ { id: "model-a", name: "Model A", description: null, reasoningEffort: highEffort }, @@ -894,6 +928,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, advertisedReasoning: { "model-b": highEffort }, }); + const modelCReasoningSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "model-c", @@ -901,6 +936,76 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelOptionIds: [], modelsFromModelSelect: false, }); + const beforeClearReplacedSnap = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(beforeClearReplacedSnap.pendingOptions).toEqual([ + { + revision: modelCReasoningSnap.revision, + configuration: { + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: { "model-b": highEffort }, + preserveDefault: true, + }, + }, + { + revision: beforeClearReplacedSnap.revision, + configuration: { + models: [], + currentModelId: "model-c", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }, + }, + ]); + const replayedByWatcher: Array<{ + readonly revision: number; + readonly currentModelId: string | null; + readonly preserveDefault: boolean | undefined; + readonly advertisedB: string | boolean | undefined; + }> = []; + const watcherDone = yield* Deferred.make(); + const watcherFiber = yield* coordinator + .watchLiveConfiguration( + instanceId, + (configuration, revision) => + Effect.sync(() => { + replayedByWatcher.push({ + revision, + currentModelId: configuration.currentModelId, + preserveDefault: configuration.preserveDefault, + advertisedB: configuration.advertisedReasoning?.["model-b"]?.currentValue, + }); + }).pipe( + Effect.flatMap(() => + replayedByWatcher.length === 2 + ? Deferred.succeed(watcherDone, undefined) + : Effect.void, + ), + ), + { afterRevision: replacedCrossCatalog.revision }, + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(watcherDone); + yield* Fiber.interrupt(watcherFiber); + expect(replayedByWatcher).toEqual([ + { + revision: modelCReasoningSnap.revision, + currentModelId: null, + preserveDefault: true, + advertisedB: "high", + }, + { + revision: beforeClearReplacedSnap.revision, + currentModelId: "model-c", + preserveDefault: undefined, + advertisedB: undefined, + }, + ]); + yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "model-a", @@ -916,13 +1021,227 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); const afterReplacedCrossClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterReplacedCrossClear.pendingOptions.find( + (e) => e.revision === modelCReasoningSnap.revision, + ), + ).toEqual({ + revision: modelCReasoningSnap.revision, + configuration: { + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: { "model-b": highEffort }, + partialOptions: true, + preserveDefault: true, + }, + }); expect( afterReplacedCrossClear.pendingOptions.at(-1)?.configuration.advertisedReasoning, ).toEqual({ - "model-b": highEffort, "model-d": lowEffort, }); + // Case 3: When model-b later reports its own full option set (either with no reasoning or + // its own lowEffort), older pending cross-model advertisedReasoning for model-b is dropped + // in both live replay and post-clear retention (even if the older publisher stays or is + // replaced). + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null }, + { id: "model-c", name: "Model C", description: null }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const dropReasoningCatalog = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + const afterModelBDroppedReasoning = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterModelBDroppedReasoning.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["model-b"] !== undefined, + ), + ).toBe(false); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => + live.currentModelId === "model-b" && live.configOptions.length === 0 + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions, + ).toEqual([]); + + // Case 4: After model-c advertises model-b: high and is replaced, model-b publishing its + // own lowEffort supersedes the orphaned highEffort so model-b keeps lowEffort after clear. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-b", + configOptions: [lowEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-a", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterSelfSupersedeClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterSelfSupersedeClear.pendingOptions.map((e) => [ + e.configuration.currentModelId, + e.configuration.configOptions.map((o) => o.currentValue), + e.configuration.advertisedReasoning?.["model-b"]?.currentValue ?? null, + ]), + ).toEqual([ + ["model-b", ["low"], null], + ["model-a", ["ask"], null], + ]); + + // Case 5: Newer cross-model advertisedReasoning (model-y: low, then model-y replaced) + // supersedes older cross-model advertisedReasoning (model-x: high) instead of letting + // model-x's stale high survive. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-x", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-y", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": lowEffort }, + }); + const modelYReasoningSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-y", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterCrossSupersedeClear = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterCrossSupersedeClear.pendingOptions + .filter((e) => e.configuration.advertisedReasoning?.["model-b"] !== undefined) + .map((e) => [ + e.revision, + e.configuration.currentModelId, + e.configuration.advertisedReasoning?.["model-b"]?.currentValue, + ]), + ).toEqual([[modelYReasoningSnap.revision, null, "low"]]); + + // Case 6: Full clearLiveConfiguration and a fresh catalog publish both reset tracked + // reasoningByModel and catalogReasoningSupersededSlugs. + yield* coordinator.clearLiveConfiguration(instanceId); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions, + ).toEqual([]); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: lowEffort }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "model-b": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "model-a", name: "Model A", description: null }, + { id: "model-b", name: "Model B", description: null, reasoningEffort: lowEffort }, + ], + currentModelId: "model-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const freshCatalogAfterSupersede = + yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: freshCatalogAfterSupersede.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions.map( + (e) => e.configuration.advertisedReasoning?.["model-b"]?.currentValue, + ), + ).toEqual(["low"]); + // Earlier displaced tail updates (both overflow m256 and displaced ordinary tail m255) // keep their tail metadata alongside preserveDefault so the driver can learn their options // off-screen without swapping slot 255 or default, while non-tail models (m1) drop it. @@ -970,7 +1289,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { }); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: replacedCrossCatalog.catalogRevision, + catalogRevision: freshCatalogAfterSupersede.catalogRevision, retain: (live) => Option.some({ ...live, partialOptions: true }), }), ).toBe(true); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 2ee2bcee94b6e..f6fbedf97a53c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -61,8 +61,11 @@ type AcpRegistryAdvertisedReasoningDescriptor = NonNullable< >; interface StoredAdvertisedReasoning { - readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor; + // `null` records that the model itself published a newer full option set + // (`currentModelId === slug`), superseding older cross-model `advertisedReasoning`. + readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor | null; readonly revision: number; + readonly partialOptions?: boolean; } interface StoredLiveConfiguration { @@ -111,12 +114,109 @@ const sortedPendingOptions = ( ): ReadonlyArray => Array.from(optionsByModel.values()).sort((left, right) => left.revision - right.revision); +const filterEntryAdvertisedReasoning = ( + entry: AcpRegistryRevisionedLiveConfiguration, + reasoningByModel: ReadonlyMap, + coveredReasoningSlugs?: Set, +): AcpRegistryRevisionedLiveConfiguration => { + const reasoning = entry.configuration.advertisedReasoning; + if (reasoning === undefined) return entry; + let changed = false; + const kept: Array = []; + for (const [slug, descriptor] of Object.entries(reasoning)) { + const tracked = reasoningByModel.get(slug); + if (tracked !== undefined) { + if (tracked.descriptor === null || entry.revision < tracked.revision) { + changed = true; + continue; + } + coveredReasoningSlugs?.add(slug); + } + kept.push([slug, descriptor]); + } + if (!changed) return entry; + const { advertisedReasoning: _dropped, ...rest } = entry.configuration; + return { + revision: entry.revision, + configuration: + kept.length === 0 ? rest : { ...rest, advertisedReasoning: Object.fromEntries(kept) }, + }; +}; + +const collectOrphanedReasoningByRevision = ( + reasoningByModel: ReadonlyMap, + coveredReasoningSlugs: ReadonlySet, +): ReadonlyArray< + readonly [ + number, + { + readonly entries: Record; + readonly partialOptions: boolean; + }, + ] +> => { + if (reasoningByModel.size === 0) return []; + const orphanedByRevision = new Map< + number, + { + readonly entries: Record; + readonly partialOptions: boolean; + } + >(); + for (const [slug, tracked] of reasoningByModel) { + if (tracked.descriptor === null || coveredReasoningSlugs.has(slug)) continue; + const existing = orphanedByRevision.get(tracked.revision); + if (existing === undefined) { + orphanedByRevision.set(tracked.revision, { + entries: { [slug]: tracked.descriptor }, + partialOptions: tracked.partialOptions === true, + }); + } else { + existing.entries[slug] = tracked.descriptor; + } + } + return Array.from(orphanedByRevision.entries()).sort( + ([leftRev], [rightRev]) => leftRev - rightRev, + ); +}; + +const buildEffectivePendingOptions = ( + optionsByModel: ReadonlyMap, + reasoningByModel: ReadonlyMap, +): ReadonlyArray => { + if (optionsByModel.size === 0 && reasoningByModel.size === 0) return []; + const coveredReasoningSlugs = new Set(); + const pending: Array = []; + for (const entry of sortedPendingOptions(optionsByModel)) { + pending.push(filterEntryAdvertisedReasoning(entry, reasoningByModel, coveredReasoningSlugs)); + } + const orphaned = collectOrphanedReasoningByRevision(reasoningByModel, coveredReasoningSlugs); + if (orphaned.length > 0) { + for (const [revision, bucket] of orphaned) { + pending.push({ + revision, + configuration: { + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: bucket.entries, + ...(bucket.partialOptions ? { partialOptions: true } : {}), + preserveDefault: true, + }, + }); + } + pending.sort((left, right) => left.revision - right.revision); + } + return pending; +}; + const toPublicLiveConfigurationSnapshot = ( entry: StoredLiveConfiguration, ): AcpRegistryLiveConfigurationSnapshot => ({ catalog: entry.catalog === null ? Option.none() : Option.some(entry.catalog), configuration: entry.configuration, - pendingOptions: sortedPendingOptions(entry.optionsByModel), + pendingOptions: buildEffectivePendingOptions(entry.optionsByModel, entry.reasoningByModel), revision: entry.revision, catalogRevision: entry.catalogRevision, clearedThroughRevision: entry.clearedThroughRevision, @@ -356,11 +456,13 @@ const make = Effect.gen(function* () { // Every revision through current.revision is either cleared or reconciled by retain. const nextCleared = Math.max(current.clearedThroughRevision, current.revision); const retain = options.retain; - const nextOptionsByModel: ReadonlyMap< - string | null, - AcpRegistryRevisionedLiveConfiguration - > = (() => { - if (retain === undefined) return EMPTY_OPTIONS_BY_MODEL; + const { nextOptionsByModel, nextReasoningByModel } = (() => { + if (retain === undefined) { + return { + nextOptionsByModel: EMPTY_OPTIONS_BY_MODEL, + nextReasoningByModel: EMPTY_REASONING_BY_MODEL, + }; + } const candidates = new Map(); const catalogReasoning = current.catalog === null @@ -389,63 +491,59 @@ const make = Effect.gen(function* () { }); } for (const [key, entry] of current.optionsByModel) { + const filteredEntry = filterEntryAdvertisedReasoning(entry, current.reasoningByModel); if ( preservedCatalogReasoning !== undefined && current.catalog !== null && key === current.catalog.configuration.currentModelId ) { candidates.set(key, { - revision: entry.revision, + revision: filteredEntry.revision, configuration: { - ...entry.configuration, + ...filteredEntry.configuration, advertisedReasoning: { ...preservedCatalogReasoning, - ...entry.configuration.advertisedReasoning, + ...filteredEntry.configuration.advertisedReasoning, }, }, }); continue; } - candidates.set(key, entry); + candidates.set(key, filteredEntry); } - if (current.reasoningByModel.size > 0) { - const coveredReasoningSlugs = new Set(); - for (const entry of candidates.values()) { - const reasoning = entry.configuration.advertisedReasoning; - if (reasoning === undefined) continue; - for (const slug of Object.keys(reasoning)) { + const retained = new Map(); + const retainedReasoning = new Map(); + const coveredReasoningSlugs = new Set(); + const recordRetainedReasoning = ( + advertisedReasoning: AcpRegistryLiveConfiguration["advertisedReasoning"], + revision: number, + excludeSlug: string | null, + partialOptions: boolean, + ) => { + if (advertisedReasoning === undefined) return; + for (const [slug, descriptor] of Object.entries(advertisedReasoning)) { + if (slug === excludeSlug) continue; + retainedReasoning.delete(slug); + retainedReasoning.set(slug, { + descriptor, + revision, + ...(partialOptions ? { partialOptions: true } : {}), + }); + } + }; + for (const entry of sortedPendingOptions(candidates)) { + if (entry.configuration.advertisedReasoning !== undefined) { + for (const slug of Object.keys(entry.configuration.advertisedReasoning)) { const tracked = current.reasoningByModel.get(slug); - if (tracked !== undefined && entry.revision >= tracked.revision) { + if ( + tracked !== undefined && + tracked.descriptor !== null && + entry.revision >= tracked.revision + ) { coveredReasoningSlugs.add(slug); } } } - const orphanedEntries: Array< - readonly [string, AcpRegistryAdvertisedReasoningDescriptor] - > = []; - for (const [slug, tracked] of current.reasoningByModel) { - if (!coveredReasoningSlugs.has(slug)) { - orphanedEntries.push([slug, tracked.descriptor]); - } - } - if (orphanedEntries.length > 0) { - const latestCandidate = sortedPendingOptions(candidates).at(-1); - if (latestCandidate !== undefined) { - candidates.set(latestCandidate.configuration.currentModelId, { - revision: latestCandidate.revision, - configuration: { - ...latestCandidate.configuration, - advertisedReasoning: { - ...Object.fromEntries(orphanedEntries), - ...latestCandidate.configuration.advertisedReasoning, - }, - }, - }); - } - } - } - const retained = new Map(); - for (const entry of sortedPendingOptions(candidates)) { const kept = retain({ ...entry.configuration, models: [], @@ -469,23 +567,30 @@ const make = Effect.gen(function* () { kept.value.cappedLastModel.id === kept.value.currentModelId; const { cappedLastModel, cappedPrefixKey, cappedTailIsOverflow, ...rest } = kept.value; + const retainedConfig: AcpRegistryLiveConfiguration = { + ...rest, + configOptions: modelOnlyOptions, + modelOptionIds: modelOnlyOptions.map((descriptor) => descriptor.id), + preserveDefault: true, + ...(keepDisplacedTailModel + ? { + cappedPrefixKey, + cappedLastModel, + ...(cappedTailIsOverflow === true ? { cappedTailIsOverflow: true } : {}), + } + : {}), + }; retained.delete(kept.value.currentModelId); retained.set(kept.value.currentModelId, { - configuration: { - ...rest, - configOptions: modelOnlyOptions, - modelOptionIds: modelOnlyOptions.map((descriptor) => descriptor.id), - preserveDefault: true, - ...(keepDisplacedTailModel - ? { - cappedPrefixKey, - cappedLastModel, - ...(cappedTailIsOverflow === true ? { cappedTailIsOverflow: true } : {}), - } - : {}), - }, + configuration: retainedConfig, revision: entry.revision, }); + recordRetainedReasoning( + retainedConfig.advertisedReasoning, + entry.revision, + retainedConfig.currentModelId, + retainedConfig.partialOptions === true, + ); continue; } retained.delete(kept.value.currentModelId); @@ -493,28 +598,71 @@ const make = Effect.gen(function* () { configuration: kept.value, revision: entry.revision, }); + recordRetainedReasoning( + kept.value.advertisedReasoning, + entry.revision, + kept.value.currentModelId, + kept.value.partialOptions === true, + ); + } + for (const [revision, bucket] of collectOrphanedReasoningByRevision( + current.reasoningByModel, + coveredReasoningSlugs, + )) { + const kept = retain({ + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: bucket.entries, + ...(bucket.partialOptions ? { partialOptions: true } : {}), + preserveDefault: true, + }); + if (Option.isNone(kept)) continue; + recordRetainedReasoning( + kept.value.advertisedReasoning, + revision, + null, + kept.value.partialOptions === true, + ); } while (retained.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = retained.keys().next().value; if (oldestKey === undefined) break; retained.delete(oldestKey); } - return retained.size === 0 ? EMPTY_OPTIONS_BY_MODEL : retained; + while (retainedReasoning.size > MAX_TRACKED_MODEL_OPTIONS) { + const oldestKey = retainedReasoning.keys().next().value; + if (oldestKey === undefined) break; + retainedReasoning.delete(oldestKey); + } + return { + nextOptionsByModel: retained.size === 0 ? EMPTY_OPTIONS_BY_MODEL : retained, + nextReasoningByModel: + retainedReasoning.size === 0 ? EMPTY_REASONING_BY_MODEL : retainedReasoning, + }; })(); - const lastRetained = sortedPendingOptions(nextOptionsByModel).at(-1); + const nextPending = buildEffectivePendingOptions( + nextOptionsByModel, + nextReasoningByModel, + ); + const lastRetained = nextPending.at(-1); const nextConfiguration: Option.Option = lastRetained === undefined || lastRetained.configuration.preserveDefault === true ? Option.none() : Option.some(lastRetained.configuration); if ( current.catalog === null && - current.reasoningByModel.size === 0 && current.catalogReasoningSupersededSlugs.size === 0 && Equal.equals(current.configuration, nextConfiguration) && Equal.equals( sortedPendingOptions(current.optionsByModel), sortedPendingOptions(nextOptionsByModel), ) && + Equal.equals( + Array.from(current.reasoningByModel.entries()), + Array.from(nextReasoningByModel.entries()), + ) && nextCleared === current.clearedThroughRevision ) { return [true, state] as const; @@ -525,7 +673,7 @@ const make = Effect.gen(function* () { catalog: null, configuration: nextConfiguration, optionsByModel: nextOptionsByModel, - reasoningByModel: EMPTY_REASONING_BY_MODEL, + reasoningByModel: nextReasoningByModel, catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, clearedThroughRevision: nextCleared, }); @@ -565,9 +713,10 @@ const make = Effect.gen(function* () { const reasoningByModel = hasCatalog ? EMPTY_REASONING_BY_MODEL : (() => { - const hasSelfToDelete = - configuration.currentModelId !== null && - current.reasoningByModel.has(configuration.currentModelId); + const selfSlug = + configuration.partialOptions !== true ? configuration.currentModelId : null; + const hasSelfToSupersede = + selfSlug !== null && current.reasoningByModel.has(selfSlug); const incoming = configuration.advertisedReasoning; const incomingEntries = incoming === undefined @@ -575,16 +724,22 @@ const make = Effect.gen(function* () { : Object.entries(incoming).filter( ([slug]) => slug !== configuration.currentModelId, ); - if (!hasSelfToDelete && incomingEntries.length === 0) { + if (!hasSelfToSupersede && incomingEntries.length === 0) { return current.reasoningByModel; } const updated = new Map(current.reasoningByModel); - if (configuration.currentModelId !== null) { - updated.delete(configuration.currentModelId); + if (hasSelfToSupersede) { + updated.delete(selfSlug); + updated.set(selfSlug, { descriptor: null, revision }); } + const isPartial = configuration.partialOptions === true; for (const [slug, descriptor] of incomingEntries) { updated.delete(slug); - updated.set(slug, { descriptor, revision }); + updated.set(slug, { + descriptor, + revision, + ...(isPartial ? { partialOptions: true } : {}), + }); } while (updated.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = updated.keys().next().value; @@ -605,6 +760,7 @@ const make = Effect.gen(function* () { } const added: Array = []; if ( + configuration.partialOptions !== true && configuration.currentModelId !== null && Object.hasOwn(catalogReasoning, configuration.currentModelId) && !current.catalogReasoningSupersededSlugs.has(configuration.currentModelId) @@ -678,7 +834,10 @@ const make = Effect.gen(function* () { deliveredRevision = current.catalog.revision; yield* onUpdate(current.catalog.configuration, current.catalog.revision); } - for (const entry of sortedPendingOptions(current.optionsByModel)) { + for (const entry of buildEffectivePendingOptions( + current.optionsByModel, + current.reasoningByModel, + )) { if (entry.revision <= deliveredRevision) continue; deliveredRevision = entry.revision; yield* onUpdate(entry.configuration, entry.revision); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 0ce030f802804..0709efc85d46b 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -4917,6 +4917,21 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "live-c") ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["effort", "high"]]); + + // Persisting replayed steps during the cleared probe commit keeps acceptedCatalog and + // enrichmentCache on ["live-c", "live-d"] so a subsequent cache-hit refresh does not + // regress back to the superseded probe ["live-c", "probe-2"]. + const cachedAfterConcurrent = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const cachedSnap = Option.getOrThrow(yield* Fiber.join(cachedAfterConcurrent)); + expect(cachedSnap.models.map((m) => m.slug)).toEqual(["live-c", "live-d"]); + expect( + cachedSnap.models + .find((m) => m.slug === "live-c") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); }), ); @@ -5759,12 +5774,31 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ], }); + let blockReasoningWatcher = false; + const releaseReasoningWatcher = yield* Deferred.make(); const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-advertised-reasoning-", initialModels: { models: entries, configOptions: [modelSelect("a")], }, + wrapCoordinator: (base) => ({ + ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + blockReasoningWatcher + ? Effect.sync(() => { + blockReasoningWatcher = false; + }).pipe( + Effect.andThen(Deferred.await(releaseReasoningWatcher)), + Effect.andThen(onUpdate(configuration, revision)), + ) + : onUpdate(configuration, revision), + options, + ), + }), }); const initial = yield* waitForEnriched().pipe( @@ -5817,6 +5851,153 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort"), ).toBe(true); + // When c advertises effort=high for b and then sends a follow-up update without b metadata + // before the watcher drains, readiness replay (with foreground startup suppressing the + // probe) must still deliver b's effort=high without stealing default from c. + const lowOnlyEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "low", + options: [{ id: "low", label: "Low" }], + }; + const highEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }; + const sawNarrowLiveCatalog = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => { + const bEffort = snapshot.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort"); + return bEffort?.type === "select" && bEffort.options.length === 1; + }), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "a", name: "a", description: null }, + { id: "b", name: "b", description: null, reasoningEffort: lowOnlyEffort }, + { id: "c", name: "c", description: null }, + ], + currentModelId: "a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(sawNarrowLiveCatalog); + + blockReasoningWatcher = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { b: highEffort }, + }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "c", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + const sawReadinessOrphanedReasoning = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.find((m) => m.slug === "c")?.isDefault === true && + snapshot.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.withForegroundStartup( + "test-agent", + instance.snapshot.refresh.pipe(Effect.andThen(Fiber.join(sawReadinessOrphanedReasoning))), + ); + yield* Deferred.succeed(releaseReasoningWatcher, undefined); + const afterOrphanedReadiness = yield* instance.snapshot.getSnapshot; + expect(afterOrphanedReadiness.models.find((m) => m.slug === "c")?.isDefault).toBe(true); + expect( + afterOrphanedReadiness.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort"), + ).toEqual(highEffort); + + // If c advertises effort=high for b and b later reports a full option set without + // reasoning, a superseding probe selecting b without reasoning must not restore high. + const modeSelect = { + id: "mode", + name: "Mode", + category: "mode" as const, + type: "select" as const, + currentValue: "ask", + options: [{ value: "ask", name: "Ask" }], + }; + const modeOption = { + id: "mode", + label: "Mode", + type: "select" as const, + currentValue: "ask", + options: [{ id: "ask", label: "Ask" }], + }; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "c", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { b: highEffort }, + }); + const sawBDroppedEffort = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.find((m) => m.slug === "b")?.isDefault === true && + (snapshot.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort") ?? false) === + false, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "b", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawBDroppedEffort); + yield* writeModels({ + models: ids.map((id) => ({ modelId: id, name: id })), + configOptions: [modelSelect("b"), modeSelect], + }); + yield* TestClock.adjust("16 minutes"); + const probeAfterBDropped = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterBDroppedProbe = Option.getOrThrow(yield* Fiber.join(probeAfterBDropped)); + expect(afterBDroppedProbe.models.find((m) => m.slug === "b")?.isDefault).toBe(true); + expect( + afterBDroppedProbe.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort") ?? false, + ).toBe(false); + // When neither live state nor a fresh probe advertises models, keep live reasoning // options on the synthetic default model instead of clearing them. yield* writeModels({ provisional: "" }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index d3d8b5ca6b0ca..ac1d568b1dd41 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -597,6 +597,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( retainedAdvertisedReasoning === undefined ? {} : { advertisedReasoning: retainedAdvertisedReasoning }; + const preserveDefaultFields = live.preserveDefault === true ? { preserveDefault: true } : {}; const configOptions = [...sharedDescriptors, ...modelDescriptors]; if (configOptions.length === 0) { // Keep the running session's model selection, capped tail update, or advertised reasoning @@ -604,7 +605,9 @@ export function retainAcpRegistryLiveOptionsAfterProbe( if ( matchingCappedTail === undefined && retainedAdvertisedReasoning === undefined && - (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) + (live.preserveDefault === true || + currentProbedModel === undefined || + currentProbedModel.id === probe.currentModelId) ) { return Option.none(); } @@ -615,6 +618,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelOptionIds: [], modelsFromModelSelect: false, partialOptions: true, + ...preserveDefaultFields, ...overflowFields, ...advertisedReasoningFields, }); @@ -628,6 +632,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelOptionIds: modelDescriptors.map((descriptor) => descriptor.id), modelsFromModelSelect: false, partialOptions: true, + ...preserveDefaultFields, ...overflowFields, ...advertisedReasoningFields, }); @@ -1066,13 +1071,24 @@ function overlayPartialLiveOptions( } else if (!model.isCustom && !reasoningDisabled) { const advertised = readAdvertisedReasoning(configuration.advertisedReasoning, model.slug); if (advertised !== undefined) { - const existingIndex = nextDescriptors.findIndex((item) => item.id === advertised.id); - if (existingIndex >= 0) { - const currentDescriptor = nextDescriptors[existingIndex]!; - const overlaid = compatibleLiveOptionValue(currentDescriptor, advertised); - nextDescriptors[existingIndex] = Option.getOrElse(overlaid, () => currentDescriptor); - } else if (!nextDescriptors.some(isReasoningDescriptor)) { + if (configuration.partialOptions !== true) { + // Live reasoning-only replay (no superseding probe schema constraining it): + // replace any earlier reasoning selector just like modelsFromDiscovery does. + for (let index = nextDescriptors.length - 1; index >= 0; index -= 1) { + if (isReasoningDescriptor(nextDescriptors[index]!)) { + nextDescriptors.splice(index, 1); + } + } nextDescriptors.push(advertised); + } else { + const existingIndex = nextDescriptors.findIndex((item) => item.id === advertised.id); + if (existingIndex >= 0) { + const currentDescriptor = nextDescriptors[existingIndex]!; + const overlaid = compatibleLiveOptionValue(currentDescriptor, advertised); + nextDescriptors[existingIndex] = Option.getOrElse(overlaid, () => currentDescriptor); + } else if (!nextDescriptors.some(isReasoningDescriptor)) { + nextDescriptors.push(advertised); + } } } } @@ -1160,7 +1176,13 @@ export function applyAcpRegistryLiveConfiguration( const selectedProbedModelId = liveCurrentModelInProbed ? configuration.currentModelId : (probedModels.find((model) => model.isDefault)?.slug ?? null); - if (!useLiveCatalog && configuration.partialOptions === true) { + const isReasoningOnlyLiveOverlay = + !useLiveCatalog && + configuration.partialOptions !== true && + configuration.preserveDefault === true && + configuration.currentModelId === null && + configuration.configOptions.length === 0; + if (!useLiveCatalog && (configuration.partialOptions === true || isReasoningOnlyLiveOverlay)) { const modelsForOverlay = (() => { if (tailSlotReplacement === undefined) return provider.models; const partialOverrideIds = new Set(); @@ -1731,9 +1753,6 @@ export const AcpRegistryDriver: ProviderDriver | undefined; readonly revision: number; }, ) { @@ -1743,8 +1762,7 @@ export const AcpRegistryDriver: ProviderDriver 0; const withPreservedStatus = (applied: ServerProvider) => options.preserveStatus === true @@ -1756,7 +1774,7 @@ export const AcpRegistryDriver: ProviderDriver Math.max(prev, options.revision)); - } + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); return withPreservedStatus(applied); } @@ -1861,54 +1877,52 @@ export const AcpRegistryDriver: ProviderDriver model.reasoningEffort === null) - .map((model) => model.id), - ) - : acceptedBefore.reasoningDisabledModelSlugs; - const savedToAccepted = - current.installed && - (current.auth.status !== "unauthenticated" || replacesCatalog) && - (replacesCatalog || acceptedBefore.models.length > 0); - if (savedToAccepted) { - yield* Ref.update(acceptedCatalog, (previous) => - replacesCatalog - ? { - models: next.models, - builtInModelCount: configuration.models.length, - modelsFromModelSelect: configuration.modelsFromModelSelect === true, - reasoningDisabledModelSlugs: nextReasoningDisabled, - probeOptions: null, - probeBaselineModels: null, - } - : { - ...previous, - models: next.models, - }, + const nextReasoningDisabled = replacesCatalog + ? new Set( + configuration.models + .filter((model) => model.reasoningEffort === null) + .map((model) => model.id), + ) + : acceptedBefore.reasoningDisabledModelSlugs; + const savedToAccepted = + current.installed && + (current.auth.status !== "unauthenticated" || replacesCatalog) && + (replacesCatalog || acceptedBefore.models.length > 0); + if (savedToAccepted) { + yield* Ref.update(acceptedCatalog, (previous) => + replacesCatalog + ? { + models: next.models, + builtInModelCount: configuration.models.length, + modelsFromModelSelect: configuration.modelsFromModelSelect === true, + reasoningDisabledModelSlugs: nextReasoningDisabled, + probeOptions: null, + probeBaselineModels: null, + } + : { + ...previous, + models: next.models, + }, + ); + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); + if (configuration.models.length > 0) { + yield* Ref.update(lastAppliedLiveCatalogRevision, (prev) => + Math.max(prev, options.revision), ); - yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); - if (configuration.models.length > 0) { - yield* Ref.update(lastAppliedLiveCatalogRevision, (prev) => - Math.max(prev, options.revision), - ); - } } - const now = yield* Clock.currentTimeMillis; - yield* Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - preserveSingleModelCatalog, - reasoningDisabledModelSlugs: acceptedBefore.reasoningDisabledModelSlugs, - hasDiscoveredCatalog, - }), - ); } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + preserveSingleModelCatalog, + reasoningDisabledModelSlugs: acceptedBefore.reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + }), + ); return next; }, ); @@ -1918,7 +1932,6 @@ export const AcpRegistryDriver: ProviderDriver | undefined; for (const step of steps) { - const stepAccepted = yield* Ref.get(acceptedCatalog); - const stepReplacesCatalog = liveConfigurationReplacesAcceptedCatalog( - step.configuration, - stepAccepted, - ); withConfiguration = yield* applyLiveConfigurationStep( withConfiguration, step.configuration, { preserveStatus: options?.preserveStatus, - updateAcceptedAndCache: persistReplayedSteps, - ignoreProbeBaseline: catalogReplacedInReplay && !stepReplacesCatalog, - ...(replayedReasoningDisabledSlugs === undefined || stepReplacesCatalog - ? {} - : { reasoningDisabledModelSlugs: replayedReasoningDisabledSlugs }), revision: step.revision, }, ); - if (stepReplacesCatalog) { - catalogReplacedInReplay = true; - replayedReasoningDisabledSlugs = new Set( - step.configuration.models - .filter((model) => model.reasoningEffort === null) - .map((model) => model.id), - ); - } } if (options?.recordLiveRevision === true) { yield* Ref.set(lastObservedLiveRevision, liveConfiguration.revision); @@ -2251,6 +2242,7 @@ export const AcpRegistryDriver: ProviderDriver 0 || afterClear.revision > liveSnapshot.revision || accepted.probeOptions !== null; yield* resetAppliedLiveRevisions; @@ -2263,22 +2255,23 @@ export const AcpRegistryDriver: ProviderDriver Math.max(prev, clearedThroughRevision), ); } + const acceptedAfter = yield* Ref.get(acceptedCatalog); const completedAt = yield* Clock.currentTimeMillis; yield* Ref.update(enrichmentCache, (latestCache) => ({ ...latestCache, entry: { // Cache the winning catalog while keeping the retry TTL from the fresh probe. - provider: !probeSupersedesLiveCatalog - ? { ...resolved, models: published.models } - : resolved, + provider: + (!probeSupersedesLiveCatalog || acceptedAfter.probeOptions === null) && + published.models !== resolved.models + ? { ...resolved, models: published.models } + : resolved, expiresAt: completedAt + acpRegistryProbeTtlMs(provider), }, })); @@ -2305,7 +2298,6 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 17:51:38 +0000 Subject: [PATCH 22/35] fix(acp-registry): eagerly strip superseded reasoning, keep __proto__ safe, preserve empty-option removals, and simplify coordinator hot paths --- .../AcpRegistryRuntimeCoordinator.test.ts | 125 ++++++++- .../server/AcpRegistryRuntimeCoordinator.ts | 246 +++++++++--------- .../src/server/driver.test.ts | 145 ++++++++++- .../src/server/driver.ts | 38 ++- .../provider-acp-registry/src/server/probe.ts | 3 + 5 files changed, 400 insertions(+), 157 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 958c22b752316..ef8e6332f0064 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -1043,10 +1043,117 @@ describe("AcpRegistryRuntimeCoordinator", () => { "model-d": lowEffort, }); + // A follow-up clear whose retain drops only the orphaned reasoning entry must update + // stored state rather than short-circuiting as a no-op. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => + live.currentModelId === null + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["model-b"] !== undefined, + ), + ).toBe(false); + + // Orphan replay preserves __proto__ as an own property alongside other slugs in the same + // revision, and retainedReasoning caps at 256 while evicting older revisions first. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-proto", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: Object.fromEntries([ + ["model-b", highEffort], + ["__proto__", lowEffort], + ]), + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-proto", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + const protoOrphanBeforeClear = (yield* coordinator.getLiveConfigurationWithRevision( + instanceId, + )).pendingOptions.find((e) => e.configuration.currentModelId === null)?.configuration + .advertisedReasoning; + expect(protoOrphanBeforeClear?.["model-b"]).toEqual(highEffort); + expect( + protoOrphanBeforeClear !== undefined && + Object.hasOwn(protoOrphanBeforeClear, "__proto__"), + ).toBe(true); + expect(protoOrphanBeforeClear?.["__proto__"]).toEqual(lowEffort); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const protoOrphanAfterClear = (yield* coordinator.getLiveConfigurationWithRevision( + instanceId, + )).pendingOptions.find((e) => e.configuration.currentModelId === null)?.configuration + .advertisedReasoning; + expect( + protoOrphanAfterClear !== undefined && Object.hasOwn(protoOrphanAfterClear, "__proto__"), + ).toBe(true); + expect(protoOrphanAfterClear?.["__proto__"]).toEqual(lowEffort); + + // Retained reasoning caps at 256 and evicts older orphaned entries before newer candidates. + yield* coordinator.clearLiveConfiguration(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "orphan-pub", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: { "oldest-orphan": highEffort }, + }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "orphan-pub", + configOptions: [modeOption("code")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + const newerAdvertised = Object.fromEntries( + Array.from({ length: 256 }, (_, index) => [`newer-${index}`, lowEffort]), + ); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "cand-pub", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: newerAdvertised, + }); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ).toBe(true); + const afterCapClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["oldest-orphan"] !== undefined, + ), + ).toBe(false); + expect( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["newer-255"] !== undefined, + ), + ).toBe(true); + // Case 3: When model-b later reports its own full option set (either with no reasoning or // its own lowEffort), older pending cross-model advertisedReasoning for model-b is dropped - // in both live replay and post-clear retention (even if the older publisher stays or is - // replaced). + // immediately so even 256+ subsequent reasoning evictions never let model-c resurrect it. yield* coordinator.publishLiveConfiguration(instanceId, { models: [ { id: "model-a", name: "Model A", description: null }, @@ -1074,6 +1181,17 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelOptionIds: [], modelsFromModelSelect: false, }); + // Cycle reasoningByModel past the 256 cap while model-c stays in optionsByModel. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-churn", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + advertisedReasoning: Object.fromEntries( + Array.from({ length: 260 }, (_, index) => [`churn-${index}`, lowEffort]), + ), + }); const afterModelBDroppedReasoning = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( @@ -1085,7 +1203,8 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: dropReasoningCatalog.catalogRevision, retain: (live) => - live.currentModelId === "model-b" && live.configOptions.length === 0 + live.currentModelId === "model-churn" || + (live.currentModelId === "model-b" && live.configOptions.length === 0) ? Option.none() : Option.some({ ...live, partialOptions: true }), }), diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index f6fbedf97a53c..6756e160accfc 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -61,9 +61,7 @@ type AcpRegistryAdvertisedReasoningDescriptor = NonNullable< >; interface StoredAdvertisedReasoning { - // `null` records that the model itself published a newer full option set - // (`currentModelId === slug`), superseding older cross-model `advertisedReasoning`. - readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor | null; + readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor; readonly revision: number; readonly partialOptions?: boolean; } @@ -114,23 +112,18 @@ const sortedPendingOptions = ( ): ReadonlyArray => Array.from(optionsByModel.values()).sort((left, right) => left.revision - right.revision); -const filterEntryAdvertisedReasoning = ( +const stripAdvertisedReasoningSlugs = ( entry: AcpRegistryRevisionedLiveConfiguration, - reasoningByModel: ReadonlyMap, - coveredReasoningSlugs?: Set, + supersededSlugs: ReadonlySet, ): AcpRegistryRevisionedLiveConfiguration => { const reasoning = entry.configuration.advertisedReasoning; if (reasoning === undefined) return entry; let changed = false; const kept: Array = []; for (const [slug, descriptor] of Object.entries(reasoning)) { - const tracked = reasoningByModel.get(slug); - if (tracked !== undefined) { - if (tracked.descriptor === null || entry.revision < tracked.revision) { - changed = true; - continue; - } - coveredReasoningSlugs?.add(slug); + if (supersededSlugs.has(slug)) { + changed = true; + continue; } kept.push([slug, descriptor]); } @@ -143,72 +136,68 @@ const filterEntryAdvertisedReasoning = ( }; }; -const collectOrphanedReasoningByRevision = ( +const makeOrphanedReasoningConfiguration = ( + entries: ReadonlyArray, + partialOptions: boolean, +): AcpRegistryLiveConfiguration => ({ + models: [], + modelsFromModelSelect: false, + currentModelId: null, + configOptions: [], + advertisedReasoning: Object.fromEntries(entries), + ...(partialOptions ? { partialOptions: true } : {}), + preserveDefault: true, +}); + +const collectOrphanedReasoningSteps = ( reasoningByModel: ReadonlyMap, coveredReasoningSlugs: ReadonlySet, -): ReadonlyArray< - readonly [ - number, - { - readonly entries: Record; - readonly partialOptions: boolean; - }, - ] -> => { +): ReadonlyArray => { if (reasoningByModel.size === 0) return []; const orphanedByRevision = new Map< number, { - readonly entries: Record; + readonly entries: Array; readonly partialOptions: boolean; } >(); for (const [slug, tracked] of reasoningByModel) { - if (tracked.descriptor === null || coveredReasoningSlugs.has(slug)) continue; + if (coveredReasoningSlugs.has(slug)) continue; const existing = orphanedByRevision.get(tracked.revision); if (existing === undefined) { orphanedByRevision.set(tracked.revision, { - entries: { [slug]: tracked.descriptor }, + entries: [[slug, tracked.descriptor]], partialOptions: tracked.partialOptions === true, }); } else { - existing.entries[slug] = tracked.descriptor; + existing.entries.push([slug, tracked.descriptor]); } } - return Array.from(orphanedByRevision.entries()).sort( - ([leftRev], [rightRev]) => leftRev - rightRev, - ); + return Array.from(orphanedByRevision.entries()) + .sort(([leftRev], [rightRev]) => leftRev - rightRev) + .map(([revision, bucket]) => ({ + revision, + configuration: makeOrphanedReasoningConfiguration(bucket.entries, bucket.partialOptions), + })); }; const buildEffectivePendingOptions = ( optionsByModel: ReadonlyMap, reasoningByModel: ReadonlyMap, ): ReadonlyArray => { - if (optionsByModel.size === 0 && reasoningByModel.size === 0) return []; + const pending = sortedPendingOptions(optionsByModel); + if (reasoningByModel.size === 0) return pending; const coveredReasoningSlugs = new Set(); - const pending: Array = []; - for (const entry of sortedPendingOptions(optionsByModel)) { - pending.push(filterEntryAdvertisedReasoning(entry, reasoningByModel, coveredReasoningSlugs)); - } - const orphaned = collectOrphanedReasoningByRevision(reasoningByModel, coveredReasoningSlugs); - if (orphaned.length > 0) { - for (const [revision, bucket] of orphaned) { - pending.push({ - revision, - configuration: { - models: [], - modelsFromModelSelect: false, - currentModelId: null, - configOptions: [], - advertisedReasoning: bucket.entries, - ...(bucket.partialOptions ? { partialOptions: true } : {}), - preserveDefault: true, - }, - }); + for (const entry of pending) { + const reasoning = entry.configuration.advertisedReasoning; + if (reasoning === undefined) continue; + for (const slug of Object.keys(reasoning)) { + coveredReasoningSlugs.add(slug); } - pending.sort((left, right) => left.revision - right.revision); } - return pending; + const orphaned = collectOrphanedReasoningSteps(reasoningByModel, coveredReasoningSlugs); + if (orphaned.length === 0) return pending; + return [...pending, ...orphaned].sort((left, right) => left.revision - right.revision); }; const toPublicLiveConfigurationSnapshot = ( @@ -278,6 +267,9 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; + readonly getLiveConfigurationClearedThroughRevision: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; readonly getLiveConfigurationWithRevision: ( instanceId: ProviderInstanceId, ) => Effect.Effect; @@ -491,29 +483,46 @@ const make = Effect.gen(function* () { }); } for (const [key, entry] of current.optionsByModel) { - const filteredEntry = filterEntryAdvertisedReasoning(entry, current.reasoningByModel); if ( preservedCatalogReasoning !== undefined && current.catalog !== null && key === current.catalog.configuration.currentModelId ) { candidates.set(key, { - revision: filteredEntry.revision, + revision: entry.revision, configuration: { - ...filteredEntry.configuration, + ...entry.configuration, advertisedReasoning: { ...preservedCatalogReasoning, - ...filteredEntry.configuration.advertisedReasoning, + ...entry.configuration.advertisedReasoning, }, }, }); continue; } - candidates.set(key, filteredEntry); + candidates.set(key, entry); } + const coveredReasoningSlugs = new Set(); + if (current.reasoningByModel.size > 0) { + for (const entry of candidates.values()) { + const reasoning = entry.configuration.advertisedReasoning; + if (reasoning === undefined) continue; + for (const slug of Object.keys(reasoning)) { + coveredReasoningSlugs.add(slug); + } + } + } + const steps: Array<{ + readonly entry: AcpRegistryRevisionedLiveConfiguration; + readonly isOrphan: boolean; + }> = [ + ...sortedPendingOptions(candidates).map((entry) => ({ entry, isOrphan: false })), + ...collectOrphanedReasoningSteps(current.reasoningByModel, coveredReasoningSlugs).map( + (entry) => ({ entry, isOrphan: true }), + ), + ].sort((left, right) => left.entry.revision - right.entry.revision); const retained = new Map(); const retainedReasoning = new Map(); - const coveredReasoningSlugs = new Set(); const recordRetainedReasoning = ( advertisedReasoning: AcpRegistryLiveConfiguration["advertisedReasoning"], revision: number, @@ -531,28 +540,25 @@ const make = Effect.gen(function* () { }); } }; - for (const entry of sortedPendingOptions(candidates)) { - if (entry.configuration.advertisedReasoning !== undefined) { - for (const slug of Object.keys(entry.configuration.advertisedReasoning)) { - const tracked = current.reasoningByModel.get(slug); - if ( - tracked !== undefined && - tracked.descriptor !== null && - entry.revision >= tracked.revision - ) { - coveredReasoningSlugs.add(slug); - } - } - } + for (const { entry, isOrphan } of steps) { const kept = retain({ ...entry.configuration, models: [], modelsFromModelSelect: false, }); if (Option.isNone(kept)) continue; + if (isOrphan) { + recordRetainedReasoning( + kept.value.advertisedReasoning, + entry.revision, + null, + kept.value.partialOptions === true, + ); + continue; + } if (entry.revision < current.revision) { - // Earlier models keep only model-specific options, advertised reasoning, and - // displaced-tail metadata without stealing default selection or shared options. + // Earlier models keep only model-specific options, advertised reasoning, + // replacement intent, and displaced-tail metadata without stealing default or shared options. const modelOptionIds = new Set(kept.value.modelOptionIds ?? []); const modelOnlyOptions = kept.value.configOptions.filter((descriptor) => modelOptionIds.has(descriptor.id), @@ -560,7 +566,13 @@ const make = Effect.gen(function* () { const hasAdvertisedReasoning = kept.value.advertisedReasoning !== undefined && Object.keys(kept.value.advertisedReasoning).length > 0; - if (modelOnlyOptions.length === 0 && !hasAdvertisedReasoning) continue; + if ( + modelOnlyOptions.length === 0 && + !hasAdvertisedReasoning && + kept.value.replaceModelOptions !== true + ) { + continue; + } const keepDisplacedTailModel = kept.value.cappedLastModel !== undefined && kept.value.cappedPrefixKey !== undefined && @@ -605,27 +617,6 @@ const make = Effect.gen(function* () { kept.value.partialOptions === true, ); } - for (const [revision, bucket] of collectOrphanedReasoningByRevision( - current.reasoningByModel, - coveredReasoningSlugs, - )) { - const kept = retain({ - models: [], - modelsFromModelSelect: false, - currentModelId: null, - configOptions: [], - advertisedReasoning: bucket.entries, - ...(bucket.partialOptions ? { partialOptions: true } : {}), - preserveDefault: true, - }); - if (Option.isNone(kept)) continue; - recordRetainedReasoning( - kept.value.advertisedReasoning, - revision, - null, - kept.value.partialOptions === true, - ); - } while (retained.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = retained.keys().next().value; if (oldestKey === undefined) break; @@ -697,11 +688,33 @@ const make = Effect.gen(function* () { // Keep the active catalog and per-model options separate; a new catalog replaces // prior per-model options while options-only updates preserve earlier models' entries. const catalog = hasCatalog ? { configuration, revision } : current.catalog; + const incoming = configuration.advertisedReasoning; + const incomingEntries = + incoming === undefined + ? [] + : Object.entries(incoming).filter( + ([slug]) => slug !== configuration.currentModelId, + ); + const supersededSlugs = new Set(); + if (configuration.currentModelId !== null) { + supersededSlugs.add(configuration.currentModelId); + } + for (const [slug] of incomingEntries) { + supersededSlugs.add(slug); + } const optionsByModel = hasCatalog ? EMPTY_OPTIONS_BY_MODEL : (() => { - const updated = new Map(current.optionsByModel); - updated.delete(configuration.currentModelId); + const updated = new Map(); + for (const [key, entry] of current.optionsByModel) { + if (key === configuration.currentModelId) continue; + updated.set( + key, + supersededSlugs.size === 0 + ? entry + : stripAdvertisedReasoningSlugs(entry, supersededSlugs), + ); + } updated.set(configuration.currentModelId, { configuration, revision }); while (updated.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = updated.keys().next().value; @@ -713,33 +726,19 @@ const make = Effect.gen(function* () { const reasoningByModel = hasCatalog ? EMPTY_REASONING_BY_MODEL : (() => { - const selfSlug = - configuration.partialOptions !== true ? configuration.currentModelId : null; - const hasSelfToSupersede = - selfSlug !== null && current.reasoningByModel.has(selfSlug); - const incoming = configuration.advertisedReasoning; - const incomingEntries = - incoming === undefined - ? [] - : Object.entries(incoming).filter( - ([slug]) => slug !== configuration.currentModelId, - ); - if (!hasSelfToSupersede && incomingEntries.length === 0) { + const hasSelfToDelete = + configuration.currentModelId !== null && + current.reasoningByModel.has(configuration.currentModelId); + if (!hasSelfToDelete && incomingEntries.length === 0) { return current.reasoningByModel; } const updated = new Map(current.reasoningByModel); - if (hasSelfToSupersede) { - updated.delete(selfSlug); - updated.set(selfSlug, { descriptor: null, revision }); + if (configuration.currentModelId !== null) { + updated.delete(configuration.currentModelId); } - const isPartial = configuration.partialOptions === true; for (const [slug, descriptor] of incomingEntries) { updated.delete(slug); - updated.set(slug, { - descriptor, - revision, - ...(isPartial ? { partialOptions: true } : {}), - }); + updated.set(slug, { descriptor, revision }); } while (updated.size > MAX_TRACKED_MODEL_OPTIONS) { const oldestKey = updated.keys().next().value; @@ -760,7 +759,6 @@ const make = Effect.gen(function* () { } const added: Array = []; if ( - configuration.partialOptions !== true && configuration.currentModelId !== null && Object.hasOwn(catalogReasoning, configuration.currentModelId) && !current.catalogReasoningSupersededSlugs.has(configuration.currentModelId) @@ -819,9 +817,16 @@ const make = Effect.gen(function* () { const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return (yield* getLiveConfigurationWithRevision(instanceId)).configuration; + return (yield* Ref.get(liveConfigurations)).get(instanceId)?.configuration ?? Option.none(); }); + const getLiveConfigurationClearedThroughRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationClearedThroughRevision"] = + Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfigurationClearedThroughRevision")( + function* (instanceId) { + return (yield* Ref.get(liveConfigurations)).get(instanceId)?.clearedThroughRevision ?? 0; + }, + ); + const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = (instanceId, onUpdate, options) => Effect.scoped( @@ -954,6 +959,7 @@ const make = Effect.gen(function* () { clearLiveConfigurationIfRevision, publishLiveConfiguration, getLiveConfiguration, + getLiveConfigurationClearedThroughRevision, getLiveConfigurationWithRevision, watchLiveConfiguration, requestUrlAuthentication, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 0709efc85d46b..6c73a96d71143 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -558,6 +558,54 @@ describe("acpRegistrySnapshotReadiness", () => { (model.capabilities?.optionDescriptors ?? []).map((descriptor) => descriptor.id), ), ).toEqual([["mode"], ["mode", "effort"]]); + + // Live reasoning-only replay (orphaned advertisedReasoning) preserves shared options on all + // models even when previousModels only holds learned model-specific options. + const lowOnlyEffort = { + id: "effort", + label: "Effort", + type: "select" as const, + role: "reasoning" as const, + options: [{ id: "low", label: "Low" }], + currentValue: "low", + }; + const withNarrowOpus = applyAcpRegistryLiveConfiguration( + overlaidEnabled, + { + models: [ + { id: "glm", name: "GLM", description: null }, + { id: "opus", name: "Opus", description: null, reasoningEffort: lowOnlyEffort }, + ], + currentModelId: "glm", + configOptions: [modeDescriptor], + modelsFromModelSelect: true, + }, + [], + ); + const afterOrphanOverlay = applyAcpRegistryLiveConfiguration( + withNarrowOpus, + { + models: [], + currentModelId: null, + configOptions: [], + advertisedReasoning: { opus: effortDescriptor }, + preserveDefault: true, + }, + [], + [], + ); + expect(afterOrphanOverlay.models.find((m) => m.slug === "glm")?.isDefault).toBe(true); + expect( + afterOrphanOverlay.models.map((model) => + (model.capabilities?.optionDescriptors ?? []).map((d) => [d.id, d.currentValue]), + ), + ).toEqual([ + [["mode", "plan"]], + [ + ["mode", "plan"], + ["effort", "high"], + ], + ]); }); it("keeps each Mistral Vibe model's own thinking levels", () => { @@ -1352,6 +1400,7 @@ describe("acpRegistryEnrichmentCache", () => { modelOptionIds: ["effort"], modelsFromModelSelect: false, partialOptions: true, + replaceModelOptions: true, }), ); @@ -1504,6 +1553,7 @@ describe("acpRegistryEnrichmentCache", () => { modelOptionIds: [], modelsFromModelSelect: false, partialOptions: true, + replaceModelOptions: true, }); expect( retainAcpRegistryLiveOptionsAfterProbe( @@ -5775,7 +5825,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }); let blockReasoningWatcher = false; - const releaseReasoningWatcher = yield* Deferred.make(); + let releaseReasoningWatcher = yield* Deferred.make(); const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-advertised-reasoning-", initialModels: { @@ -5787,15 +5837,14 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { watchLiveConfiguration: (instanceId, onUpdate, options) => base.watchLiveConfiguration( instanceId, - (configuration, revision) => - blockReasoningWatcher - ? Effect.sync(() => { - blockReasoningWatcher = false; - }).pipe( - Effect.andThen(Deferred.await(releaseReasoningWatcher)), - Effect.andThen(onUpdate(configuration, revision)), - ) - : onUpdate(configuration, revision), + (configuration, revision) => { + if (!blockReasoningWatcher) return onUpdate(configuration, revision); + blockReasoningWatcher = false; + const gate = releaseReasoningWatcher; + return Deferred.await(gate).pipe( + Effect.andThen(onUpdate(configuration, revision)), + ); + }, options, ), }), @@ -5936,8 +5985,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort"), ).toEqual(highEffort); - // If c advertises effort=high for b and b later reports a full option set without - // reasoning, a superseding probe selecting b without reasoning must not restore high. + // If c advertises effort=high for b and b later reports an empty full option set, + // the live watcher immediately removes b's old selector and a superseding probe selecting + // b without reasoning must not restore high. const modeSelect = { id: "mode", name: "Mode", @@ -5976,7 +6026,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* coordinator.publishLiveConfiguration(identity.instanceId, { models: [], currentModelId: "b", - configOptions: [modeOption], + configOptions: [], modelOptionIds: [], modelsFromModelSelect: false, }); @@ -5998,6 +6048,75 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.some((d) => d.id === "effort") ?? false, ).toBe(false); + // When b previously learned effort=high and reports a full update removing effort while + // a superseding probe selecting a runs before the watcher drains, probe retention preserves + // replacement intent so b's omitted effort is removed while c keeps its learned effort. + const sawBLearnedAndCLearned = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high" && + snapshot.models + .find((m) => m.slug === "c") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "b", + configOptions: [modeOption, highEffort], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + advertisedReasoning: { c: highEffort }, + }); + yield* Fiber.join(sawBLearnedAndCLearned); + + releaseReasoningWatcher = yield* Deferred.make(); + blockReasoningWatcher = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "b", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "a", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* writeModels({ + models: ids.map((id) => ({ modelId: id, name: id })), + configOptions: [modelSelect("a"), modeSelect], + }); + yield* TestClock.adjust("16 minutes"); + const probeConsumedRemoval = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const afterProbeConsumedRemoval = Option.getOrThrow( + yield* Fiber.join(probeConsumedRemoval), + ); + yield* Deferred.succeed(releaseReasoningWatcher, undefined); + expect(afterProbeConsumedRemoval.models.find((m) => m.slug === "a")?.isDefault).toBe(true); + expect( + afterProbeConsumedRemoval.models + .find((m) => m.slug === "b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["mode", "ask"]]); + expect( + afterProbeConsumedRemoval.models + .find((m) => m.slug === "c") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue, + ).toBe("high"); + // When neither live state nor a fresh probe advertises models, keep live reasoning // options on the synthetic default model instead of clearing them. yield* writeModels({ provisional: "" }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index ac1d568b1dd41..0279632e7b83d 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -597,7 +597,11 @@ export function retainAcpRegistryLiveOptionsAfterProbe( retainedAdvertisedReasoning === undefined ? {} : { advertisedReasoning: retainedAdvertisedReasoning }; - const preserveDefaultFields = live.preserveDefault === true ? { preserveDefault: true } : {}; + const replaceModelOptions = + currentProbedModel !== undefined && + currentProbedModel.id !== probe.currentModelId && + (live.partialOptions !== true || live.replaceModelOptions === true); + const replaceModelOptionsFields = replaceModelOptions ? { replaceModelOptions: true } : {}; const configOptions = [...sharedDescriptors, ...modelDescriptors]; if (configOptions.length === 0) { // Keep the running session's model selection, capped tail update, or advertised reasoning @@ -605,9 +609,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( if ( matchingCappedTail === undefined && retainedAdvertisedReasoning === undefined && - (live.preserveDefault === true || - currentProbedModel === undefined || - currentProbedModel.id === probe.currentModelId) + (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) ) { return Option.none(); } @@ -618,7 +620,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelOptionIds: [], modelsFromModelSelect: false, partialOptions: true, - ...preserveDefaultFields, + ...replaceModelOptionsFields, ...overflowFields, ...advertisedReasoningFields, }); @@ -632,7 +634,7 @@ export function retainAcpRegistryLiveOptionsAfterProbe( modelOptionIds: modelDescriptors.map((descriptor) => descriptor.id), modelsFromModelSelect: false, partialOptions: true, - ...preserveDefaultFields, + ...replaceModelOptionsFields, ...overflowFields, ...advertisedReasoningFields, }); @@ -1306,7 +1308,8 @@ export function applyAcpRegistryLiveConfiguration( !useLiveCatalog && effectiveConfigOptions.length === 0 && !hasAdvertisedReasoning && - tailSlotReplacement === undefined + tailSlotReplacement === undefined && + !liveCurrentModelInProbed ? stripReasoningForDisabledModels( withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), disabledReasoningSlugs, @@ -1780,7 +1783,7 @@ export const AcpRegistryDriver: ProviderDriver model.id === configuration.currentModelId) || (configuration.cappedLastModel !== undefined && @@ -2242,7 +2245,6 @@ export const AcpRegistryDriver: ProviderDriver 0 || afterClear.revision > liveSnapshot.revision || accepted.probeOptions !== null; yield* resetAppliedLiveRevisions; @@ -2261,17 +2263,14 @@ export const AcpRegistryDriver: ProviderDriver ({ ...latestCache, entry: { // Cache the winning catalog while keeping the retry TTL from the fresh probe. - provider: - (!probeSupersedesLiveCatalog || acceptedAfter.probeOptions === null) && - published.models !== resolved.models - ? { ...resolved, models: published.models } - : resolved, + provider: !probeSupersedesLiveCatalog + ? { ...resolved, models: published.models } + : resolved, expiresAt: completedAt + acpRegistryProbeTtlMs(provider), }, })); @@ -2346,15 +2345,12 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 18:25:13 +0000 Subject: [PATCH 23/35] fix(acp-registry): recover accepted catalog on readiness handoff, restore pendingOptions probe guard, and honor displaced-tail replacement --- .../AcpRegistryRuntimeCoordinator.test.ts | 42 +- .../src/server/driver.test.ts | 432 +++++++++++++++++- .../src/server/driver.ts | 67 ++- 3 files changed, 496 insertions(+), 45 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index ef8e6332f0064..8f89c369ff2e3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -1105,8 +1105,25 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(protoOrphanAfterClear?.["__proto__"]).toEqual(lowEffort); - // Retained reasoning caps at 256 and evicts older orphaned entries before newer candidates. + // Retained reasoning caps at 256 during clear and evicts older orphaned entries before + // newer candidates (1 orphan + 255 newer candidates + 1 preserved catalog reasoning entry + // carried by a newer same-model update = 257 entries entering retention). yield* coordinator.clearLiveConfiguration(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [ + { id: "catalog-pub", name: "Catalog Pub", description: null }, + { + id: "catalog-model", + name: "Catalog Model", + description: null, + reasoningEffort: lowEffort, + }, + ], + currentModelId: "catalog-pub", + configOptions: [], + modelsFromModelSelect: true, + }); + const capCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, { models: [], currentModelId: "orphan-pub", @@ -1123,7 +1140,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); const newerAdvertised = Object.fromEntries( - Array.from({ length: 256 }, (_, index) => [`newer-${index}`, lowEffort]), + Array.from({ length: 255 }, (_, index) => [`newer-${index}`, lowEffort]), ); yield* coordinator.publishLiveConfiguration(instanceId, { models: [], @@ -1133,9 +1150,21 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, advertisedReasoning: newerAdvertised, }); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "catalog-pub", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["oldest-orphan"] !== undefined, + ), + ).toBe(true); expect( yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: replacedCrossCatalog.catalogRevision, + catalogRevision: capCatalog.catalogRevision, retain: (live) => Option.some({ ...live, partialOptions: true }), }), ).toBe(true); @@ -1147,7 +1176,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(false); expect( afterCapClear.pendingOptions.some( - (e) => e.configuration.advertisedReasoning?.["newer-255"] !== undefined, + (e) => e.configuration.advertisedReasoning?.["newer-0"] !== undefined, + ), + ).toBe(true); + expect( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["catalog-model"] !== undefined, ), ).toBe(true); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 6c73a96d71143..e5dba44f22494 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -42,6 +42,7 @@ import { } from "./driver.ts"; import { ACP_REGISTRY_MAX_MODELS, + type AcpRegistryLiveConfiguration, acpRegistryAdvertisesModelCatalog, acpRegistryProbeResult, normalizeAcpRegistryLiveConfiguration, @@ -1632,6 +1633,55 @@ describe("acpRegistryEnrichmentCache", () => { ), ).toEqual(selectionOnly); + // Second-clear retention preserves replaceModelOptions only when the partial entry already + // carried it, and does not drop an earlier preserveDefault replacement entry. + const secondClearSchema = { + models: [ + { id: "new-model", name: "new-model", description: null }, + { id: "old-model", name: "old-model", description: null }, + ], + currentModelId: "new-model", + configOptions: [], + modelOptionIds: new Set(), + }; + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + preserveDefault: true, + replaceModelOptions: true, + }, + secondClearSchema, + ), + ).toEqual(selectionOnly); + expect( + retainAcpRegistryLiveOptionsAfterProbe( + { + models: [], + currentModelId: "old-model", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + }, + secondClearSchema, + ), + ).toEqual( + Option.some({ + models: [], + currentModelId: "old-model", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + }), + ); + // Never promotes a live shared option into a probe model-specific option on the probe's current model. expect( retainAcpRegistryLiveOptionsAfterProbe( @@ -2321,6 +2371,55 @@ describe("prepareAcpRegistryLiveConfiguration", () => { .find((m) => m.slug === "m255") ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), ).toEqual([["variant", "v2"]]); + // Replacement intent on an off-screen displaced tail replaces (or deletes when empty) prior + // learned descriptors for m255 instead of merging them back. + const replacedDisplacedTailEntry = { + ...prepareAcpRegistryLiveConfiguration([ + ...modelSelect("m255", choices), + effortOption("high"), + ]).toLiveConfiguration({ includeCatalog: false }), + partialOptions: true, + preserveDefault: true, + }; + const mergedDisplacedTail = updateAcpRegistryLearnedModelsFromLive( + learnedWithEarlierOrdinaryTail, + afterEarlierOrdinaryTail.models, + replacedDisplacedTailEntry, + ); + expect( + mergedDisplacedTail + .find((m) => m.slug === "m255") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["variant", "v2"], + ["effort", "high"], + ]); + const replacedDisplacedTail = updateAcpRegistryLearnedModelsFromLive( + learnedWithEarlierOrdinaryTail, + afterEarlierOrdinaryTail.models, + replacedDisplacedTailEntry, + undefined, + { replaceCurrentLearnedOptions: true }, + ); + expect( + replacedDisplacedTail + .find((m) => m.slug === "m255") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); + const clearedDisplacedTail = updateAcpRegistryLearnedModelsFromLive( + learnedWithEarlierOrdinaryTail, + afterEarlierOrdinaryTail.models, + { + ...prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + partialOptions: true, + preserveDefault: true, + }, + undefined, + { replaceCurrentLearnedOptions: true }, + ); + expect(clearedDisplacedTail.some((m) => m.slug === "m255")).toBe(false); // Restoring m255 into slot 255 while a different model (m0) is current with its own // `variant` option must keep m255's off-screen learned `variant=v2` intact. const m0RestoringM255 = { @@ -3931,6 +4030,152 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); + // When only an earlier preserveDefault entry remains in pendingOptions (configuration is + // None), invalidateCaches + refresh must keep probeOptions active so the retained override + // survives and later stale live options are still filtered against the new probe schema. + yield* writeModels({ + models: ["new-model", "old-model"], + configOptions: [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "new-model", + options: [ + { value: "new-model", name: "New Model" }, + { value: "old-model", name: "Old Model" }, + ], + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + }); + const withEffortProbe = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(withEffortProbe); + + const sawPendingOverride = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.models.find((m) => m.slug === "new-model")?.isDefault === true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Fiber.join(sawPendingOverride); + + yield* TestClock.adjust("16 minutes"); + const clearedToPendingOnly = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(clearedToPendingOnly); + expect(Option.isNone(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( + true, + ); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(identity.instanceId)).pendingOptions + .length, + ).toBeGreaterThan(0); + + yield* instance.invalidateCaches ?? Effect.void; + const afterInvalidatePendingOnly = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const invalidatedSnap = Option.getOrThrow(yield* Fiber.join(afterInvalidatePendingOnly)); + expect( + invalidatedSnap.models + .find((m) => m.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue, + ).toBe("low"); + + const sawFilteredLegacy = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + { + id: "legacy", + label: "Legacy", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const filteredSnap = Option.getOrThrow(yield* Fiber.join(sawFilteredLegacy)); + expect( + filteredSnap.models.map((m) => [ + m.slug, + (m.capabilities?.optionDescriptors ?? []).map((d) => d.id), + ]), + ).toEqual([ + ["new-model", ["effort"]], + ["old-model", ["effort"]], + ]); + yield* writeModels(["new-model", "old-model", "other-model"]); + yield* TestClock.adjust("16 minutes"); + const restoredForAuthInvalidate = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); @@ -4569,6 +4814,54 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { const handoffCallbackBlocked = yield* Deferred.make(); let blockHandoffWatcher = false; + let retiringRaceArmed = false; + let retiringRacePending = false; + let retiringWatcherReady = yield* Deferred.make(); + let trackRetiringWatcherReady = false; + let retiringReadyCount = 0; + let retiringOnUpdate: + | ((configuration: AcpRegistryLiveConfiguration, revision: number) => Effect.Effect) + | null = null; + let retiringRaceUpdates: Array<{ + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; + }> = []; + const racedCatalog: AcpRegistryLiveConfiguration = { + models: [ + { id: "raced-a", name: "Raced A", description: null }, + { id: "raced-b", name: "Raced B", description: null }, + ], + currentModelId: "raced-a", + configOptions: [], + modelsFromModelSelect: true, + }; + const racedOptions: AcpRegistryLiveConfiguration = { + models: [], + currentModelId: "raced-b", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }; + const markRetiringReady = () => + Effect.suspend(() => { + if (!trackRetiringWatcherReady) return Effect.void; + retiringReadyCount += 1; + if (retiringReadyCount < 2) return Effect.void; + trackRetiringWatcherReady = false; + return Deferred.succeed(retiringWatcherReady, undefined).pipe(Effect.asVoid); + }); const { coordinator, instance, @@ -4580,20 +4873,65 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { initialModels: ["old-model", "other-model"], wrapCoordinator: (base) => ({ ...base, - watchLiveConfiguration: (instanceId, onUpdate, options) => - base.watchLiveConfiguration( - instanceId, - (configuration, revision) => - blockHandoffWatcher && configuration.currentModelId === "handoff-a" - ? Effect.sync(() => { - blockHandoffWatcher = false; - }).pipe( - Effect.andThen(Deferred.succeed(handoffCallbackBlocked, undefined)), - Effect.andThen(Effect.never), - ) - : onUpdate(configuration, revision), - options, + getUrlAuthAction: (instanceId) => + base.getUrlAuthAction(instanceId).pipe( + Effect.tap(() => + retiringRaceArmed + ? Effect.gen(function* () { + retiringRaceArmed = false; + retiringRacePending = true; + yield* base.publishLiveConfiguration(instanceId, racedCatalog); + const r2 = (yield* base.getLiveConfigurationWithRevision(instanceId)) + .revision; + yield* base.publishLiveConfiguration(instanceId, racedOptions); + const r3 = (yield* base.getLiveConfigurationWithRevision(instanceId)) + .revision; + retiringRaceUpdates = [ + { configuration: racedCatalog, revision: r2 }, + { configuration: racedOptions, revision: r3 }, + ]; + }) + : Effect.void, + ), + ), + watchUrlAuthAction: (instanceId, onUpdate) => + markRetiringReady().pipe( + Effect.andThen(base.watchUrlAuthAction(instanceId, onUpdate)), + Effect.ensuring( + Effect.suspend(() => { + if (!retiringRacePending || retiringOnUpdate === null) return Effect.void; + retiringRacePending = false; + const runUpdate = retiringOnUpdate; + const updates = retiringRaceUpdates; + retiringRaceUpdates = []; + return Effect.forEach(updates, ({ configuration, revision }) => + runUpdate(configuration, revision), + ).pipe(Effect.asVoid); + }), + ), ), + watchLiveConfiguration: (instanceId, onUpdate, options) => { + retiringOnUpdate = onUpdate; + return markRetiringReady().pipe( + Effect.andThen( + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => { + if (retiringRacePending && onUpdate === retiringOnUpdate) return Effect.void; + return blockHandoffWatcher && configuration.currentModelId === "handoff-a" + ? Effect.sync(() => { + blockHandoffWatcher = false; + }).pipe( + Effect.andThen(Deferred.succeed(handoffCallbackBlocked, undefined)), + Effect.andThen(Effect.never), + ) + : onUpdate(configuration, revision); + }, + options, + ), + ), + ); + }, }), }); @@ -4633,11 +4971,41 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* withBlockedForegroundStartup( Effect.gen(function* () { + retiringWatcherReady = yield* Deferred.make(); + trackRetiringWatcherReady = true; yield* instance.snapshot.refresh; + yield* Deferred.await(retiringWatcherReady); expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ "handoff-a", "handoff-b", ]); + + // If the retiring live watcher applies a newer catalog (R2) and options update (R3) + // after readiness reads R1 and applySnapshotBase commits R1, the replacement watcher + // must restore the already-accepted catalog instead of leaving R1 visible. + const sawRacedRestored = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.map((m) => m.slug).join() === "raced-a,raced-b" && + snapshot.models.find((m) => m.slug === "raced-b")?.isDefault === true && + snapshot.models + .find((m) => m.slug === "raced-b") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + retiringRaceArmed = true; + yield* instance.snapshot.refresh; + const restoredRaced = Option.getOrThrow(yield* Fiber.join(sawRacedRestored)); + expect(restoredRaced.models.map((m) => m.slug)).toEqual(["raced-a", "raced-b"]); + expect(restoredRaced.models.find((m) => m.slug === "raced-b")?.isDefault).toBe(true); + expect( + restoredRaced.models + .find((m) => m.slug === "raced-b") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["effort", "high"]]); }), ); }), @@ -5826,12 +6194,24 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { let blockReasoningWatcher = false; let releaseReasoningWatcher = yield* Deferred.make(); + let gateProbeResolve = false; + const probeResolveEntered = yield* Deferred.make(); + const releaseProbeResolve = yield* Deferred.make(); const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ prefix: "acp-driver-advertised-reasoning-", initialModels: { models: entries, configOptions: [modelSelect("a")], }, + onResolve: () => + gateProbeResolve + ? Effect.sync(() => { + gateProbeResolve = false; + }).pipe( + Effect.andThen(Deferred.succeed(probeResolveEntered, undefined)), + Effect.andThen(Deferred.await(releaseProbeResolve)), + ) + : Effect.void, wrapCoordinator: (base) => ({ ...base, watchLiveConfiguration: (instanceId, onUpdate, options) => @@ -6076,6 +6456,21 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }); yield* Fiber.join(sawBLearnedAndCLearned); + yield* writeModels({ + models: ids.map((id) => ({ modelId: id, name: id })), + configOptions: [modelSelect("a"), modeSelect], + }); + yield* TestClock.adjust("16 minutes"); + gateProbeResolve = true; + const probeConsumedRemoval = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + const refreshFiber = yield* instance.snapshot.refresh.pipe( + Effect.forkScoped({ startImmediately: true }), + ); + // Wait until readiness has finished and the probe is in flight before publishing b's + // removal and a's selection, so readiness cannot replay them ahead of probe retention. + yield* Deferred.await(probeResolveEntered); releaseReasoningWatcher = yield* Deferred.make(); blockReasoningWatcher = true; yield* coordinator.publishLiveConfiguration(identity.instanceId, { @@ -6092,15 +6487,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { modelOptionIds: [], modelsFromModelSelect: false, }); - yield* writeModels({ - models: ids.map((id) => ({ modelId: id, name: id })), - configOptions: [modelSelect("a"), modeSelect], - }); - yield* TestClock.adjust("16 minutes"); - const probeConsumedRemoval = yield* waitForEnriched().pipe( - Effect.forkScoped({ startImmediately: true }), - ); - yield* instance.snapshot.refresh; + yield* Deferred.succeed(releaseProbeResolve, undefined); + yield* Fiber.join(refreshFiber); const afterProbeConsumedRemoval = Option.getOrThrow( yield* Fiber.join(probeConsumedRemoval), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 0279632e7b83d..b3dfe220ef372 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -393,14 +393,23 @@ export function updateAcpRegistryLearnedModelsFromLive( isModelSpecificDescriptor(descriptor, modelOptionIds) && (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), ); - if (incoming.length > 0) { + const previous = learnedBySlug.get(slug); + const replace = options?.replaceCurrentLearnedOptions === true; + if (incoming.length === 0) { + if (replace && previous !== undefined) { + learnedBySlug.delete(slug); + if (slug === lastLearnedSlug) lastLearnedSlug = undefined; + dataChanged = true; + } + } else { const incomingIds = new Set(incoming.map((descriptor) => descriptor.id)); - const previous = learnedBySlug.get(slug); - const preservedPrevious = (previous?.capabilities?.optionDescriptors ?? []).filter( - (descriptor) => - !incomingIds.has(descriptor.id) && - (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), - ); + const preservedPrevious = replace + ? [] + : (previous?.capabilities?.optionDescriptors ?? []).filter( + (descriptor) => + !incomingIds.has(descriptor.id) && + (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), + ); const updated: ServerProviderModel = { slug, name: configuration.cappedLastModel.name, @@ -2245,6 +2254,7 @@ export const AcpRegistryDriver: ProviderDriver 0 || afterClear.revision > liveSnapshot.revision || accepted.probeOptions !== null; yield* resetAppliedLiveRevisions; @@ -2350,26 +2360,45 @@ export const AcpRegistryDriver: ProviderDriver 0 && - Equal.equals(rawCurrent.models, accepted.models) - ? { ...rawCurrent, models: accepted.models } - : rawCurrent; if ( - !current.installed || - (current.auth.status === "unauthenticated" && + !rawCurrent.installed || + (rawCurrent.auth.status === "unauthenticated" && configuration.models.length === 0) ) { return; } + const accepted = yield* Ref.get(acceptedCatalog); + if (revision < appliedRevision) { + // A retiring watcher can apply a newer catalog and options between + // readiness returning and applySnapshotBase committing. Restore the + // already-accepted catalog without replaying the stale intermediate step. + if ( + accepted.probeOptions === null && + accepted.models.length > 0 && + !Equal.equals(rawCurrent.models, accepted.models) + ) { + const { message: _staleMessage, ...rest } = rawCurrent; + yield* publishSnapshot({ + ...rest, + ...(rawCurrent.status !== "ready" && rawCurrent.message !== undefined + ? { message: rawCurrent.message } + : {}), + models: accepted.models, + }); + } + return; + } + // Always base live updates on acceptedCatalog.models when no probe baseline is + // active, preserving both WeakMap overflow-tail identity and any newer catalog + // whose publish was dropped during a readiness generation handoff. + const current = + accepted.probeOptions === null && accepted.models.length > 0 + ? { ...rawCurrent, models: accepted.models } + : rawCurrent; const next = yield* applyLiveConfigurationStep(current, configuration, { preserveStatus: current.status !== "ready", revision, From eb29a6054e14d531dc0fe08069507749e3238fb6 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 18:59:16 +0000 Subject: [PATCH 24/35] fix(acp-registry): track live session reset revision and simplify watcher --- .../src/server/driver.test.ts | 227 +++++++++++++++++- .../src/server/driver.ts | 77 +++--- 2 files changed, 260 insertions(+), 44 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index e5dba44f22494..a3b1d337c7998 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2420,6 +2420,26 @@ describe("prepareAcpRegistryLiveConfiguration", () => { { replaceCurrentLearnedOptions: true }, ); expect(clearedDisplacedTail.some((m) => m.slug === "m255")).toBe(false); + // Even without replacement intent, an empty displaced-tail update strips reasoning when + // reasoning is disabled on that model. + const disabledReasoningDisplacedTail = updateAcpRegistryLearnedModelsFromLive( + replacedDisplacedTail, + afterEarlierOrdinaryTail.models, + { + ...prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + cappedLastModel: { + id: "m255", + name: "Model 255", + description: null, + reasoningEffort: null, + }, + partialOptions: true, + preserveDefault: true, + }, + ); + expect(disabledReasoningDisplacedTail.some((m) => m.slug === "m255")).toBe(false); // Restoring m255 into slot 255 while a different model (m0) is current with its own // `variant` option must keep m255's off-screen learned `variant=v2` intact. const m0RestoringM255 = { @@ -3813,6 +3833,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const afterUninstalledLive = yield* instance.snapshot.getSnapshot; expect(afterUninstalledLive.installed).toBe(false); expect(afterUninstalledLive.status).toBe("error"); + expect(afterUninstalledLive.models).toEqual(uninstalledSnap.models); // Direct readiness refresh while not_found also stays error/uninstalled despite live config. inspectHandler = () => notFoundInspection; @@ -3843,8 +3864,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const probeEntered = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); const signOutRejected = yield* Deferred.make(); + const unauthLiveProcessed = yield* Deferred.make(); let gateNextResolve = false; let injectCatalogBeforeSignOutClear = false; + let trackUnauthLiveUpdate = false; const { directory, coordinator, @@ -3857,6 +3880,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { initialModels: ["new-model", "old-model", "other-model"], wrapCoordinator: (base) => ({ ...base, + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + onUpdate(configuration, revision).pipe( + Effect.tap(() => + trackUnauthLiveUpdate + ? Deferred.succeed(unauthLiveProcessed, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + options, + ), clearLiveConfigurationIfRevision: (instanceId, options) => Effect.gen(function* () { if (injectCatalogBeforeSignOutClear && options.retain === undefined) { @@ -3967,6 +4003,35 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(restored); + // Sign-out cleared liveSessionResetRevision, so a fresh options-only update on the + // re-authenticated probe is accepted rather than filtered against an empty probe schema. + const sawFreshAfterSignOut = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "fresh-after-signout") === + true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "fresh-after-signout", + label: "Fresh After Signout", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["fresh-after-signout"], + modelsFromModelSelect: false, + }); + expect(Option.isSome(yield* Fiber.join(sawFreshAfterSignOut))).toBe(true); + const liveBeforeDisable = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => @@ -4014,6 +4079,35 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(restored2); + // disableProvider cleared liveSessionResetRevision, so a fresh options-only update on + // the new probe is accepted rather than filtered against the probe's empty option schema. + const sawFreshAfterDisable = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.some((d) => d.id === "fresh-after-disable") === + true, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "fresh-after-disable", + label: "Fresh After Disable", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["fresh-after-disable"], + modelsFromModelSelect: false, + }); + expect(Option.isSome(yield* Fiber.join(sawFreshAfterDisable))).toBe(true); + yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.snapshot.refresh; @@ -4173,6 +4267,105 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ["new-model", ["effort"]], ["old-model", ["effort"]], ]); + + // Even when a superseding probe after invalidateCaches drops the last pending override + // (leaving pendingOptions empty and configuration None), probeOptions must remain stored + // so later options-only updates from the old session still filter out stale options. + yield* writeModels({ + models: [ + { modelId: "replaced-model-a", name: "Replaced Model A" }, + { modelId: "replaced-model-b", name: "Replaced Model B" }, + ], + configOptions: [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "replaced-model-a", + options: [ + { value: "replaced-model-a", name: "Replaced Model A" }, + { value: "replaced-model-b", name: "Replaced Model B" }, + ], + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + }); + yield* instance.invalidateCaches ?? Effect.void; + const droppedLastOverride = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(droppedLastOverride); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(identity.instanceId)).pendingOptions, + ).toEqual([]); + + // A second invalidateCaches + probe with zero pending overrides left still remembers the + // superseded live session and filters legacy options on subsequent live updates. + yield* instance.invalidateCaches ?? Effect.void; + const secondEmptyClear = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(secondEmptyClear); + + const sawStillFilteredLegacy = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "replaced-model-a") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "effort")?.currentValue === + "low", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "replaced-model-a", + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + role: "reasoning", + currentValue: "low", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + { + id: "legacy", + label: "Legacy", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + const stillFilteredSnap = Option.getOrThrow(yield* Fiber.join(sawStillFilteredLegacy)); + expect( + stillFilteredSnap.models.map((m) => [ + m.slug, + (m.capabilities?.optionDescriptors ?? []).map((d) => d.id), + ]), + ).toEqual([ + ["replaced-model-a", ["effort"]], + ["replaced-model-b", []], + ]); yield* writeModels(["new-model", "old-model", "other-model"]); yield* TestClock.adjust("16 minutes"); @@ -4233,6 +4426,35 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( true, ); + + // An options-only update arriving while unauthenticated must be ignored by the watcher. + yield* TestClock.adjust("16 minutes"); + const signedOutForWatcher = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const unauthSnap = Option.getOrThrow(yield* Fiber.join(signedOutForWatcher)); + trackUnauthLiveUpdate = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [{ id: "plan", label: "Plan" }], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Deferred.await(unauthLiveProcessed); + trackUnauthLiveUpdate = false; + expect((yield* instance.snapshot.getSnapshot).models).toEqual(unauthSnap.models); }), ); @@ -4981,8 +5203,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ]); // If the retiring live watcher applies a newer catalog (R2) and options update (R3) - // after readiness reads R1 and applySnapshotBase commits R1, the replacement watcher - // must restore the already-accepted catalog instead of leaving R1 visible. + // after readiness reads R1 and applySnapshotBase commits R1, basing live watcher steps + // on acceptedCatalog.models keeps R3 from corrupting acceptedCatalog back to R1 and + // lets the replacement watcher's R3 replay publish the already-accepted catalog. const sawRacedRestored = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index b3dfe220ef372..84e371e0b5bea 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -395,38 +395,36 @@ export function updateAcpRegistryLearnedModelsFromLive( ); const previous = learnedBySlug.get(slug); const replace = options?.replaceCurrentLearnedOptions === true; - if (incoming.length === 0) { - if (replace && previous !== undefined) { + const incomingIds = new Set(incoming.map((descriptor) => descriptor.id)); + const preservedPrevious = replace + ? [] + : (previous?.capabilities?.optionDescriptors ?? []).filter( + (descriptor) => + !incomingIds.has(descriptor.id) && + (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), + ); + const combined = [...preservedPrevious, ...incoming]; + if (combined.length === 0) { + if (previous !== undefined) { learnedBySlug.delete(slug); - if (slug === lastLearnedSlug) lastLearnedSlug = undefined; dataChanged = true; } } else { - const incomingIds = new Set(incoming.map((descriptor) => descriptor.id)); - const preservedPrevious = replace - ? [] - : (previous?.capabilities?.optionDescriptors ?? []).filter( - (descriptor) => - !incomingIds.has(descriptor.id) && - (!isReasoningDisabled || !isReasoningDescriptor(descriptor)), - ); const updated: ServerProviderModel = { slug, name: configuration.cappedLastModel.name, isCustom: false, capabilities: createModelCapabilities({ - optionDescriptors: [...preservedPrevious, ...incoming], + optionDescriptors: combined, }), }; if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { learnedBySlug.delete(slug); learnedBySlug.set(slug, updated); - lastLearnedSlug = slug; dataChanged = true; } else if (slug !== lastLearnedSlug) { learnedBySlug.delete(slug); learnedBySlug.set(slug, previous); - lastLearnedSlug = slug; orderTouched = true; } } @@ -1696,6 +1694,9 @@ export const AcpRegistryDriver: ProviderDriver(EMPTY_ACCEPTED_CATALOG); const clearAcceptedCatalog = Ref.set(acceptedCatalog, EMPTY_ACCEPTED_CATALOG); + // Tracks the coordinator revision through which live state was explicitly reset (sign-out or + // full cache clear), excluding invalidateCaches which preserves coordinator state. + const liveSessionResetRevision = yield* Ref.make(0); const lastObservedLiveRevision = yield* Ref.make(0); const lastAppliedLiveCatalogRevision = yield* Ref.make(0); const lastAppliedLiveRevision = yield* Ref.make(0); @@ -2251,12 +2252,7 @@ export const AcpRegistryDriver: ProviderDriver 0 || - afterClear.revision > liveSnapshot.revision || - accepted.probeOptions !== null; + afterClear.revision > (yield* Ref.get(liveSessionResetRevision)); yield* resetAppliedLiveRevisions; yield* Ref.set(acceptedCatalog, { models: resolved.models, @@ -2301,6 +2297,14 @@ export const AcpRegistryDriver: ProviderDriver 0 && - !Equal.equals(rawCurrent.models, accepted.models) - ) { - const { message: _staleMessage, ...rest } = rawCurrent; - yield* publishSnapshot({ - ...rest, - ...(rawCurrent.status !== "ready" && rawCurrent.message !== undefined - ? { message: rawCurrent.message } - : {}), - models: accepted.models, - }); - } - return; - } // Always base live updates on acceptedCatalog.models when no probe baseline is // active, preserving both WeakMap overflow-tail identity and any newer catalog // whose publish was dropped during a readiness generation handoff. @@ -2482,7 +2466,16 @@ export const AcpRegistryDriver: ProviderDriver + Ref.set(liveSessionResetRevision, clearedThrough), + ), + ) ).pipe( Effect.andThen( options?.clearCommands === true From aeca1fc4440054dd62d88388014f53b8d1b59ad8 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 19:34:34 +0000 Subject: [PATCH 25/35] fix(acp-registry): seed reset revision on create and compare clearedThroughRevision --- .../src/server/driver.test.ts | 170 ++++++++++++++++-- .../src/server/driver.ts | 22 ++- 2 files changed, 174 insertions(+), 18 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index a3b1d337c7998..1bed6199e76f5 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2421,25 +2421,68 @@ describe("prepareAcpRegistryLiveConfiguration", () => { ); expect(clearedDisplacedTail.some((m) => m.slug === "m255")).toBe(false); // Even without replacement intent, an empty displaced-tail update strips reasoning when - // reasoning is disabled on that model. + // reasoning is disabled on that model while preserving unrelated learned options, and removes + // the entry once no descriptors remain. + const emptyDisabledM255Update = { + ...prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ + includeCatalog: false, + }), + cappedLastModel: { + id: "m255", + name: "Model 255", + description: null, + reasoningEffort: null, + }, + partialOptions: true, + preserveDefault: true, + }; + const disabledReasoningPreservingVariant = updateAcpRegistryLearnedModelsFromLive( + mergedDisplacedTail, + afterEarlierOrdinaryTail.models, + emptyDisabledM255Update, + ); + expect( + disabledReasoningPreservingVariant + .find((m) => m.slug === "m255") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v2"]]); const disabledReasoningDisplacedTail = updateAcpRegistryLearnedModelsFromLive( replacedDisplacedTail, afterEarlierOrdinaryTail.models, + emptyDisabledM255Update, + ); + expect(disabledReasoningDisplacedTail.some((m) => m.slug === "m255")).toBe(false); + // An unchanged empty displaced-tail update still refreshes the model's MRU position. + const m255MergedLearned = mergedDisplacedTail.find((m) => m.slug === "m255")!; + const learnedWithLaterOther = [ + ...mergedDisplacedTail, + { + slug: "m999", + name: "Model 999", + isCustom: false, + capabilities: m255MergedLearned.capabilities, + }, + ]; + const touchedDisplacedTail = updateAcpRegistryLearnedModelsFromLive( + learnedWithLaterOther, + afterEarlierOrdinaryTail.models, { ...prepareAcpRegistryLiveConfiguration(modelSelect("m255", choices)).toLiveConfiguration({ includeCatalog: false, }), - cappedLastModel: { - id: "m255", - name: "Model 255", - description: null, - reasoningEffort: null, - }, partialOptions: true, preserveDefault: true, }, ); - expect(disabledReasoningDisplacedTail.some((m) => m.slug === "m255")).toBe(false); + expect(touchedDisplacedTail.at(-1)?.slug).toBe("m255"); + expect( + touchedDisplacedTail + .find((m) => m.slug === "m255") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([ + ["variant", "v2"], + ["effort", "high"], + ]); // Restoring m255 into slot 255 while a different model (m0) is current with its own // `variant` option must keep m255's off-screen learned `variant=v2` intact. const m0RestoringM255 = { @@ -3866,8 +3909,20 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const signOutRejected = yield* Deferred.make(); const unauthLiveProcessed = yield* Deferred.make(); let gateNextResolve = false; + let injectModeAfterInitialClear = true; let injectCatalogBeforeSignOutClear = false; let trackUnauthLiveUpdate = false; + // Pre-populate the shared coordinator before create() to simulate a rebuilt driver instance: + // create() must seed liveSessionResetRevision from its clear so the first probe does not + // treat the prior instance's cleared publications as an active superseded live session. + const sharedCoordinator = + yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + yield* sharedCoordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "prior-instance-model", name: "Prior Instance Model", description: null }], + currentModelId: "prior-instance-model", + configOptions: [], + modelsFromModelSelect: true, + }); const { directory, coordinator, @@ -3910,7 +3965,32 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.succeed(signOutRejected, undefined); return cleared; } - return yield* base.clearLiveConfigurationIfRevision(instanceId, options); + const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); + // Publish an options-only update right after the clear returns (before the driver + // reads clearedThroughRevision) to verify supersession checks clearedThroughRevision + // rather than the post-clear live revision. + if (cleared && injectModeAfterInitialClear && options.retain !== undefined) { + injectModeAfterInitialClear = false; + yield* base.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [ + { id: "plan", label: "Plan" }, + { id: "code", label: "Code" }, + ], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + } + return cleared; }), }), onResolve: () => @@ -3923,11 +4003,48 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), }); + // Neither the prior instance's cleared state nor an options-only publish arriving right + // after the clear should mark the rebuilt driver's first probe as superseding a live session. const initial = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - yield* Fiber.join(initial); + const initialSnap = Option.getOrThrow(yield* Fiber.join(initial)); + expect( + initialSnap.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, + ).toBe("plan"); + const sawPostStartModeUpdate = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue === + "code", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "code", + options: [ + { id: "plan", label: "Plan" }, + { id: "code", label: "Code" }, + ], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect(Option.isSome(yield* Fiber.join(sawPostStartModeUpdate))).toBe(true); // Unauthenticated post-TTL probe racing an options-only live update must still keep // status: warning, auth: unauthenticated, sign-in message, and models: ["default"]. @@ -4455,6 +4572,39 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.await(unauthLiveProcessed); trackUnauthLiveUpdate = false; expect((yield* instance.snapshot.getSnapshot).models).toEqual(unauthSnap.models); + + // A full live catalog arriving while unauthenticated must still apply and be saved to + // acceptedCatalog so a subsequent readiness refresh without live coordinator state keeps it. + const sawUnauthCatalog = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.map((m) => m.slug).join() === "unauth-live-a,unauth-live-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "unauth-live-a", name: "Unauth Live A", description: null }, + { id: "unauth-live-b", name: "Unauth Live B", description: null }, + ], + currentModelId: "unauth-live-a", + configOptions: [], + modelsFromModelSelect: true, + }); + expect( + Option.getOrThrow(yield* Fiber.join(sawUnauthCatalog)).models.map((m) => m.slug), + ).toEqual(["unauth-live-a", "unauth-live-b"]); + yield* coordinator.clearLiveConfiguration(identity.instanceId); + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "unauth-live-a", + "unauth-live-b", + ]); + }), + ); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 84e371e0b5bea..4ec7b96fcbf82 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1694,9 +1694,14 @@ export const AcpRegistryDriver: ProviderDriver(EMPTY_ACCEPTED_CATALOG); const clearAcceptedCatalog = Ref.set(acceptedCatalog, EMPTY_ACCEPTED_CATALOG); - // Tracks the coordinator revision through which live state was explicitly reset (sign-out or - // full cache clear), excluding invalidateCaches which preserves coordinator state. - const liveSessionResetRevision = yield* Ref.make(0); + // Tracks the coordinator revision through which live state was explicitly reset (instance + // creation, sign-out, or full cache clear), excluding invalidateCaches which preserves + // coordinator state. + const liveSessionResetRevision = yield* Ref.make( + Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationClearedThroughRevision(instanceId) + : 0, + ); const lastObservedLiveRevision = yield* Ref.make(0); const lastAppliedLiveCatalogRevision = yield* Ref.make(0); const lastAppliedLiveRevision = yield* Ref.make(0); @@ -2247,12 +2252,13 @@ export const AcpRegistryDriver: ProviderDriver (yield* Ref.get(liveSessionResetRevision)); + clearedThroughRevision > (yield* Ref.get(liveSessionResetRevision)); yield* resetAppliedLiveRevisions; yield* Ref.set(acceptedCatalog, { models: resolved.models, From 52195395373f7fe42af7c04e3cd0b1976f555b0f Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 19:55:10 +0000 Subject: [PATCH 26/35] refactor(acp-registry): return cleared watermark atomically from live clear methods --- .../AcpRegistryRuntimeCoordinator.test.ts | 220 +++++++++++------- .../server/AcpRegistryRuntimeCoordinator.ts | 18 +- .../src/server/driver.test.ts | 207 ++++++++-------- .../src/server/driver.ts | 67 +++--- 4 files changed, 271 insertions(+), 241 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 8f89c369ff2e3..663f617a685bf 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -461,6 +461,8 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: true, }); + expect(yield* coordinator.clearLiveConfiguration(instanceId)).toBe(0); + yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v1")); const first = yield* coordinator.getLiveConfigurationWithRevision(instanceId); yield* coordinator.publishLiveConfiguration(instanceId, configFor("model-v2")); @@ -470,7 +472,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: first.catalogRevision, }), - ).toBe(false); + ).toEqual(Option.none()); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, ).toBe(0); @@ -548,7 +550,7 @@ describe("AcpRegistryRuntimeCoordinator", () => { return Option.some({ ...live, partialOptions: true }); }, }), - ).toBe(true); + ).toEqual(Option.some(optionsSnap.revision)); // Every candidate passed to retain has catalog models and provenance stripped. expect(seenRetainInputs).toEqual([ ["model-v3", 0, false], @@ -595,7 +597,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { catalogRevision: third.catalogRevision, }), - ).toBe(true); + ).toEqual(Option.some(optionsSnap.revision)); + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: third.catalogRevision, + }), + ).toEqual(Option.some(optionsSnap.revision)); expect(yield* coordinator.getLiveConfigurationWithRevision(instanceId)).toEqual({ ...optionsSnap, catalog: Option.none(), @@ -631,10 +638,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { // Clear retention caps pendingOptions at 256 even when catalog options plus 256 // per-model updates are all retained (evicting the oldest entry, catalog-model). expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: catalogForCap.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: catalogForCap.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const clearedCap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(clearedCap.pendingOptions).toHaveLength(256); @@ -645,13 +654,15 @@ describe("AcpRegistryRuntimeCoordinator", () => { // preserveDefault, getLiveConfiguration returns none so Copilot does not read an // earlier model's effort. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: catalogForCap.catalogRevision, - retain: (live) => - live.currentModelId === "m256" - ? Option.none() - : Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: catalogForCap.catalogRevision, + retain: (live) => + live.currentModelId === "m256" + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const clearedEarlierOnly = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(clearedEarlierOnly.configuration).toEqual(Option.none()); @@ -690,10 +701,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: advertisedCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: advertisedCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterAdvClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(afterAdvClear.pendingOptions).toEqual([ @@ -725,13 +738,15 @@ describe("AcpRegistryRuntimeCoordinator", () => { // If retain strips advertisedReasoning (e.g. probe disabled reasoning for model-c) // and model-b has no model-specific options, the earlier entry is dropped. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: advertisedCatalog.catalogRevision, - retain: (live) => { - const { advertisedReasoning: _dropped, ...rest } = live; - return Option.some({ ...rest, partialOptions: true }); - }, - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: advertisedCatalog.catalogRevision, + retain: (live) => { + const { advertisedReasoning: _dropped, ...rest } = live; + return Option.some({ ...rest, partialOptions: true }); + }, + }), + ), ).toBe(true); const afterDisabledClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(afterDisabledClear.pendingOptions).toHaveLength(1); @@ -753,10 +768,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { }); const reasoningCatalog = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: reasoningCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: reasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterCatalogReasoningClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -798,10 +815,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: sameModelCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: sameModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterSameModelClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect(afterSameModelClear.pendingOptions).toHaveLength(2); @@ -857,10 +876,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: crossModelCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: crossModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterCrossModelClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -882,10 +903,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: crossModelCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: crossModelCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterSecondCrossClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -1014,10 +1037,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: replacedCrossCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterReplacedCrossClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -1046,13 +1071,15 @@ describe("AcpRegistryRuntimeCoordinator", () => { // A follow-up clear whose retain drops only the orphaned reasoning entry must update // stored state rather than short-circuiting as a no-op. expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: replacedCrossCatalog.catalogRevision, - retain: (live) => - live.currentModelId === null - ? Option.none() - : Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => + live.currentModelId === null + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions.some( @@ -1091,10 +1118,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(protoOrphanBeforeClear?.["__proto__"]).toEqual(lowEffort); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: replacedCrossCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: replacedCrossCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const protoOrphanAfterClear = (yield* coordinator.getLiveConfigurationWithRevision( instanceId, @@ -1163,10 +1192,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { ), ).toBe(true); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: capCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: capCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterCapClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( @@ -1234,14 +1265,16 @@ describe("AcpRegistryRuntimeCoordinator", () => { ), ).toBe(false); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: dropReasoningCatalog.catalogRevision, - retain: (live) => - live.currentModelId === "model-churn" || - (live.currentModelId === "model-b" && live.configOptions.length === 0) - ? Option.none() - : Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => + live.currentModelId === "model-churn" || + (live.currentModelId === "model-b" && live.configOptions.length === 0) + ? Option.none() + : Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions, @@ -1279,10 +1312,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: dropReasoningCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterSelfSupersedeClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -1325,10 +1360,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { modelsFromModelSelect: false, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: dropReasoningCatalog.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: dropReasoningCatalog.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterCrossSupersedeClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); @@ -1343,8 +1380,15 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toEqual([[modelYReasoningSnap.revision, null, "low"]]); // Case 6: Full clearLiveConfiguration and a fresh catalog publish both reset tracked - // reasoningByModel and catalogReasoningSupersededSlugs. - yield* coordinator.clearLiveConfiguration(instanceId); + // reasoningByModel and catalogReasoningSupersededSlugs, and clearLiveConfiguration returns + // the resulting cleared-through watermark. + const beforeFullClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(yield* coordinator.clearLiveConfiguration(instanceId)).toBe( + beforeFullClear.revision, + ); + expect(yield* coordinator.clearLiveConfiguration(instanceId)).toBe( + beforeFullClear.revision, + ); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions, ).toEqual([]); @@ -1384,10 +1428,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { const freshCatalogAfterSupersede = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: freshCatalogAfterSupersede.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: freshCatalogAfterSupersede.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); expect( (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).pendingOptions.map( @@ -1441,10 +1487,12 @@ describe("AcpRegistryRuntimeCoordinator", () => { cappedLastModel: ordinaryTailModel, }); expect( - yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { - catalogRevision: freshCatalogAfterSupersede.catalogRevision, - retain: (live) => Option.some({ ...live, partialOptions: true }), - }), + Option.isSome( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: freshCatalogAfterSupersede.catalogRevision, + retain: (live) => Option.some({ ...live, partialOptions: true }), + }), + ), ).toBe(true); const afterOverflowClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); expect( diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index 6756e160accfc..f1440b0e4fe08 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -250,7 +250,7 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< instanceId: ProviderInstanceId, onUpdate: (commands: AcpRegistryAvailableCommands) => Effect.Effect, ) => Effect.Effect; - readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; + readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; readonly clearLiveConfigurationIfRevision: ( instanceId: ProviderInstanceId, options: { @@ -259,7 +259,7 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< configuration: AcpRegistryLiveConfiguration, ) => Option.Option; }, - ) => Effect.Effect; + ) => Effect.Effect>; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, @@ -410,9 +410,9 @@ const make = Effect.gen(function* () { const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = (instanceId) => - Ref.update(liveConfigurations, (state) => { + Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId); - if (current === undefined) return state; + if (current === undefined) return [0, state] as const; const nextCleared = Math.max(current.clearedThroughRevision, current.revision); if ( current.catalog === null && @@ -422,7 +422,7 @@ const make = Effect.gen(function* () { current.catalogReasoningSupersededSlugs.size === 0 && nextCleared === current.clearedThroughRevision ) { - return state; + return [nextCleared, state] as const; } const next = new Map(state); next.set(instanceId, { @@ -434,7 +434,7 @@ const make = Effect.gen(function* () { catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, clearedThroughRevision: nextCleared, }); - return next; + return [nextCleared, next] as const; }); const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = @@ -443,7 +443,7 @@ const make = Effect.gen(function* () { return yield* Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId) ?? EMPTY_STORED_LIVE_CONFIGURATION; if (current.catalogRevision !== options.catalogRevision) { - return [false, state] as const; + return [Option.none(), state] as const; } // Every revision through current.revision is either cleared or reconciled by retain. const nextCleared = Math.max(current.clearedThroughRevision, current.revision); @@ -656,7 +656,7 @@ const make = Effect.gen(function* () { ) && nextCleared === current.clearedThroughRevision ) { - return [true, state] as const; + return [Option.some(nextCleared), state] as const; } const next = new Map(state); next.set(instanceId, { @@ -668,7 +668,7 @@ const make = Effect.gen(function* () { catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, clearedThroughRevision: nextCleared, }); - return [true, next] as const; + return [Option.some(nextCleared), next] as const; }); }, ); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 1bed6199e76f5..dde40f171f51f 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3901,17 +3901,23 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); it.effect( - "clears accepted state on unauthenticated probes (even with concurrent options updates), invalidation, and provider disable", + "seeds reset revision on rebuild, accepts live catalogs while unauthenticated, and clears accepted state on sign-out, invalidation, and provider disable", () => Effect.gen(function* () { const probeEntered = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); const signOutRejected = yield* Deferred.make(); - const unauthLiveProcessed = yield* Deferred.make(); + let onNextLiveWatchUpdate: Deferred.Deferred | null = null; let gateNextResolve = false; let injectModeAfterInitialClear = true; let injectCatalogBeforeSignOutClear = false; - let trackUnauthLiveUpdate = false; + const awaitLiveWatchUpdate = (publish: Effect.Effect) => + Effect.gen(function* () { + const done = yield* Deferred.make(); + onNextLiveWatchUpdate = done; + yield* publish; + yield* Deferred.await(done); + }); // Pre-populate the shared coordinator before create() to simulate a rebuilt driver instance: // create() must seed liveSessionResetRevision from its clear so the first probe does not // treat the prior instance's cleared publications as an active superseded live session. @@ -3940,11 +3946,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { instanceId, (configuration, revision) => onUpdate(configuration, revision).pipe( - Effect.tap(() => - trackUnauthLiveUpdate - ? Deferred.succeed(unauthLiveProcessed, undefined).pipe(Effect.asVoid) - : Effect.void, - ), + Effect.tap(() => { + const pending = onNextLiveWatchUpdate; + if (pending === null) return Effect.void; + onNextLiveWatchUpdate = null; + return Deferred.succeed(pending, undefined).pipe(Effect.asVoid); + }), ), options, ), @@ -3966,10 +3973,14 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { return cleared; } const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); - // Publish an options-only update right after the clear returns (before the driver - // reads clearedThroughRevision) to verify supersession checks clearedThroughRevision - // rather than the post-clear live revision. - if (cleared && injectModeAfterInitialClear && options.retain !== undefined) { + // Publish an options-only update right after the clear returns to verify + // supersession uses the watermark returned by the clear rather than the post-clear + // live revision. + if ( + Option.isSome(cleared) && + injectModeAfterInitialClear && + options.retain !== undefined + ) { injectModeAfterInitialClear = false; yield* base.publishLiveConfiguration(instanceId, { models: [], @@ -4120,34 +4131,30 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(restored); - // Sign-out cleared liveSessionResetRevision, so a fresh options-only update on the - // re-authenticated probe is accepted rather than filtered against an empty probe schema. - const sawFreshAfterSignOut = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((m) => m.slug === "new-model") - ?.capabilities?.optionDescriptors?.some((d) => d.id === "fresh-after-signout") === - true, - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), + // Sign-out advanced liveSessionResetRevision to the cleared watermark, so a fresh + // options-only update on the re-authenticated probe is accepted rather than filtered + // against an empty probe schema. + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "fresh-after-signout", + label: "Fresh After Signout", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["fresh-after-signout"], + modelsFromModelSelect: false, + }), ); - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [], - currentModelId: "new-model", - configOptions: [ - { - id: "fresh-after-signout", - label: "Fresh After Signout", - type: "boolean", - currentValue: true, - }, - ], - modelOptionIds: ["fresh-after-signout"], - modelsFromModelSelect: false, - }); - expect(Option.isSome(yield* Fiber.join(sawFreshAfterSignOut))).toBe(true); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("fresh-after-signout"); const liveBeforeDisable = yield* instance.snapshot.streamChanges.pipe( Stream.filter( @@ -4196,34 +4203,30 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Fiber.join(restored2); - // disableProvider cleared liveSessionResetRevision, so a fresh options-only update on - // the new probe is accepted rather than filtered against the probe's empty option schema. - const sawFreshAfterDisable = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models - .find((m) => m.slug === "new-model") - ?.capabilities?.optionDescriptors?.some((d) => d.id === "fresh-after-disable") === - true, - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), + // disableProvider advanced liveSessionResetRevision to the cleared watermark, so a fresh + // options-only update on the new probe is accepted rather than filtered against the probe's + // empty option schema. + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "fresh-after-disable", + label: "Fresh After Disable", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["fresh-after-disable"], + modelsFromModelSelect: false, + }), ); - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [], - currentModelId: "new-model", - configOptions: [ - { - id: "fresh-after-disable", - label: "Fresh After Disable", - type: "boolean", - currentValue: true, - }, - ], - modelOptionIds: ["fresh-after-disable"], - modelsFromModelSelect: false, - }); - expect(Option.isSome(yield* Fiber.join(sawFreshAfterDisable))).toBe(true); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("fresh-after-disable"); yield* withBlockedForegroundStartup( Effect.gen(function* () { @@ -4524,7 +4527,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); // If a newer live catalog lands right before an unauthenticated probe clears - // coordinator state, clearLiveConfigurationIfRevision returns false and the stale + // coordinator state, clearLiveConfigurationIfRevision returns Option.none() and the stale // sign-out warning must be discarded rather than overwriting the new catalog. yield* writeModels({ fail: "Sign in required", code: -32000 }); injectCatalogBeforeSignOutClear = true; @@ -4553,48 +4556,42 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* instance.snapshot.refresh; const unauthSnap = Option.getOrThrow(yield* Fiber.join(signedOutForWatcher)); - trackUnauthLiveUpdate = true; - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [], - currentModelId: null, - configOptions: [ - { - id: "mode", - label: "Mode", - type: "select", - currentValue: "plan", - options: [{ id: "plan", label: "Plan" }], - }, - ], - modelOptionIds: [], - modelsFromModelSelect: false, - }); - yield* Deferred.await(unauthLiveProcessed); - trackUnauthLiveUpdate = false; + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [{ id: "plan", label: "Plan" }], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }), + ); expect((yield* instance.snapshot.getSnapshot).models).toEqual(unauthSnap.models); // A full live catalog arriving while unauthenticated must still apply and be saved to // acceptedCatalog so a subsequent readiness refresh without live coordinator state keeps it. - const sawUnauthCatalog = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.models.map((m) => m.slug).join() === "unauth-live-a,unauth-live-b", - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "unauth-live-a", name: "Unauth Live A", description: null }, + { id: "unauth-live-b", name: "Unauth Live B", description: null }, + ], + currentModelId: "unauth-live-a", + configOptions: [], + modelsFromModelSelect: true, + }), ); - yield* coordinator.publishLiveConfiguration(identity.instanceId, { - models: [ - { id: "unauth-live-a", name: "Unauth Live A", description: null }, - { id: "unauth-live-b", name: "Unauth Live B", description: null }, - ], - currentModelId: "unauth-live-a", - configOptions: [], - modelsFromModelSelect: true, - }); - expect( - Option.getOrThrow(yield* Fiber.join(sawUnauthCatalog)).models.map((m) => m.slug), - ).toEqual(["unauth-live-a", "unauth-live-b"]); + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "unauth-live-a", + "unauth-live-b", + ]); yield* coordinator.clearLiveConfiguration(identity.instanceId); yield* withBlockedForegroundStartup( Effect.gen(function* () { @@ -5555,7 +5552,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { clearLiveConfigurationIfRevision: (instanceId, options) => base.clearLiveConfigurationIfRevision(instanceId, options).pipe( Effect.tap((cleared) => - cleared && injectLiveCatalogAfterClear + Option.isSome(cleared) && injectLiveCatalogAfterClear ? Effect.sync(() => { injectLiveCatalogAfterClear = false; }).pipe( diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 4ec7b96fcbf82..4c0f02807d667 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1624,13 +1624,18 @@ export const AcpRegistryDriver: ProviderDriver runtimeCoordinator.value .clearAvailableCommands(instanceId) - .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))), + .pipe( + Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId)), + Effect.asVoid, + ), ); } const random = yield* SecureRandom.SecureRandom; @@ -1697,11 +1702,7 @@ export const AcpRegistryDriver: ProviderDriver(); + if (probeSupersedesLiveCatalog && Option.isNone(clearedThrough)) return; if (effectiveConfig.source === "local") { yield* Ref.set(reportedLocalVersion, provider.version); } @@ -2239,7 +2240,7 @@ export const AcpRegistryDriver: ProviderDriver (yield* Ref.get(liveSessionResetRevision)); + clearedThrough.value > (yield* Ref.get(liveSessionResetRevision)); yield* resetAppliedLiveRevisions; yield* Ref.set(acceptedCatalog, { models: resolved.models, @@ -2270,9 +2265,9 @@ export const AcpRegistryDriver: ProviderDriver - Math.max(prev, clearedThroughRevision), + Math.max(prev, clearedThrough.value), ); } const completedAt = yield* Clock.currentTimeMillis; @@ -2295,22 +2290,15 @@ export const AcpRegistryDriver: ProviderDriver + Ref.set(liveSessionResetRevision, clearedThrough), ), - ), - Effect.flatMap((clearedThrough) => - Ref.set(liveSessionResetRevision, clearedThrough), - ), - ) + ) ).pipe( Effect.andThen( options?.clearCommands === true From 87f75cd1aa9499caa31d8405d33a4146157409fa Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 20:20:25 +0000 Subject: [PATCH 27/35] fix(acp-registry): gate signed-out options replay and trace full clears --- .../AcpRegistryRuntimeCoordinator.test.ts | 10 ++- .../server/AcpRegistryRuntimeCoordinator.ts | 5 +- .../src/server/driver.test.ts | 86 ++++++++++++++++++- .../src/server/driver.ts | 46 +++++----- 4 files changed, 122 insertions(+), 25 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 663f617a685bf..a50389a486c1d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -1381,8 +1381,16 @@ describe("AcpRegistryRuntimeCoordinator", () => { // Case 6: Full clearLiveConfiguration and a fresh catalog publish both reset tracked // reasoningByModel and catalogReasoningSupersededSlugs, and clearLiveConfiguration returns - // the resulting cleared-through watermark. + // the advanced cleared-through watermark. + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-x", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); const beforeFullClear = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + expect(beforeFullClear.clearedThroughRevision).toBeLessThan(beforeFullClear.revision); expect(yield* coordinator.clearLiveConfiguration(instanceId)).toBe( beforeFullClear.revision, ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index f1440b0e4fe08..816a0929cfb44 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -409,8 +409,8 @@ const make = Effect.gen(function* () { ); const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = - (instanceId) => - Ref.modify(liveConfigurations, (state) => { + Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfiguration")(function* (instanceId) { + return yield* Ref.modify(liveConfigurations, (state) => { const current = state.get(instanceId); if (current === undefined) return [0, state] as const; const nextCleared = Math.max(current.clearedThroughRevision, current.revision); @@ -436,6 +436,7 @@ const make = Effect.gen(function* () { }); return [nextCleared, next] as const; }); + }); const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index dde40f171f51f..9e6d1b715d71a 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2717,8 +2717,15 @@ createInterface({ input: process.stdin }).on("line", (line) => { if (method === "initialize") { send({ id, - result: { protocolVersion: 1, agentCapabilities: { providers: {} }, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, + result: { + protocolVersion: 1, + agentCapabilities: { providers: {} }, + authMethods: [{ id: "agent-login", name: "Agent Login" }], + agentInfo: { name: "fake", version: "1.5.9" }, + }, }); + } else if (method === "authenticate") { + send({ id, result: {} }); } else if (method === "session/new") { const payload = JSON.parse(readFileSync(process.argv[2], "utf8")); if (!Array.isArray(payload) && typeof payload.provisional === "string") { @@ -4593,15 +4600,90 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "unauth-live-b", ]); yield* coordinator.clearLiveConfiguration(identity.instanceId); + // Signed-out readiness must keep the saved catalog without replaying options-only updates, + // and the watcher must keep ignoring options-only updates even after readiness resets auth + // status to "unknown". + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [ + { id: "plan", label: "Plan" }, + { id: "code", label: "Code" }, + ], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }), + ); yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.snapshot.refresh; - expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + const readinessWhileSignedOut = yield* instance.snapshot.getSnapshot; + expect(readinessWhileSignedOut.models.map((m) => m.slug)).toEqual([ "unauth-live-a", "unauth-live-b", ]); + expect( + readinessWhileSignedOut.models.flatMap( + (m) => m.capabilities?.optionDescriptors ?? [], + ), + ).toEqual([]); }), ); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "code", + options: [ + { id: "plan", label: "Plan" }, + { id: "code", label: "Code" }, + ], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models.flatMap( + (m) => m.capabilities?.optionDescriptors ?? [], + ), + ).toEqual([]); + + // Confirmed sign-in (auth.onChanged(true)) clears the signed-out restriction so readiness + // immediately replays pending options-only updates before enrichment finishes. + yield* writeModels(["new-model", "old-model"]); + const sawAuthenticatedReadiness = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.auth.status === "authenticated" && snapshot.nativeSessions === undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.auth!.start("owner", Effect.void, "agent-login"); + const authenticatedReadiness = Option.getOrThrow( + yield* Fiber.join(sawAuthenticatedReadiness), + ); + expect( + authenticatedReadiness.models + .find((m) => m.slug === "unauth-live-a") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, + ).toBe("code"); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 4c0f02807d667..281cff5ba7bc7 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1703,6 +1703,9 @@ export const AcpRegistryDriver: ProviderDriver 0; - if (accepted.probeOptions !== null && !hasNewCatalogStep) { - for (const entry of liveConfiguration.pendingOptions) { - if (entry.revision > appliedRev) { + if (!(yield* Ref.get(lastProbeUnauthenticated))) { + if (accepted.probeOptions !== null && !hasNewCatalogStep) { + for (const entry of liveConfiguration.pendingOptions) { + if (entry.revision > appliedRev) { + steps.push(entry); + } + } + const latestPending = liveConfiguration.pendingOptions.at(-1); + if (latestPending !== undefined && steps.at(-1) !== latestPending) { + steps.push(latestPending); + } + } else { + for (const entry of liveConfiguration.pendingOptions) { + if (entry.revision <= liveConfiguration.clearedThroughRevision) continue; + if (!hasNewCatalogStep && entry.revision <= appliedRev) continue; steps.push(entry); } } - const latestPending = liveConfiguration.pendingOptions.at(-1); - if (latestPending !== undefined && steps.at(-1) !== latestPending) { - steps.push(latestPending); - } - } else { - for (const entry of liveConfiguration.pendingOptions) { - if (entry.revision <= liveConfiguration.clearedThroughRevision) continue; - if (!hasNewCatalogStep && entry.revision <= appliedRev) continue; - steps.push(entry); - } } for (const step of steps) { withConfiguration = yield* applyLiveConfigurationStep( @@ -2229,6 +2234,7 @@ export const AcpRegistryDriver: ProviderDriver(); if (probeSupersedesLiveCatalog && Option.isNone(clearedThrough)) return; + yield* Ref.set(lastProbeUnauthenticated, false); if (effectiveConfig.source === "local") { yield* Ref.set(reportedLocalVersion, provider.version); } @@ -2265,11 +2271,6 @@ export const AcpRegistryDriver: ProviderDriver - Math.max(prev, clearedThrough.value), - ); - } const completedAt = yield* Clock.currentTimeMillis; yield* Ref.update(enrichmentCache, (latestCache) => ({ ...latestCache, @@ -2299,6 +2300,7 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 20:46:17 +0000 Subject: [PATCH 28/35] fix(acp-registry): mark signed out atomically on explicit logout and harden auth tests --- .../src/server/driver.test.ts | 238 +++++++++++++++++- .../src/server/driver.ts | 22 +- 2 files changed, 244 insertions(+), 16 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 9e6d1b715d71a..cf2fb92dc42b9 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2719,12 +2719,12 @@ createInterface({ input: process.stdin }).on("line", (line) => { id, result: { protocolVersion: 1, - agentCapabilities: { providers: {} }, + agentCapabilities: { providers: {}, auth: { logout: {} } }, authMethods: [{ id: "agent-login", name: "Agent Login" }], agentInfo: { name: "fake", version: "1.5.9" }, }, }); - } else if (method === "authenticate") { + } else if (method === "authenticate" || method === "logout" || method === "auth/logout") { send({ id, result: {} }); } else if (method === "session/new") { const payload = JSON.parse(readFileSync(process.argv[2], "utf8")); @@ -3914,17 +3914,58 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const probeEntered = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); const signOutRejected = yield* Deferred.make(); - let onNextLiveWatchUpdate: Deferred.Deferred | null = null; + const readyRaceRejected = yield* Deferred.make(); + let pendingLiveWatch: { + readonly minRevision: number; + readonly done: Deferred.Deferred; + } | null = null; let gateNextResolve = false; let injectModeAfterInitialClear = true; let injectCatalogBeforeSignOutClear = false; + let injectCatalogBeforeReadyClear = false; const awaitLiveWatchUpdate = (publish: Effect.Effect) => Effect.gen(function* () { + const beforeRevision = (yield* coordinator.getLiveConfigurationWithRevision( + identity.instanceId, + )).revision; const done = yield* Deferred.make(); - onNextLiveWatchUpdate = done; + pendingLiveWatch = { minRevision: beforeRevision + 1, done }; yield* publish; yield* Deferred.await(done); }); + // A brand-new driver starts with lastProbeUnauthenticated = false, so pre-probe readiness + // replays options-only updates published while foreground startup blocks the first probe. + yield* Effect.scoped( + Effect.gen(function* () { + const preProbe = yield* setupPeriodicDriver({ + prefix: "acp-driver-preprobe-", + initialModels: ["new-model", "old-model"], + }); + yield* preProbe.coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "pre-probe", + label: "Pre-probe", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* preProbe.withBlockedForegroundStartup( + Effect.gen(function* () { + yield* preProbe.instance.snapshot.refresh; + expect( + (yield* preProbe.instance.snapshot + .getSnapshot).models[0]?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("pre-probe"); + }), + ); + }), + ); // Pre-populate the shared coordinator before create() to simulate a rebuilt driver instance: // create() must seed liveSessionResetRevision from its clear so the first probe does not // treat the prior instance's cleared publications as an active superseded live session. @@ -3954,10 +3995,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { (configuration, revision) => onUpdate(configuration, revision).pipe( Effect.tap(() => { - const pending = onNextLiveWatchUpdate; - if (pending === null) return Effect.void; - onNextLiveWatchUpdate = null; - return Deferred.succeed(pending, undefined).pipe(Effect.asVoid); + const pending = pendingLiveWatch; + if (pending === null || revision < pending.minRevision) return Effect.void; + pendingLiveWatch = null; + return Deferred.succeed(pending.done, undefined).pipe(Effect.asVoid); }), ), options, @@ -3979,6 +4020,21 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.succeed(signOutRejected, undefined); return cleared; } + if (injectCatalogBeforeReadyClear && options.retain !== undefined) { + injectCatalogBeforeReadyClear = false; + yield* base.publishLiveConfiguration(instanceId, { + models: [ + { id: "raced-ready-a", name: "Raced Ready A", description: null }, + { id: "raced-ready-b", name: "Raced Ready B", description: null }, + ], + currentModelId: "raced-ready-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); + yield* Deferred.succeed(readyRaceRejected, undefined); + return cleared; + } const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); // Publish an options-only update right after the clear returns to verify // supersession uses the watermark returned by the clear rather than the post-clear @@ -4553,6 +4609,29 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( true, ); + // The discarded sign-out probe must leave lastProbeUnauthenticated false, so an + // options-only update on the raced catalog is still applied by the watcher. + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "raced-auth-b", + configOptions: [ + { + id: "after-raced-signout", + label: "After Raced Signout", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["after-raced-signout"], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "raced-auth-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("after-raced-signout"); // An options-only update arriving while unauthenticated must be ignored by the watcher. yield* TestClock.adjust("16 minutes"); @@ -4627,6 +4706,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { yield* instance.snapshot.refresh; const readinessWhileSignedOut = yield* instance.snapshot.getSnapshot; + expect(readinessWhileSignedOut.auth.status).toBe("unknown"); expect(readinessWhileSignedOut.models.map((m) => m.slug)).toEqual([ "unauth-live-a", "unauth-live-b", @@ -4675,6 +4755,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const postSignInEnriched = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); yield* instance.auth!.start("owner", Effect.void, "agent-login"); const authenticatedReadiness = Option.getOrThrow( yield* Fiber.join(sawAuthenticatedReadiness), @@ -4684,6 +4767,145 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "unauth-live-a") ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, ).toBe("code"); + yield* Fiber.join(postSignInEnriched); + + // Explicit sign-out (auth.logout -> onChanged(false)) atomically marks signed out without + // waiting for a failing probe, blocking options-only updates in both watcher and readiness. + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.auth!.logout!(Effect.void); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: null, + configOptions: [ + { + id: "mode", + label: "Mode", + type: "select", + currentValue: "plan", + options: [ + { id: "plan", label: "Plan" }, + { id: "code", label: "Code" }, + ], + }, + ], + modelOptionIds: [], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models.flatMap( + (m) => m.capabilities?.optionDescriptors ?? [], + ), + ).toEqual([]); + yield* instance.snapshot.refresh; + expect( + (yield* instance.snapshot.getSnapshot).models.flatMap( + (m) => m.capabilities?.optionDescriptors ?? [], + ), + ).toEqual([]); + }), + ); + + // A ready probe clears lastProbeUnauthenticated before withLiveRuntimeState so compatible + // options published while signed out are immediately replayed on the probe snapshot. + yield* writeModels({ + models: ["new-model", "old-model"], + configOptions: [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "new-model", + options: [ + { value: "new-model", name: "New Model" }, + { value: "old-model", name: "Old Model" }, + ], + }, + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "code", + options: [ + { value: "plan", name: "Plan" }, + { value: "code", name: "Code" }, + ], + }, + ], + }); + const readyReplayedSignedOutOption = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(readyReplayedSignedOutOption)) + .models.find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, + ).toBe("plan"); + + // Explicit management logout also marks signed out, and a ready probe that loses the + // catalog race still clears lastProbeUnauthenticated so follow-up options on the winning + // catalog are accepted. + yield* instance.acpSessionManagement!.logout(directory); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "new-model", + configOptions: [ + { + id: "blocked-after-mgmt-logout", + label: "Blocked After Mgmt Logout", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["blocked-after-mgmt-logout"], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "new-model") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).not.toContain("blocked-after-mgmt-logout"); + yield* TestClock.adjust("16 minutes"); + injectCatalogBeforeReadyClear = true; + const racedReadyApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.models.map((m) => m.slug).join() === "raced-ready-a,raced-ready-b", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(readyRaceRejected); + yield* Fiber.join(racedReadyApplied); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "raced-ready-b", + configOptions: [ + { + id: "after-raced-ready", + label: "After Raced Ready", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["after-raced-ready"], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "raced-ready-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("after-raced-ready"); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 281cff5ba7bc7..c0188c2ac429c 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1703,8 +1703,9 @@ export const AcpRegistryDriver: ProviderDriver 0); + current.installed && (replacesCatalog || acceptedBefore.models.length > 0); if (savedToAccepted) { yield* Ref.update(acceptedCatalog, (previous) => replacesCatalog @@ -2191,6 +2190,7 @@ export const AcpRegistryDriver: ProviderDriver entry.configuration), @@ -2234,7 +2234,6 @@ export const AcpRegistryDriver: ProviderDriver(); if (probeSupersedesLiveCatalog && Option.isNone(clearedThrough)) return; - yield* Ref.set(lastProbeUnauthenticated, false); if (effectiveConfig.source === "local") { yield* Ref.set(reportedLocalVersion, provider.version); } @@ -2451,12 +2450,18 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( Effect.uninterruptible( invalidateEnrichmentCache.pipe( Effect.andThen(clearLearnedModels), Effect.andThen(clearAcceptedCatalog), + Effect.andThen( + options?.markSignedOut === true + ? Ref.set(lastProbeUnauthenticated, true) + : Effect.void, + ), Effect.andThen(resetAppliedLiveRevisions), Effect.andThen( Option.isSome(runtimeCoordinator) @@ -2482,6 +2487,7 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), - Effect.tap(() => clearLiveState), + Effect.tap(() => clearSignedOutState), ); return Option.isSome(runtimeCoordinator) ? logout.pipe( From 94a65abbbfd586b74920b7ac33be2628763d9130 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 21:18:29 +0000 Subject: [PATCH 29/35] fix(acp-registry): decouple ready-probe auth reopening from live-catalog races --- .../src/server/driver.test.ts | 228 +++++++++++++++--- .../src/server/driver.ts | 97 +++++--- 2 files changed, 268 insertions(+), 57 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index cf2fb92dc42b9..954512e2c604b 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3911,15 +3911,17 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "seeds reset revision on rebuild, accepts live catalogs while unauthenticated, and clears accepted state on sign-out, invalidation, and provider disable", () => Effect.gen(function* () { - const probeEntered = yield* Deferred.make(); - const releaseProbe = yield* Deferred.make(); const signOutRejected = yield* Deferred.make(); const readyRaceRejected = yield* Deferred.make(); + let pendingResolveGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let pendingCommitEntered: Deferred.Deferred | null = null; let pendingLiveWatch: { readonly minRevision: number; readonly done: Deferred.Deferred; } | null = null; - let gateNextResolve = false; let injectModeAfterInitialClear = true; let injectCatalogBeforeSignOutClear = false; let injectCatalogBeforeReadyClear = false; @@ -3933,7 +3935,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* publish; yield* Deferred.await(done); }); - // A brand-new driver starts with lastProbeUnauthenticated = false, so pre-probe readiness + // A brand-new driver starts signed in (not signed out), so pre-probe readiness // replays options-only updates published while foreground startup blocks the first probe. yield* Effect.scoped( Effect.gen(function* () { @@ -3989,6 +3991,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { initialModels: ["new-model", "old-model", "other-model"], wrapCoordinator: (base) => ({ ...base, + getLiveConfigurationWithRevision: (instanceId) => + base.getLiveConfigurationWithRevision(instanceId).pipe( + Effect.tap(() => { + const done = pendingCommitEntered; + if (done === null) return Effect.void; + pendingCommitEntered = null; + return Deferred.succeed(done, undefined).pipe(Effect.asVoid); + }), + ), watchLiveConfiguration: (instanceId, onUpdate, options) => base.watchLiveConfiguration( instanceId, @@ -4069,13 +4080,27 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), onResolve: () => Effect.gen(function* () { - if (gateNextResolve) { - gateNextResolve = false; - yield* Deferred.succeed(probeEntered, undefined); - yield* Deferred.await(releaseProbe); + const gate = pendingResolveGate; + if (gate !== null) { + pendingResolveGate = null; + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); } }), }); + const runGatedProbe = (duringProbe: Effect.Effect) => + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + pendingResolveGate = { entered, release }; + yield* instance.snapshot.refresh; + yield* Deferred.await(entered); + yield* duringProbe; + const commitEntered = yield* Deferred.make(); + pendingCommitEntered = commitEntered; + yield* Deferred.succeed(release, undefined); + yield* Deferred.await(commitEntered); + }); // Neither the prior instance's cleared state nor an options-only publish arriving right // after the clear should mark the rebuilt driver's first probe as superseding a live session. @@ -4124,14 +4149,16 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { // status: warning, auth: unauthenticated, sign-in message, and models: ["default"]. yield* writeModels({ fail: "Sign in required", code: -32000 }); yield* TestClock.adjust("16 minutes"); - gateNextResolve = true; + const authProbeEntered = yield* Deferred.make(); + const releaseAuthProbe = yield* Deferred.make(); + pendingResolveGate = { entered: authProbeEntered, release: releaseAuthProbe }; const signedOutProbe = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - yield* Deferred.await(probeEntered); + yield* Deferred.await(authProbeEntered); const optionsDuringAuthProbe = yield* instance.snapshot.streamChanges.pipe( Stream.filter( @@ -4165,7 +4192,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }); yield* Fiber.join(optionsDuringAuthProbe); - yield* Deferred.succeed(releaseProbe, undefined); + yield* Deferred.succeed(releaseAuthProbe, undefined); const signedOut = Option.getOrThrow(yield* Fiber.join(signedOutProbe)); expect(signedOut.status).toBe("warning"); expect(signedOut.auth.status).toBe("unauthenticated"); @@ -4609,7 +4636,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.isSome(yield* coordinator.getLiveConfiguration(identity.instanceId))).toBe( true, ); - // The discarded sign-out probe must leave lastProbeUnauthenticated false, so an + // The discarded sign-out probe must not mark the driver signed out, so an // options-only update on the raced catalog is still applied by the watcher. yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { @@ -4662,7 +4689,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect((yield* instance.snapshot.getSnapshot).models).toEqual(unauthSnap.models); // A full live catalog arriving while unauthenticated must still apply and be saved to - // acceptedCatalog so a subsequent readiness refresh without live coordinator state keeps it. + // acceptedCatalog, and a follow-up non-replacing single-model update while auth status is + // still unauthenticated must also persist in acceptedCatalog across readiness refreshes. yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [ @@ -4678,10 +4706,33 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "unauth-live-a", "unauth-live-b", ]); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [{ id: "unauth-live-a", name: "Unauth Live A", description: null }], + currentModelId: "unauth-live-a", + configOptions: [ + { + id: "unauth-live-opt", + label: "Unauth Live Opt", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["unauth-live-opt"], + modelsFromModelSelect: false, + }), + ); + const snapAfterNonReplacingUnauth = yield* instance.snapshot.getSnapshot; + expect(snapAfterNonReplacingUnauth.auth.status).toBe("unauthenticated"); + expect( + snapAfterNonReplacingUnauth.models + .find((m) => m.slug === "unauth-live-a") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toEqual(["unauth-live-opt"]); yield* coordinator.clearLiveConfiguration(identity.instanceId); - // Signed-out readiness must keep the saved catalog without replaying options-only updates, - // and the watcher must keep ignoring options-only updates even after readiness resets auth - // status to "unknown". + // Signed-out readiness must keep the saved catalog and its saved non-replacing update + // without replaying options-only updates, and the watcher must keep ignoring options-only + // updates even after readiness resets auth status to "unknown". yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -4712,9 +4763,13 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "unauth-live-b", ]); expect( - readinessWhileSignedOut.models.flatMap( - (m) => m.capabilities?.optionDescriptors ?? [], - ), + readinessWhileSignedOut.models + .find((m) => m.slug === "unauth-live-a") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toEqual(["unauth-live-opt"]); + expect( + readinessWhileSignedOut.models.find((m) => m.slug === "unauth-live-b")?.capabilities + ?.optionDescriptors ?? [], ).toEqual([]); }), ); @@ -4738,10 +4793,15 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { modelsFromModelSelect: false, }), ); + const snapAfterBlockedWatcherOption = yield* instance.snapshot.getSnapshot; expect( - (yield* instance.snapshot.getSnapshot).models.flatMap( - (m) => m.capabilities?.optionDescriptors ?? [], - ), + snapAfterBlockedWatcherOption.models + .find((m) => m.slug === "unauth-live-a") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toEqual(["unauth-live-opt"]); + expect( + snapAfterBlockedWatcherOption.models.find((m) => m.slug === "unauth-live-b")?.capabilities + ?.optionDescriptors ?? [], ).toEqual([]); // Confirmed sign-in (auth.onChanged(true)) clears the signed-out restriction so readiness @@ -4808,7 +4868,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { }), ); - // A ready probe clears lastProbeUnauthenticated before withLiveRuntimeState so compatible + // A ready probe reopens options replay before building the snapshot so compatible // options published while signed out are immediately replayed on the probe snapshot. yield* writeModels({ models: ["new-model", "old-model"], @@ -4847,9 +4907,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, ).toBe("plan"); - // Explicit management logout also marks signed out, and a ready probe that loses the - // catalog race still clears lastProbeUnauthenticated so follow-up options on the winning - // catalog are accepted. + // Explicit management logout also marks signed out, and a ready probe that loses a + // live-catalog race (either during commit or before the first revision check) keeps the + // newer catalog while reopening options replay, unless a newer sign-out or reset superseded it. yield* instance.acpSessionManagement!.logout(directory); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { @@ -4872,7 +4932,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "new-model") ?.capabilities?.optionDescriptors?.map((d) => d.id), ).not.toContain("blocked-after-mgmt-logout"); - yield* TestClock.adjust("16 minutes"); injectCatalogBeforeReadyClear = true; const racedReadyApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter( @@ -4906,6 +4965,121 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "raced-ready-b") ?.capabilities?.optionDescriptors?.map((d) => d.id), ).toContain("after-raced-ready"); + + // Same ready-probe catalog race when the live catalog arrives mid-probe (before the + // commit's first revision check, advancing both cache generation and catalog revision). + yield* instance.acpSessionManagement!.logout(directory); + yield* runGatedProbe( + Effect.gen(function* () { + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "mid-raced-a", name: "Mid Raced A", description: null }, + { id: "mid-raced-b", name: "Mid Raced B", description: null }, + ], + currentModelId: "mid-raced-a", + configOptions: [], + modelsFromModelSelect: true, + }), + ); + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "mid-raced-a", + "mid-raced-b", + ]); + }), + ); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "mid-raced-b", + configOptions: [ + { + id: "after-mid-raced-ready", + label: "After Mid Raced Ready", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["after-mid-raced-ready"], + modelsFromModelSelect: false, + }), + ); + const snapAfterMidRace = yield* instance.snapshot.getSnapshot; + expect(snapAfterMidRace.models.map((m) => m.slug)).toEqual(["mid-raced-a", "mid-raced-b"]); + expect( + snapAfterMidRace.models + .find((m) => m.slug === "mid-raced-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("after-mid-raced-ready"); + + // An in-flight ready probe superseded by explicit sign-out must NOT reopen options replay. + yield* runGatedProbe( + Effect.gen(function* () { + yield* instance.acpSessionManagement!.logout(directory); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "post-logout-a", name: "Post Logout A", description: null }, + { id: "post-logout-b", name: "Post Logout B", description: null }, + ], + currentModelId: "post-logout-a", + configOptions: [], + modelsFromModelSelect: true, + }), + ); + }), + ); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "post-logout-b", + configOptions: [ + { + id: "blocked-after-raced-logout", + label: "Blocked After Raced Logout", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["blocked-after-raced-logout"], + modelsFromModelSelect: false, + }), + ); + const snapAfterRacedLogout = yield* instance.snapshot.getSnapshot; + expect(snapAfterRacedLogout.models.map((m) => m.slug)).toEqual([ + "post-logout-a", + "post-logout-b", + ]); + expect( + snapAfterRacedLogout.models + .find((m) => m.slug === "post-logout-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).not.toContain("blocked-after-raced-logout"); + + // An in-flight ready probe while signed out superseded by cache/auth reset must also + // keep options replay closed. + yield* runGatedProbe(instance.invalidateCaches!); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "post-logout-b", + configOptions: [ + { + id: "blocked-after-raced-invalidate", + label: "Blocked After Raced Invalidate", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["blocked-after-raced-invalidate"], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models + .find((m) => m.slug === "post-logout-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).not.toContain("blocked-after-raced-invalidate"); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index c0188c2ac429c..60fb228be5909 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1703,10 +1703,17 @@ export const AcpRegistryDriver: ProviderDriver ({ + signedOut: true, + epoch: state.epoch + 1, + })); + const clearSignedOut = Ref.update(signedOutState, (state) => + state.signedOut ? { ...state, signedOut: false } : state, + ); const lastObservedLiveRevision = yield* Ref.make(0); const lastAppliedLiveCatalogRevision = yield* Ref.make(0); const lastAppliedLiveRevision = yield* Ref.make(0); @@ -2003,7 +2010,7 @@ export const AcpRegistryDriver: ProviderDriver 0; - if (!(yield* Ref.get(lastProbeUnauthenticated))) { + if (!(yield* Ref.get(signedOutState)).signedOut) { if (accepted.probeOptions !== null && !hasNewCatalogStep) { for (const entry of liveConfiguration.pendingOptions) { if (entry.revision > appliedRev) { @@ -2085,22 +2092,44 @@ export const AcpRegistryDriver: ProviderDriver entry.configuration), @@ -2299,7 +2333,7 @@ export const AcpRegistryDriver: ProviderDriver ({ + ...state, + epoch: state.epoch + 1, + })), ), Effect.andThen(resetAppliedLiveRevisions), Effect.andThen( @@ -2500,8 +2537,8 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 21:52:38 +0000 Subject: [PATCH 30/35] fix(acp-registry): serialize auth confirmation and replay dropped options on reopen --- .../src/server/driver.test.ts | 65 +++++++++++++- .../src/server/driver.ts | 84 +++++++++++-------- 2 files changed, 111 insertions(+), 38 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 954512e2c604b..e7d0af98ed401 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -4096,6 +4096,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* instance.snapshot.refresh; yield* Deferred.await(entered); yield* duringProbe; + // Resolves on commitEnrichment's coordinator read while it holds liveSnapshotSemaphore, + // so the caller's follow-up awaitLiveWatchUpdate runs strictly after commit finishes. const commitEntered = yield* Deferred.make(); pendingCommitEntered = commitEntered; yield* Deferred.succeed(release, undefined); @@ -4960,14 +4962,18 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { modelsFromModelSelect: false, }), ); + const snapAfterRacedReady = yield* instance.snapshot.getSnapshot; + expect(snapAfterRacedReady.nativeSessions).toBeUndefined(); expect( - (yield* instance.snapshot.getSnapshot).models + snapAfterRacedReady.models .find((m) => m.slug === "raced-ready-b") ?.capabilities?.optionDescriptors?.map((d) => d.id), ).toContain("after-raced-ready"); // Same ready-probe catalog race when the live catalog arrives mid-probe (before the - // commit's first revision check, advancing both cache generation and catalog revision). + // commit's first revision check, advancing both cache generation and catalog revision): + // reopening must also replay options dropped while signed out before later updates advance + // the applied revision past them. yield* instance.acpSessionManagement!.logout(directory); yield* runGatedProbe( Effect.gen(function* () { @@ -4986,12 +4992,32 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "mid-raced-a", "mid-raced-b", ]); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "mid-raced-b", + configOptions: [ + { + id: "dropped-while-signed-out", + label: "Dropped While Signed Out", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["dropped-while-signed-out"], + modelsFromModelSelect: false, + }), + ); + expect( + (yield* instance.snapshot.getSnapshot).models.find((m) => m.slug === "mid-raced-b") + ?.capabilities?.optionDescriptors ?? [], + ).toEqual([]); }), ); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], - currentModelId: "mid-raced-b", + currentModelId: "mid-raced-a", configOptions: [ { id: "after-mid-raced-ready", @@ -5006,10 +5032,16 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); const snapAfterMidRace = yield* instance.snapshot.getSnapshot; expect(snapAfterMidRace.models.map((m) => m.slug)).toEqual(["mid-raced-a", "mid-raced-b"]); + expect(snapAfterMidRace.nativeSessions).toBeUndefined(); expect( snapAfterMidRace.models .find((m) => m.slug === "mid-raced-b") ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("dropped-while-signed-out"); + expect( + snapAfterMidRace.models + .find((m) => m.slug === "mid-raced-a") + ?.capabilities?.optionDescriptors?.map((d) => d.id), ).toContain("after-mid-raced-ready"); // An in-flight ready probe superseded by explicit sign-out must NOT reopen options replay. @@ -5080,6 +5112,33 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "post-logout-b") ?.capabilities?.optionDescriptors?.map((d) => d.id), ).not.toContain("blocked-after-raced-invalidate"); + + // A transient non-auth probe failure while signed out must NOT reopen options replay. + yield* writeModels({ fail: "Temporary discovery outage" }); + yield* runGatedProbe(Effect.void); + yield* awaitLiveWatchUpdate( + coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "post-logout-b", + configOptions: [ + { + id: "blocked-after-transient-warning", + label: "Blocked After Transient Warning", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["blocked-after-transient-warning"], + modelsFromModelSelect: false, + }), + ); + const snapAfterTransientWarning = yield* instance.snapshot.getSnapshot; + expect(snapAfterTransientWarning.status).toBe("warning"); + expect( + snapAfterTransientWarning.models + .find((m) => m.slug === "post-logout-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).not.toContain("blocked-after-transient-warning"); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 60fb228be5909..2d618a1d7ae43 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1711,6 +1711,10 @@ export const AcpRegistryDriver: ProviderDriver ({ + ...state, + epoch: state.epoch + 1, + })); const clearSignedOut = Ref.update(signedOutState, (state) => state.signedOut ? { ...state, signedOut: false } : state, ); @@ -2091,7 +2095,6 @@ export const AcpRegistryDriver: ProviderDriver + state.signedOut && state.epoch === probeStartSignedOutEpoch + ? ([true, { ...state, signedOut: false }] as const) + : ([false, state] as const), + )); if ( current.generation !== generation || (fresh && liveSnapshot.catalogRevision !== probeStartCatalogRevision) ) { + if (reopenedSignedOut) { + const rawCurrent = yield* getSnapshot; + if (rawCurrent.installed) { + const replayed = yield* withLiveRuntimeState(rawCurrent, { + fallbackToAcceptedModels: true, + preserveStatus: rawCurrent.status !== "ready", + }); + if (!Equal.equals(replayed, rawCurrent)) { + yield* publishSnapshot(replayed); + } + } + } return; } let resolved = provider; @@ -2484,21 +2500,19 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( Effect.uninterruptible( - invalidateEnrichmentCache.pipe( + (options?.clearConfirmedAuthentication === true + ? confirmedAuthentication.set(false) + : Effect.void + ).pipe( + Effect.andThen(invalidateEnrichmentCache), Effect.andThen(clearLearnedModels), Effect.andThen(clearAcceptedCatalog), - Effect.andThen( - options?.markSignedOut === true - ? markSignedOut - : Ref.update(signedOutState, (state) => ({ - ...state, - epoch: state.epoch + 1, - })), - ), + Effect.andThen(options?.markSignedOut === true ? markSignedOut : advanceSignedOutEpoch), Effect.andThen(resetAppliedLiveRevisions), Effect.andThen( Option.isSome(runtimeCoordinator) @@ -2523,29 +2537,31 @@ export const AcpRegistryDriver: ProviderDriver - confirmedAuthentication - .set(authenticated) - .pipe( - Effect.andThen( - authenticated - ? liveSnapshotSemaphore.withPermit( - Effect.uninterruptible( - invalidateEnrichmentCache.pipe(Effect.andThen(clearSignedOut)), - ), - ) - : clearSignedOutState, - ), - Effect.andThen(snapshot.refresh), - Effect.asVoid, - ), + (authenticated + ? liveSnapshotSemaphore.withPermit( + Effect.uninterruptible( + confirmedAuthentication + .set(true) + .pipe(Effect.andThen(invalidateEnrichmentCache), Effect.andThen(clearSignedOut)), + ), + ) + : clearSignedOutState + ).pipe(Effect.andThen(snapshot.refresh), Effect.asVoid), }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -2554,7 +2570,6 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), Effect.tap(() => clearSignedOutState), ); return Option.isSome(runtimeCoordinator) From 1dbbb99191f4ae36f0ca73797e38dcf7ab37f867 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 22:24:49 +0000 Subject: [PATCH 31/35] fix(acp-registry): simplify reopened live replay and pin auth/race invariants --- .../src/server/driver.test.ts | 169 +++++++++++++++++- .../src/server/driver.ts | 16 +- 2 files changed, 167 insertions(+), 18 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index e7d0af98ed401..37cfd99309f14 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3277,6 +3277,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { readonly wrapCoordinator?: ( coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"], ) => AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"]; + readonly wrapFileSystem?: (fs: FileSystem.FileSystem) => FileSystem.FileSystem; readonly inspect?: () => AcpRegistrySupport.AcpRegistryInspection; readonly onResolve?: () => Effect.Effect; }) => @@ -3291,6 +3292,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const effectiveCoordinator = options.wrapCoordinator === undefined ? coordinator : options.wrapCoordinator(coordinator); + const effectiveFileSystem = + options.wrapFileSystem === undefined ? fileSystem : options.wrapFileSystem(fileSystem); const instance = yield* AcpRegistryDriver.create({ instanceId: identity.instanceId, displayName: identity.displayName, @@ -3298,6 +3301,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { environment: [], config: decodeSettings({ agentId: "test-agent" }), }).pipe( + Effect.provideService(FileSystem.FileSystem, effectiveFileSystem), Effect.provideService( AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, effectiveCoordinator, @@ -3917,6 +3921,11 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; } | null = null; + let pendingAuthPersistGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let blockLiveWatch: Deferred.Deferred | null = null; let pendingCommitEntered: Deferred.Deferred | null = null; let pendingLiveWatch: { readonly minRevision: number; @@ -3989,6 +3998,22 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { } = yield* setupPeriodicDriver({ prefix: "acp-driver-clear-", initialModels: ["new-model", "old-model", "other-model"], + wrapFileSystem: (base) => ({ + ...base, + rename: (oldPath, newPath) => + Effect.gen(function* () { + const gate = pendingAuthPersistGate; + if (gate !== null && newPath.includes("acp-auth-")) { + const contents = yield* base.readFileString(oldPath); + if (contents.includes('"authenticated":true')) { + pendingAuthPersistGate = null; + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + } + return yield* base.rename(oldPath, newPath); + }), + }), wrapCoordinator: (base) => ({ ...base, getLiveConfigurationWithRevision: (instanceId) => @@ -4004,7 +4029,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { base.watchLiveConfiguration( instanceId, (configuration, revision) => - onUpdate(configuration, revision).pipe( + (blockLiveWatch !== null ? Deferred.await(blockLiveWatch) : Effect.void).pipe( + Effect.andThen(onUpdate(configuration, revision)), Effect.tap(() => { const pending = pendingLiveWatch; if (pending === null || revision < pending.minRevision) return Effect.void; @@ -4097,7 +4123,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.await(entered); yield* duringProbe; // Resolves on commitEnrichment's coordinator read while it holds liveSnapshotSemaphore, - // so the caller's follow-up awaitLiveWatchUpdate runs strictly after commit finishes. + // so the watcher handles the caller's follow-up publish only after commit finishes. const commitEntered = yield* Deferred.make(); pendingCommitEntered = commitEntered; yield* Deferred.succeed(release, undefined); @@ -4831,11 +4857,65 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ).toBe("code"); yield* Fiber.join(postSignInEnriched); - // Explicit sign-out (auth.logout -> onChanged(false)) atomically marks signed out without - // waiting for a failing probe, blocking options-only updates in both watcher and readiness. + // Confirmed sign-in invalidates a still-valid enrichment cache so the post-sign-in refresh + // probes newly available models instead of serving stale cached entries. + yield* writeModels(["post-signin-a", "post-signin-b"]); + const postCacheInvalidatingSignIn = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.auth!.start("owner", Effect.void, "agent-login"); + expect( + Option.getOrThrow(yield* Fiber.join(postCacheInvalidatingSignIn)).models.map( + (m) => m.slug, + ), + ).toEqual(["post-signin-a", "post-signin-b"]); + + // auth.invalidate clears persisted sign-in confirmation so readiness falls back to unknown. + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.auth!.invalidate!; + expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); + }), + ); + + // onChanged(true) holds liveSnapshotSemaphore while persisting sign-in confirmation so + // concurrent snapshot mutations (like an older unauthenticated commit or cache reset) + // cannot interleave and clobber confirmed auth. + const authPersistEntered = yield* Deferred.make(); + const releaseAuthPersist = yield* Deferred.make(); + pendingAuthPersistGate = { entered: authPersistEntered, release: releaseAuthPersist }; + const sawSerializedSignIn = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.auth.status === "authenticated"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.auth!.start("owner", Effect.void, "agent-login"); + yield* Deferred.await(authPersistEntered); + let invalidateCompletedWhilePersistingAuth = false; + const concurrentInvalidateFiber = yield* instance.invalidateCaches!.pipe( + Effect.tap(() => + Effect.sync(() => { + invalidateCompletedWhilePersistingAuth = true; + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Effect.sync(() => { + expect(invalidateCompletedWhilePersistingAuth).toBe(false); + }).pipe(Effect.ensuring(Deferred.succeed(releaseAuthPersist, undefined))); + yield* Fiber.join(concurrentInvalidateFiber); + expect(invalidateCompletedWhilePersistingAuth).toBe(true); + expect(Option.getOrThrow(yield* Fiber.join(sawSerializedSignIn)).auth.status).toBe( + "authenticated", + ); + + // Explicit sign-out (auth.logout -> onChanged(false)) atomically clears sign-in + // confirmation and marks signed out without waiting for a failing probe, blocking + // options-only updates in both watcher and readiness. yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.auth!.logout!(Effect.void); + expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -4862,8 +4942,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ), ).toEqual([]); yield* instance.snapshot.refresh; + const snapAfterAuthLogoutRefresh = yield* instance.snapshot.getSnapshot; + expect(snapAfterAuthLogoutRefresh.auth.status).toBe("unknown"); expect( - (yield* instance.snapshot.getSnapshot).models.flatMap( + snapAfterAuthLogoutRefresh.models.flatMap( (m) => m.capabilities?.optionDescriptors ?? [], ), ).toEqual([]); @@ -4972,8 +5054,8 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { // Same ready-probe catalog race when the live catalog arrives mid-probe (before the // commit's first revision check, advancing both cache generation and catalog revision): - // reopening must also replay options dropped while signed out before later updates advance - // the applied revision past them. + // reopening must also replay pending options still held by the coordinator before later + // updates advance the applied revision past them. yield* instance.acpSessionManagement!.logout(directory); yield* runGatedProbe( Effect.gen(function* () { @@ -5044,6 +5126,79 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.map((d) => d.id), ).toContain("after-mid-raced-ready"); + // Same ready-probe catalog race when only coordinator catalogRevision advanced (the live + // watcher has not processed the catalog yet, so cache generation is unchanged): the commit + // must still take the early return and replay the new catalog + pending options immediately. + yield* instance.acpSessionManagement!.logout(directory); + const releaseBlockedWatch = yield* Deferred.make(); + const blockedWatchDrained = yield* Deferred.make(); + yield* Effect.gen(function* () { + let unwatchedOptRevision = 0; + yield* runGatedProbe( + Effect.gen(function* () { + blockLiveWatch = releaseBlockedWatch; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [ + { id: "unwatched-a", name: "Unwatched A", description: null }, + { id: "unwatched-b", name: "Unwatched B", description: null }, + ], + currentModelId: "unwatched-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "unwatched-b", + configOptions: [ + { + id: "unwatched-opt", + label: "Unwatched Opt", + type: "boolean", + currentValue: true, + }, + ], + modelOptionIds: ["unwatched-opt"], + modelsFromModelSelect: false, + }); + unwatchedOptRevision = (yield* coordinator.getLiveConfigurationWithRevision( + identity.instanceId, + )).revision; + }), + ); + // publishAvailableCommands acquires liveSnapshotSemaphore, proving commitEnrichment + // has finished while the live-configuration watcher is still blocked. + const sawCommitFinished = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + (snapshot.slashCommands ?? []).some((command) => command.name === "sync-commit"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "sync-commit", description: "Sync commit" }], + skills: [], + }); + const snapBeforeWatchDrains = Option.getOrThrow(yield* Fiber.join(sawCommitFinished)); + expect(snapBeforeWatchDrains.models.map((m) => m.slug)).toEqual([ + "unwatched-a", + "unwatched-b", + ]); + expect(snapBeforeWatchDrains.nativeSessions).toBeUndefined(); + expect( + snapBeforeWatchDrains.models + .find((m) => m.slug === "unwatched-b") + ?.capabilities?.optionDescriptors?.map((d) => d.id), + ).toContain("unwatched-opt"); + pendingLiveWatch = { minRevision: unwatchedOptRevision, done: blockedWatchDrained }; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + blockLiveWatch = null; + }).pipe(Effect.andThen(Deferred.succeed(releaseBlockedWatch, undefined))), + ), + ); + yield* Deferred.await(blockedWatchDrained); + // An in-flight ready probe superseded by explicit sign-out must NOT reopen options replay. yield* runGatedProbe( Effect.gen(function* () { diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 2d618a1d7ae43..f550513d1d0c6 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1705,7 +1705,7 @@ export const AcpRegistryDriver: ProviderDriver ({ signedOut: true, @@ -2212,16 +2212,10 @@ export const AcpRegistryDriver: ProviderDriver withLiveRuntimeState(currentSnapshot)), + Effect.flatMap(publishSnapshot), + ); } return; } From 2e3e302827bce5c115f56f12f77967e246334ab8 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 22:56:49 +0000 Subject: [PATCH 32/35] test(acp-registry): split auth/reopen suite and assert persisted sign-in state --- .../src/server/driver.test.ts | 256 ++++++++++++------ 1 file changed, 177 insertions(+), 79 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 37cfd99309f14..851fd6db6129a 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3916,24 +3916,16 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { () => Effect.gen(function* () { const signOutRejected = yield* Deferred.make(); - const readyRaceRejected = yield* Deferred.make(); let pendingResolveGate: { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; } | null = null; - let pendingAuthPersistGate: { - readonly entered: Deferred.Deferred; - readonly release: Deferred.Deferred; - } | null = null; - let blockLiveWatch: Deferred.Deferred | null = null; - let pendingCommitEntered: Deferred.Deferred | null = null; let pendingLiveWatch: { readonly minRevision: number; readonly done: Deferred.Deferred; } | null = null; let injectModeAfterInitialClear = true; let injectCatalogBeforeSignOutClear = false; - let injectCatalogBeforeReadyClear = false; const awaitLiveWatchUpdate = (publish: Effect.Effect) => Effect.gen(function* () { const beforeRevision = (yield* coordinator.getLiveConfigurationWithRevision( @@ -3998,39 +3990,13 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { } = yield* setupPeriodicDriver({ prefix: "acp-driver-clear-", initialModels: ["new-model", "old-model", "other-model"], - wrapFileSystem: (base) => ({ - ...base, - rename: (oldPath, newPath) => - Effect.gen(function* () { - const gate = pendingAuthPersistGate; - if (gate !== null && newPath.includes("acp-auth-")) { - const contents = yield* base.readFileString(oldPath); - if (contents.includes('"authenticated":true')) { - pendingAuthPersistGate = null; - yield* Deferred.succeed(gate.entered, undefined); - yield* Deferred.await(gate.release); - } - } - return yield* base.rename(oldPath, newPath); - }), - }), wrapCoordinator: (base) => ({ ...base, - getLiveConfigurationWithRevision: (instanceId) => - base.getLiveConfigurationWithRevision(instanceId).pipe( - Effect.tap(() => { - const done = pendingCommitEntered; - if (done === null) return Effect.void; - pendingCommitEntered = null; - return Deferred.succeed(done, undefined).pipe(Effect.asVoid); - }), - ), watchLiveConfiguration: (instanceId, onUpdate, options) => base.watchLiveConfiguration( instanceId, (configuration, revision) => - (blockLiveWatch !== null ? Deferred.await(blockLiveWatch) : Effect.void).pipe( - Effect.andThen(onUpdate(configuration, revision)), + onUpdate(configuration, revision).pipe( Effect.tap(() => { const pending = pendingLiveWatch; if (pending === null || revision < pending.minRevision) return Effect.void; @@ -4057,21 +4023,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { yield* Deferred.succeed(signOutRejected, undefined); return cleared; } - if (injectCatalogBeforeReadyClear && options.retain !== undefined) { - injectCatalogBeforeReadyClear = false; - yield* base.publishLiveConfiguration(instanceId, { - models: [ - { id: "raced-ready-a", name: "Raced Ready A", description: null }, - { id: "raced-ready-b", name: "Raced Ready B", description: null }, - ], - currentModelId: "raced-ready-a", - configOptions: [], - modelsFromModelSelect: true, - }); - const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); - yield* Deferred.succeed(readyRaceRejected, undefined); - return cleared; - } const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); // Publish an options-only update right after the clear returns to verify // supersession uses the watermark returned by the clear rather than the post-clear @@ -4114,21 +4065,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { } }), }); - const runGatedProbe = (duringProbe: Effect.Effect) => - Effect.gen(function* () { - const entered = yield* Deferred.make(); - const release = yield* Deferred.make(); - pendingResolveGate = { entered, release }; - yield* instance.snapshot.refresh; - yield* Deferred.await(entered); - yield* duringProbe; - // Resolves on commitEnrichment's coordinator read while it holds liveSnapshotSemaphore, - // so the watcher handles the caller's follow-up publish only after commit finishes. - const commitEntered = yield* Deferred.make(); - pendingCommitEntered = commitEntered; - yield* Deferred.succeed(release, undefined); - yield* Deferred.await(commitEntered); - }); // Neither the prior instance's cleared state nor an options-only publish arriving right // after the clear should mark the rebuilt driver's first probe as superseding a live session. @@ -4836,10 +4772,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { // immediately replays pending options-only updates before enrichment finishes. yield* writeModels(["new-model", "old-model"]); const sawAuthenticatedReadiness = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.auth.status === "authenticated" && snapshot.nativeSessions === undefined, - ), + Stream.filter((snapshot) => snapshot.nativeSessions === undefined), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); @@ -4850,31 +4783,179 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const authenticatedReadiness = Option.getOrThrow( yield* Fiber.join(sawAuthenticatedReadiness), ); + expect(authenticatedReadiness.auth.status).toBe("authenticated"); expect( authenticatedReadiness.models .find((m) => m.slug === "unauth-live-a") ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, ).toBe("code"); yield* Fiber.join(postSignInEnriched); + }), + ); + + it.effect( + "serializes sign-in confirmation and reopens pending options on ready-probe races without reopening on resets or transient failures", + () => + Effect.gen(function* () { + const readyRaceRejected = yield* Deferred.make(); + let lastPersistedAuthConfirmed: boolean | null = null; + let pendingResolveGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let pendingAuthPersistGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let blockLiveWatch: Deferred.Deferred | null = null; + let pendingCommitEntered: Deferred.Deferred | null = null; + let pendingLiveWatch: { + readonly minRevision: number; + readonly done: Deferred.Deferred; + } | null = null; + let injectCatalogBeforeReadyClear = false; + const { + directory, + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-auth-reopen-", + initialModels: ["new-model", "old-model"], + wrapFileSystem: (base) => ({ + ...base, + rename: (oldPath, newPath) => + Effect.gen(function* () { + if (newPath.includes("acp-auth-")) { + const contents = yield* base.readFileString(oldPath); + const parsed = JSON.parse(contents) as { readonly authenticated?: boolean }; + if (typeof parsed.authenticated === "boolean") { + lastPersistedAuthConfirmed = parsed.authenticated; + } + const gate = pendingAuthPersistGate; + if (gate !== null && parsed.authenticated === true) { + pendingAuthPersistGate = null; + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + } + return yield* base.rename(oldPath, newPath); + }), + }), + wrapCoordinator: (base) => ({ + ...base, + getLiveConfigurationWithRevision: (instanceId) => + base.getLiveConfigurationWithRevision(instanceId).pipe( + Effect.tap(() => { + const done = pendingCommitEntered; + if (done === null) return Effect.void; + pendingCommitEntered = null; + return Deferred.succeed(done, undefined).pipe(Effect.asVoid); + }), + ), + watchLiveConfiguration: (instanceId, onUpdate, options) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => + (blockLiveWatch !== null ? Deferred.await(blockLiveWatch) : Effect.void).pipe( + Effect.andThen(onUpdate(configuration, revision)), + Effect.tap(() => { + const pending = pendingLiveWatch; + if (pending === null || revision < pending.minRevision) return Effect.void; + pendingLiveWatch = null; + return Deferred.succeed(pending.done, undefined).pipe(Effect.asVoid); + }), + ), + options, + ), + clearLiveConfigurationIfRevision: (instanceId, options) => + Effect.gen(function* () { + if (injectCatalogBeforeReadyClear && options.retain !== undefined) { + injectCatalogBeforeReadyClear = false; + yield* base.publishLiveConfiguration(instanceId, { + models: [ + { id: "raced-ready-a", name: "Raced Ready A", description: null }, + { id: "raced-ready-b", name: "Raced Ready B", description: null }, + ], + currentModelId: "raced-ready-a", + configOptions: [], + modelsFromModelSelect: true, + }); + const cleared = yield* base.clearLiveConfigurationIfRevision(instanceId, options); + yield* Deferred.succeed(readyRaceRejected, undefined); + return cleared; + } + return yield* base.clearLiveConfigurationIfRevision(instanceId, options); + }), + }), + onResolve: () => + Effect.gen(function* () { + const gate = pendingResolveGate; + if (gate !== null) { + pendingResolveGate = null; + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + }), + }); + const awaitLiveWatchUpdate = (publish: Effect.Effect) => + Effect.gen(function* () { + const beforeRevision = (yield* coordinator.getLiveConfigurationWithRevision( + identity.instanceId, + )).revision; + const done = yield* Deferred.make(); + pendingLiveWatch = { minRevision: beforeRevision + 1, done }; + yield* publish; + yield* Deferred.await(done); + }); + const runGatedProbe = (duringProbe: Effect.Effect) => + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + pendingResolveGate = { entered, release }; + yield* instance.snapshot.refresh; + yield* Deferred.await(entered); + yield* duringProbe; + // Resolves on commitEnrichment's coordinator read while it holds liveSnapshotSemaphore, + // so the watcher handles the caller's follow-up publish only after commit finishes. + const commitEntered = yield* Deferred.make(); + pendingCommitEntered = commitEntered; + yield* Deferred.succeed(release, undefined); + yield* Deferred.await(commitEntered); + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); // Confirmed sign-in invalidates a still-valid enrichment cache so the post-sign-in refresh - // probes newly available models instead of serving stale cached entries. + // probes newly available models instead of serving stale cached entries, and persists + // sign-in confirmation. yield* writeModels(["post-signin-a", "post-signin-b"]); const postCacheInvalidatingSignIn = yield* waitForEnriched().pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.auth!.start("owner", Effect.void, "agent-login"); - expect( - Option.getOrThrow(yield* Fiber.join(postCacheInvalidatingSignIn)).models.map( - (m) => m.slug, - ), - ).toEqual(["post-signin-a", "post-signin-b"]); + const postCacheInvalidatingSnap = Option.getOrThrow( + yield* Fiber.join(postCacheInvalidatingSignIn), + ); + expect(postCacheInvalidatingSnap.models.map((m) => m.slug)).toEqual([ + "post-signin-a", + "post-signin-b", + ]); + expect(postCacheInvalidatingSnap.auth.status).toBe("authenticated"); + expect(lastPersistedAuthConfirmed).toBe(true); // auth.invalidate clears persisted sign-in confirmation so readiness falls back to unknown. yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.auth!.invalidate!; expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); + expect(lastPersistedAuthConfirmed).toBe(false); }), ); @@ -4885,7 +4966,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const releaseAuthPersist = yield* Deferred.make(); pendingAuthPersistGate = { entered: authPersistEntered, release: releaseAuthPersist }; const sawSerializedSignIn = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.auth.status === "authenticated"), + Stream.filter((snapshot) => snapshot.nativeSessions === undefined), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); @@ -4908,6 +4989,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.getOrThrow(yield* Fiber.join(sawSerializedSignIn)).auth.status).toBe( "authenticated", ); + expect(lastPersistedAuthConfirmed).toBe(true); // Explicit sign-out (auth.logout -> onChanged(false)) atomically clears sign-in // confirmation and marks signed out without waiting for a failing probe, blocking @@ -4916,6 +4998,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { yield* instance.auth!.logout!(Effect.void); expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); + expect(lastPersistedAuthConfirmed).toBe(false); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -4991,10 +5074,19 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ?.capabilities?.optionDescriptors?.find((d) => d.id === "mode")?.currentValue, ).toBe("plan"); - // Explicit management logout also marks signed out, and a ready probe that loses a - // live-catalog race (either during commit or before the first revision check) keeps the - // newer catalog while reopening options replay, unless a newer sign-out or reset superseded it. + // Explicit management logout clears persisted sign-in confirmation and marks signed out; + // a ready probe that loses a live-catalog race (during commit or before the first revision + // check) keeps the newer catalog while reopening options replay, unless superseded. + const postReconfirmEnriched = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.auth!.start("owner", Effect.void, "agent-login"); + expect(Option.getOrThrow(yield* Fiber.join(postReconfirmEnriched)).auth.status).toBe( + "authenticated", + ); + expect(lastPersistedAuthConfirmed).toBe(true); yield* instance.acpSessionManagement!.logout(directory); + expect(lastPersistedAuthConfirmed).toBe(false); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -5016,6 +5108,12 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { .find((m) => m.slug === "new-model") ?.capabilities?.optionDescriptors?.map((d) => d.id), ).not.toContain("blocked-after-mgmt-logout"); + yield* withBlockedForegroundStartup( + Effect.gen(function* () { + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); + }), + ); injectCatalogBeforeReadyClear = true; const racedReadyApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter( From 3ac826373efc03a019811e1804e42c318a1c658c Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:17:03 +0000 Subject: [PATCH 33/35] test(acp-registry): isolate per-test auth cache dir and read persisted file on disk --- .../src/server/driver.test.ts | 49 +++++++++++++------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 851fd6db6129a..0b8737fe5bb35 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -8,6 +8,7 @@ import { import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; @@ -3284,7 +3285,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const host = yield* ProviderHost.ProviderHost; const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: options.prefix }); + const statusCacheDir = path.join(directory, "status-cache"); const agentPath = path.join(directory, "agent.mjs"); const modelsPath = path.join(directory, "models.json"); yield* fileSystem.writeFileString(agentPath, fakeAgentSource); @@ -3301,6 +3304,13 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { environment: [], config: decodeSettings({ agentId: "test-agent" }), }).pipe( + Effect.provideService(ProviderHost.ProviderHost, { + ...host, + paths: { + ...host.paths, + providerStatusCacheDir: statusCacheDir, + }, + }), Effect.provideService(FileSystem.FileSystem, effectiveFileSystem), Effect.provideService( AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, @@ -3343,6 +3353,18 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); return result; }); + const readPersistedAuthConfirmed = () => + Effect.gen(function* () { + const entries = yield* fileSystem.readDirectory(statusCacheDir); + const authFile = entries.find( + (entry) => entry.startsWith("acp-auth-") && entry.endsWith(".json"), + ); + if (authFile === undefined) return null; + const contents = yield* fileSystem.readFileString(path.join(statusCacheDir, authFile)); + return ( + (JSON.parse(contents) as { readonly authenticated?: boolean }).authenticated ?? null + ); + }); return { directory, coordinator, @@ -3350,6 +3372,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { waitForEnriched, writeModels, withBlockedForegroundStartup, + readPersistedAuthConfirmed, }; }); @@ -4798,7 +4821,6 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { () => Effect.gen(function* () { const readyRaceRejected = yield* Deferred.make(); - let lastPersistedAuthConfirmed: boolean | null = null; let pendingResolveGate: { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; @@ -4821,6 +4843,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { waitForEnriched, writeModels, withBlockedForegroundStartup, + readPersistedAuthConfirmed, } = yield* setupPeriodicDriver({ prefix: "acp-driver-auth-reopen-", initialModels: ["new-model", "old-model"], @@ -4828,14 +4851,10 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ...base, rename: (oldPath, newPath) => Effect.gen(function* () { - if (newPath.includes("acp-auth-")) { + const gate = pendingAuthPersistGate; + if (gate !== null && newPath.includes("acp-auth-")) { const contents = yield* base.readFileString(oldPath); - const parsed = JSON.parse(contents) as { readonly authenticated?: boolean }; - if (typeof parsed.authenticated === "boolean") { - lastPersistedAuthConfirmed = parsed.authenticated; - } - const gate = pendingAuthPersistGate; - if (gate !== null && parsed.authenticated === true) { + if (contents.includes('"authenticated":true')) { pendingAuthPersistGate = null; yield* Deferred.succeed(gate.entered, undefined); yield* Deferred.await(gate.release); @@ -4930,7 +4949,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - yield* Fiber.join(initial); + expect(Option.getOrThrow(yield* Fiber.join(initial)).auth.status).toBe("unknown"); // Confirmed sign-in invalidates a still-valid enrichment cache so the post-sign-in refresh // probes newly available models instead of serving stale cached entries, and persists @@ -4948,14 +4967,14 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { "post-signin-b", ]); expect(postCacheInvalidatingSnap.auth.status).toBe("authenticated"); - expect(lastPersistedAuthConfirmed).toBe(true); + expect(yield* readPersistedAuthConfirmed()).toBe(true); // auth.invalidate clears persisted sign-in confirmation so readiness falls back to unknown. yield* withBlockedForegroundStartup( Effect.gen(function* () { yield* instance.auth!.invalidate!; expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); - expect(lastPersistedAuthConfirmed).toBe(false); + expect(yield* readPersistedAuthConfirmed()).toBe(false); }), ); @@ -4989,7 +5008,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.getOrThrow(yield* Fiber.join(sawSerializedSignIn)).auth.status).toBe( "authenticated", ); - expect(lastPersistedAuthConfirmed).toBe(true); + expect(yield* readPersistedAuthConfirmed()).toBe(true); // Explicit sign-out (auth.logout -> onChanged(false)) atomically clears sign-in // confirmation and marks signed out without waiting for a failing probe, blocking @@ -4998,7 +5017,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { Effect.gen(function* () { yield* instance.auth!.logout!(Effect.void); expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unknown"); - expect(lastPersistedAuthConfirmed).toBe(false); + expect(yield* readPersistedAuthConfirmed()).toBe(false); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], @@ -5084,9 +5103,9 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { expect(Option.getOrThrow(yield* Fiber.join(postReconfirmEnriched)).auth.status).toBe( "authenticated", ); - expect(lastPersistedAuthConfirmed).toBe(true); + expect(yield* readPersistedAuthConfirmed()).toBe(true); yield* instance.acpSessionManagement!.logout(directory); - expect(lastPersistedAuthConfirmed).toBe(false); + expect(yield* readPersistedAuthConfirmed()).toBe(false); yield* awaitLiveWatchUpdate( coordinator.publishLiveConfiguration(identity.instanceId, { models: [], From 2ccc5eaed665aedc086a0b616aa9b581cb26ff64 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:36:31 +0000 Subject: [PATCH 34/35] test(acp-registry): create isolated status cache dir before reading persisted auth --- packages/provider-acp-registry/src/server/driver.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 0b8737fe5bb35..8b331aca79047 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3288,6 +3288,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { const host = yield* ProviderHost.ProviderHost; const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: options.prefix }); const statusCacheDir = path.join(directory, "status-cache"); + yield* fileSystem.makeDirectory(statusCacheDir); const agentPath = path.join(directory, "agent.mjs"); const modelsPath = path.join(directory, "models.json"); yield* fileSystem.writeFileString(agentPath, fakeAgentSource); @@ -4950,6 +4951,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); yield* instance.snapshot.refresh; expect(Option.getOrThrow(yield* Fiber.join(initial)).auth.status).toBe("unknown"); + expect(yield* readPersistedAuthConfirmed()).toBeNull(); // Confirmed sign-in invalidates a still-valid enrichment cache so the post-sign-in refresh // probes newly available models instead of serving stale cached entries, and persists From 042787ccfc894fbd12351a773c2ba5c76c4af2c5 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:46:29 +0000 Subject: [PATCH 35/35] test(acp-registry): decode persisted auth file with Schema instead of JSON.parse cast --- packages/provider-acp-registry/src/server/driver.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 8b331aca79047..a3be26213908e 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3354,6 +3354,11 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); return result; }); + const decodePersistedAuthState = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ binding: Schema.String, authenticated: Schema.Boolean }), + ), + ); const readPersistedAuthConfirmed = () => Effect.gen(function* () { const entries = yield* fileSystem.readDirectory(statusCacheDir); @@ -3362,9 +3367,7 @@ it.layer(driverLayer)("AcpRegistryDriver periodic refresh", (it) => { ); if (authFile === undefined) return null; const contents = yield* fileSystem.readFileString(path.join(statusCacheDir, authFile)); - return ( - (JSON.parse(contents) as { readonly authenticated?: boolean }).authenticated ?? null - ); + return (yield* decodePersistedAuthState(contents)).authenticated; }); return { directory,