diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 90852f89dfa82..2de648c6c4b1e 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5419,7 +5419,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, @@ -5489,7 +5491,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"); @@ -5505,15 +5510,31 @@ describe("AcpAdapterV2", () => { : Effect.void, // Holds openSession's own publication until the adapter has seen the // late response, so adoption overlaps session configuration. - onSessionConfigurationUpdate: (configOptions) => - (publications++ === 0 ? Deferred.await(adoptionHandled) : Effect.void).pipe( - Effect.andThen(Effect.sync(() => publishedConfigurations.push(configOptions))), + 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, + }), + ), + ), Effect.andThen( configOptions.some((option) => option.category === "model") ? Deferred.succeed(adopted, undefined) : Effect.void, ), - ), + Effect.as(catalogKey), + ); + }, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, @@ -5577,12 +5598,171 @@ 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), ); + it.effect( + "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; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + 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; + 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: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + 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 Effect.sync(() => { + publications.push({ includeCatalog }); + return catalogKey; + }); + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + getConfigOptions: Effect.sync(() => activeConfigOptions), + handleSessionUpdate: (next) => + Effect.sync(() => { + sessionUpdate = next; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))), + }), + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-catalog-dedupe"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + 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], + "initial session setup publishes its catalog", + ); + + // config_option_update with unchanged model choices sets includeCatalog: false. + activeConfigOptions = makeModelSelect("composer-2", initialChoices); + yield* sessionUpdate!({ + sessionId: initialNativeId, + 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: initialNativeId, + update: { sessionUpdate: "config_option_update", configOptions: [] }, + }); + assert.deepEqual( + publications.map((entry) => entry.includeCatalog), + [true, false, true], + ); + + // 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], + ); + }).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/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..1adc3c87dae86 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: ["hermes", "auto", "default"], current: "default" }, - { models: ["hermes", "auto", "default"], current: "hermes" }, + { models: [], current: null }, + { models: [], current: "default" }, + { 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 a6662853ae028..a50389a486c1d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -257,4 +257,1295 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* Fiber.interrupt(consumer); }).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( + "preserves the active catalog independently of options-only updates from any session", + () => + 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 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({ 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 = { + 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.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 drops earlier per-model pending options. + const foreignOptionsOnly = { + models: [], + currentModelId: "model-a", + configOptions: [effortOption], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }; + yield* coordinator.publishLiveConfiguration(instanceId, foreignOptionsOnly); + const foreignSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + 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 behind the active catalog replays the catalog first, then each pending option update. + const replayed: Array = []; + const allReplayed = 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 === 3 ? Deferred.succeed(allReplayed, undefined) : Effect.void, + ), + Effect.asVoid, + ), + { afterRevision: 0 }, + ) + .pipe(Effect.forkChild({ startImmediately: true })); + 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)), + ); + + 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, + configOptions: [], + 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")); + + // Outdated catalogRevision cannot clear a newer catalog or advance clearedThroughRevision. + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: first.catalogRevision, + }), + ).toEqual(Option.none()); + expect( + (yield* coordinator.getLiveConfigurationWithRevision(instanceId)).clearedThroughRevision, + ).toBe(0); + + // 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: [modeOption("ask"), effortOption("high")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }; + yield* coordinator.publishLiveConfiguration(instanceId, modelV2Options); + const optionsSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + + const seenRetainInputs: Array = []; + expect( + yield* coordinator.clearLiveConfigurationIfRevision(instanceId, { + 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 }); + }, + }), + ).toEqual(Option.some(optionsSnap.revision)); + // 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(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: third.catalogRevision, + }), + ).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(), + configuration: Option.none(), + pendingOptions: [], + clearedThroughRevision: optionsSnap.revision, + }); + + // 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: [effortOption("high")], + modelOptionIds: ["effort"], + 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"); + + // 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( + 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); + 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( + 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()); + 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( + 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([ + { + 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( + 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); + 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( + Option.isSome( + 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, + }); + + // A same-model options-only update for model-a overrides model-a's own options without + // 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: lowEffort }, + { id: "model-c", name: "Model C", description: null, reasoningEffort: lowEffort }, + ], + currentModelId: "model-a", + configOptions: [effortOption("high")], + modelOptionIds: ["effort"], + 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", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + 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); + 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[1]?.configuration.advertisedReasoning).toEqual({ + "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( + Option.isSome( + 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 }); + + // 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( + Option.isSome( + 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; 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 }, + { 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 }, + }); + const modelCReasoningSnap = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "model-c", + configOptions: [modeOption("code")], + 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", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + expect( + Option.isSome( + 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.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-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( + 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( + (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( + Option.isSome( + 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 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", + 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: 255 }, (_, index) => [`newer-${index}`, lowEffort]), + ); + yield* coordinator.publishLiveConfiguration(instanceId, { + models: [], + currentModelId: "cand-pub", + configOptions: [], + modelOptionIds: [], + 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( + 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( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["oldest-orphan"] !== undefined, + ), + ).toBe(false); + expect( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["newer-0"] !== undefined, + ), + ).toBe(true); + expect( + afterCapClear.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["catalog-model"] !== 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 + // 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 }, + { 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, + }); + // 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( + afterModelBDroppedReasoning.pendingOptions.some( + (e) => e.configuration.advertisedReasoning?.["model-b"] !== undefined, + ), + ).toBe(false); + expect( + 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, + ).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( + Option.isSome( + 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( + Option.isSome( + 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, and clearLiveConfiguration returns + // 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, + ); + expect(yield* coordinator.clearLiveConfiguration(instanceId)).toBe( + beforeFullClear.revision, + ); + 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( + 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( + (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. + 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", + 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: "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", + configOptions: [modeOption("ask")], + modelOptionIds: [], + modelsFromModelSelect: false, + cappedPrefixKey: "prefix-255", + cappedLastModel: ordinaryTailModel, + }); + expect( + 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( + 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, + }); + 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 bec80c06ddd39..816a0929cfb44 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"; @@ -15,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; @@ -25,8 +39,178 @@ interface AvailableCommandsUpdate { interface LiveConfigurationUpdate { readonly instanceId: ProviderInstanceId; readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +export interface AcpRegistryRevisionedLiveConfiguration { + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +export interface AcpRegistryLiveConfigurationSnapshot { + readonly catalog: Option.Option; + readonly configuration: Option.Option; + readonly pendingOptions: ReadonlyArray; + readonly revision: number; + readonly catalogRevision: number; + readonly clearedThroughRevision: number; } +type AcpRegistryAdvertisedReasoningDescriptor = NonNullable< + AcpRegistryLiveConfiguration["models"][number]["reasoningEffort"] +>; + +interface StoredAdvertisedReasoning { + readonly descriptor: AcpRegistryAdvertisedReasoningDescriptor; + readonly revision: number; + readonly partialOptions?: boolean; +} + +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; +} + +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(), + configuration: Option.none(), + pendingOptions: [], + revision: 0, + catalogRevision: 0, + clearedThroughRevision: 0, +}; + +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, +}; + +const sortedPendingOptions = ( + optionsByModel: ReadonlyMap, +): ReadonlyArray => + Array.from(optionsByModel.values()).sort((left, right) => left.revision - right.revision); + +const stripAdvertisedReasoningSlugs = ( + entry: AcpRegistryRevisionedLiveConfiguration, + 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)) { + if (supersededSlugs.has(slug)) { + changed = true; + continue; + } + 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 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 => { + if (reasoningByModel.size === 0) return []; + const orphanedByRevision = new Map< + number, + { + readonly entries: Array; + readonly partialOptions: boolean; + } + >(); + for (const [slug, tracked] of reasoningByModel) { + if (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.push([slug, tracked.descriptor]); + } + } + 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 => { + const pending = sortedPendingOptions(optionsByModel); + if (reasoningByModel.size === 0) return pending; + const coveredReasoningSlugs = new Set(); + for (const entry of pending) { + const reasoning = entry.configuration.advertisedReasoning; + if (reasoning === undefined) continue; + for (const slug of Object.keys(reasoning)) { + coveredReasoningSlugs.add(slug); + } + } + const orphaned = collectOrphanedReasoningSteps(reasoningByModel, coveredReasoningSlugs); + if (orphaned.length === 0) return pending; + return [...pending, ...orphaned].sort((left, right) => left.revision - right.revision); +}; + +const toPublicLiveConfigurationSnapshot = ( + entry: StoredLiveConfiguration, +): AcpRegistryLiveConfigurationSnapshot => ({ + catalog: entry.catalog === null ? Option.none() : Option.some(entry.catalog), + configuration: entry.configuration, + pendingOptions: buildEffectivePendingOptions(entry.optionsByModel, entry.reasoningByModel), + revision: entry.revision, + catalogRevision: entry.catalogRevision, + clearedThroughRevision: entry.clearedThroughRevision, +}); + interface UrlAuthActionUpdate { readonly instanceId: ProviderInstanceId; readonly action: AcpRegistryUrlAuthAction | null; @@ -66,7 +250,16 @@ 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: { + readonly catalogRevision: number; + readonly retain?: ( + configuration: AcpRegistryLiveConfiguration, + ) => Option.Option; + }, + ) => Effect.Effect>; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, @@ -74,9 +267,19 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; + readonly getLiveConfigurationClearedThroughRevision: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + readonly getLiveConfigurationWithRevision: ( + instanceId: ProviderInstanceId, + ) => 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: ( instanceId: ProviderInstanceId, @@ -103,13 +306,14 @@ const make = Effect.gen(function* () { new Map(), ); const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurationByInstance = yield* Ref.make( - new Map(), - ); + const liveConfigurations = yield* Ref.make< + ReadonlyMap + >(new Map()); const urlAuthActionUpdates = yield* PubSub.unbounded(); 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); @@ -205,44 +409,453 @@ 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; + 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); + if ( + current.catalog === null && + Option.isNone(current.configuration) && + current.optionsByModel.size === 0 && + current.reasoningByModel.size === 0 && + current.catalogReasoningSupersededSlugs.size === 0 && + nextCleared === current.clearedThroughRevision + ) { + return [nextCleared, state] as const; + } + const next = new Map(state); + next.set(instanceId, { + ...current, + catalog: null, + configuration: Option.none(), + optionsByModel: EMPTY_OPTIONS_BY_MODEL, + reasoningByModel: EMPTY_REASONING_BY_MODEL, + catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, + clearedThroughRevision: nextCleared, + }); + return [nextCleared, next] as const; }); + }); + + const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = + Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( + function* (instanceId, options) { + return yield* Ref.modify(liveConfigurations, (state) => { + const current = state.get(instanceId) ?? EMPTY_STORED_LIVE_CONFIGURATION; + if (current.catalogRevision !== options.catalogRevision) { + 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); + const retain = options.retain; + 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 + ? undefined + : extractAdvertisedReasoning(current.catalog.configuration); + 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) { + 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 ( + preservedCatalogReasoning !== undefined && + current.catalog !== null && + key === current.catalog.configuration.currentModelId + ) { + candidates.set(key, { + revision: entry.revision, + configuration: { + ...entry.configuration, + advertisedReasoning: { + ...preservedCatalogReasoning, + ...entry.configuration.advertisedReasoning, + }, + }, + }); + continue; + } + 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 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, 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, + // 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), + ); + const hasAdvertisedReasoning = + kept.value.advertisedReasoning !== undefined && + Object.keys(kept.value.advertisedReasoning).length > 0; + if ( + modelOnlyOptions.length === 0 && + !hasAdvertisedReasoning && + kept.value.replaceModelOptions !== true + ) { + continue; + } + const keepDisplacedTailModel = + kept.value.cappedLastModel !== undefined && + kept.value.cappedPrefixKey !== undefined && + 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: retainedConfig, + revision: entry.revision, + }); + recordRetainedReasoning( + retainedConfig.advertisedReasoning, + entry.revision, + retainedConfig.currentModelId, + retainedConfig.partialOptions === true, + ); + continue; + } + retained.delete(kept.value.currentModelId); + retained.set(kept.value.currentModelId, { + configuration: kept.value, + revision: entry.revision, + }); + recordRetainedReasoning( + kept.value.advertisedReasoning, + entry.revision, + kept.value.currentModelId, + kept.value.partialOptions === true, + ); + } + while (retained.size > MAX_TRACKED_MODEL_OPTIONS) { + const oldestKey = retained.keys().next().value; + if (oldestKey === undefined) break; + retained.delete(oldestKey); + } + 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 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.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 [Option.some(nextCleared), state] as const; + } + const next = new Map(state); + next.set(instanceId, { + ...current, + catalog: null, + configuration: nextConfiguration, + optionsByModel: nextOptionsByModel, + reasoningByModel: nextReasoningByModel, + catalogReasoningSupersededSlugs: EMPTY_SLUG_SET, + clearedThroughRevision: nextCleared, + }); + return [Option.some(nextCleared), next] as const; + }); + }, + ); const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, configuration), - ).pipe( - Effect.andThen( - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, - }), + // Serialize store + PubSub publish uninterruptibly so concurrent sessions emit in revision order. + liveConfigurationPublishPermit.withPermit( + 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; + // 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(); + 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; + if (oldestKey === undefined) break; + updated.delete(oldestKey); + } + return updated; + })(); + const reasoningByModel = hasCatalog + ? EMPTY_REASONING_BY_MODEL + : (() => { + 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 (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, + }); + 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) { + const entry = (yield* Ref.get(liveConfigurations)).get(instanceId); + return entry === undefined + ? EMPTY_LIVE_CONFIGURATION_SNAPSHOT + : toPublicLiveConfigurationSnapshot(entry); + }, + ); + const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(liveConfigurationByInstance)).get(instanceId)); + 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) => + (instanceId, onUpdate, options) => Effect.scoped( Effect.gen(function* () { 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)).get(instanceId); + 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); + } + for (const entry of buildEffectivePendingOptions( + current.optionsByModel, + current.reasoningByModel, + )) { + if (entry.revision <= deliveredRevision) continue; + deliveredRevision = entry.revision; + yield* onUpdate(entry.configuration, entry.revision); + } } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.configuration)), + Stream.runForEach((update) => { + if (update.revision <= deliveredRevision) return Effect.void; + deliveredRevision = update.revision; + return onUpdate(update.configuration, update.revision); + }), ); }), ); @@ -344,8 +957,11 @@ const make = Effect.gen(function* () { getAvailableCommands, watchAvailableCommands, clearLiveConfiguration, + clearLiveConfigurationIfRevision, publishLiveConfiguration, getLiveConfiguration, + getLiveConfigurationClearedThroughRevision, + getLiveConfigurationWithRevision, watchLiveConfiguration, requestUrlAuthentication, acceptUrlAuthentication, diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..55ea49ae001ac 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -42,8 +42,8 @@ import * as ProviderContinuationRequests from "@t3tools/provider-core/server/Pro import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { normalizeAcpRegistryCommands, - normalizeAcpRegistryLiveConfiguration, normalizeAcpRegistryWebUrl, + prepareAcpRegistryLiveConfiguration, } from "./probe.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -374,11 +374,25 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), - onSessionConfigurationUpdate: (configOptions, modeState, modelState) => - runtimeCoordinator.publishLiveConfiguration( - options.instanceId, - normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState), - ), + onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => { + const prepared = prepareAcpRegistryLiveConfiguration( + configOptions, + 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 }), + ) + .pipe(Effect.as(includeCatalog ? prepared.catalogKey : lastCatalogKey)); + }, 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 564486b9d8269..a5ba66e6c6237 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -9,10 +9,12 @@ 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"; 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"; @@ -22,23 +24,32 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; 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, + MAX_DISPLACED_LEARNED_MODELS, + acpRegistryProbeSupersedesLiveCatalog, applyAcpRegistryAvailableCommands, applyAcpRegistryLiveConfiguration, buildCheckedAcpRegistrySnapshot, checkAcpRegistryProviderReadiness, checkAcpRegistryProviderStatus, isAcpRegistryCacheValid, + retainAcpRegistryLiveOptionsAfterProbe, updateAcpRegistryEnrichmentCache, + updateAcpRegistryLearnedModelsFromLive, + updateAcpRegistryLearnedModelsFromProbe, } from "./driver.ts"; import { + ACP_REGISTRY_MAX_MODELS, + type AcpRegistryLiveConfiguration, acpRegistryAdvertisesModelCatalog, acpRegistryProbeResult, normalizeAcpRegistryLiveConfiguration, + prepareAcpRegistryLiveConfiguration, } from "./probe.ts"; const decodeSettings = Schema.decodeSync(AcpRegistrySettings); @@ -416,6 +427,189 @@ 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([[], []]); + + // 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 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([]); + const providerAfterCatalogDisable = applyAcpRegistryLiveConfiguration( + provider, + catalogDisabled, + [], + ); + expect( + applyAcpRegistryLiveConfiguration( + 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 = prepareAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "opus", + availableModels: [ + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + { modelId: "opus", name: "Opus" }, + ], + }).toLiveConfiguration({ 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 = { + 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"]]); + + // 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", () => { @@ -770,12 +964,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, }, [], @@ -783,6 +1006,107 @@ 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: [placeholderEffort, sharedMode], + modelOptionIds: ["effort"], + 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); + 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); + + // 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( + discoveredNamedDefault, + { + models: [], + currentModelId: null, + configOptions: [placeholderEffort, sharedMode], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }, + [], + discoveredNamedDefault.models, + { hasDiscoveredCatalog: true }, + ); + expect(afterUnknownModelOptions.models.find((m) => m.slug === "default")?.isDefault).toBe(true); + expect( + 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, + { + 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, { @@ -830,6 +1154,69 @@ 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"]); + + const optionsOnly = prepareAcpRegistryLiveConfiguration( + [ + { + 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" }, + ], + }, + ).toLiveConfiguration({ 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", () => { @@ -851,9 +1238,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, @@ -864,605 +1265,6748 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.generation).toBe(5); expect(updated.entry).toBeNull(); }); -}); -describe("acpRegistryAdvertisesModelCatalog", () => { - it("counts choices inside option groups and available model state", () => { + it("lets authoritative fresh probes supersede live catalogs without letting provisional probes regress them", () => { expect( - acpRegistryAdvertisesModelCatalog([ - { - id: "model", - name: "Model", - type: "select" as const, - category: "model" as const, - currentValue: "auto", - options: [ - { - groupId: "qwen", - name: "Qwen", - options: [ - { value: "auto", name: "Auto" }, - { value: "qmodel", name: "Qwen3.8-Max" }, - ], - }, - ], - }, - ]), + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 3, + probedModelsFromModelSelect: false, + liveModelCount: 2, + liveModelsFromModelSelect: true, + }), ).toBe(true); expect( - acpRegistryAdvertisesModelCatalog([ - { - id: "model", - name: "Model", - type: "select" as const, - category: "model" as const, - currentValue: "smodel", - options: [{ value: "smodel", name: "Sonus" }], - }, - ]), + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: true, + liveModelCount: 3, + liveModelsFromModelSelect: true, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: true, + liveModelCount: 1, + liveModelsFromModelSelect: true, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 1, + liveModelsFromModelSelect: false, + }), + ).toBe(true); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 1, + liveModelsFromModelSelect: true, + }), ).toBe(false); - expect(acpRegistryAdvertisesModelCatalog(undefined)).toBe(false); expect( - acpRegistryAdvertisesModelCatalog(undefined, { - availableModels: [ - { modelId: "auto", name: "Auto", description: null }, - { modelId: "qmodel", name: "Qwen", description: null }, - ], - currentModelId: "auto", + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 3, + liveModelsFromModelSelect: true, + }), + ).toBe(false); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 0, + probedModelsFromModelSelect: false, + liveModelCount: 2, + liveModelsFromModelSelect: true, + }), + ).toBe(false); + // When neither source advertises models, an empty probe keeps live options on synthetic default. + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 0, + probedModelsFromModelSelect: false, + liveModelCount: 0, + liveModelsFromModelSelect: false, + }), + ).toBe(false); + expect( + acpRegistryProbeSupersedesLiveCatalog({ + probedModelCount: 1, + probedModelsFromModelSelect: false, + liveModelCount: 0, + liveModelsFromModelSelect: false, }), ).toBe(true); }); -}); - -const fakeAgentSource = ` -import { readFileSync } from "node:fs"; -import { createInterface } from "node:readline"; -const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); -createInterface({ input: process.stdin }).on("line", (line) => { - const { id, method } = JSON.parse(line); - if (id === undefined) return; - if (method === "initialize") { - send({ - id, - result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, + 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, + currentValue, + options: [ + { id: "ask", label: "Ask" }, + { id: "code", label: "Code" }, + ], }); - } else if (method === "session/new") { - const modelIds = JSON.parse(readFileSync(process.argv[2], "utf8")); - send({ - id, - result: { - sessionId: "probe-session", - models: { - currentModelId: modelIds[0], - availableModels: modelIds.map((modelId) => ({ modelId, name: modelId })), + 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: choices.map((id) => ({ id, label: id === "low" ? "Low" : "High" })), + }); + const legacy = { + id: "legacy", + label: "Legacy", + type: "select" as const, + currentValue: "on", + options: [{ id: "on", label: "On" }], + }; + const fast = (currentValue: boolean) => ({ + id: "fast", + label: "Fast", + type: "boolean" as const, + currentValue, + }); + + 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(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"), effort("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + partialOptions: true, + replaceModelOptions: 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, + }), + ); + + // 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, + replaceModelOptions: true, + }); + 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(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( + 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()); + + // 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( + { + 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(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( + { + 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( + { + 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(selectionOnly); + }); +}); + +describe("prepareAcpRegistryLiveConfiguration", () => { + 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 }>, + ) => [ + { + 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 = prepareAcpRegistryLiveConfiguration(modelSelect("m0", choices)).catalogKey; + expect(prepareAcpRegistryLiveConfiguration(modelSelect("m1", choices)).catalogKey).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.cappedPrefixKey).toBeDefined(); + expect(overflowOptionsOnly.cappedLastModel).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); + // 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({ + includeCatalog: false, + }), + [], + ); + 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); + // 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 + // 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") => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }); + 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: [], }, }); - send({ - method: "session/update", - params: { - sessionId: "probe-session", - update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + 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, }); - } else { - send({ id, result: {} }); - } -}); -`; + 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) => ({ + 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({ + includeCatalog: false, + }), + [], + ); + 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( + [ + ...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) => ({ + 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( + [ + { 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)]), + ).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"); + // 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"]]); + // 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"]]); + // 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); + // Even without replacement intent, an empty displaced-tail update strips reasoning when + // 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, + }), + partialOptions: true, + preserveDefault: true, + }, + ); + 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 = { + ...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 = { + 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}`, + 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 + // normalized non-current _meta.reasoningEfforts via advertisedReasoning. + 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 = prepareAcpRegistryLiveConfiguration([], undefined, modelState); + const withEffortHigh = prepareAcpRegistryLiveConfiguration( + [effortSelect("high")], + undefined, + modelState, + ); + const withEffortLow = prepareAcpRegistryLiveConfiguration( + [effortSelect("low")], + undefined, + modelState, + ); + 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 }, + { id: "constructor", name: "Constructor", 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"]]); + expect( + appliedToActive.models.find((model) => model.slug === "constructor")?.capabilities + ?.optionDescriptors, + ).toEqual([]); + }); +}); + +describe("acpRegistryAdvertisesModelCatalog", () => { + it("counts choices inside option groups and available model state", () => { + expect( + acpRegistryAdvertisesModelCatalog([ + { + id: "model", + name: "Model", + type: "select" as const, + category: "model" as const, + currentValue: "auto", + options: [ + { + groupId: "qwen", + name: "Qwen", + options: [ + { value: "auto", name: "Auto" }, + { value: "qmodel", name: "Qwen3.8-Max" }, + ], + }, + ], + }, + ]), + ).toBe(true); + expect( + acpRegistryAdvertisesModelCatalog([ + { + id: "model", + name: "Model", + type: "select" as const, + category: "model" as const, + currentValue: "smodel", + options: [{ value: "smodel", name: "Sonus" }], + }, + ]), + ).toBe(false); + expect(acpRegistryAdvertisesModelCatalog(undefined)).toBe(false); + expect( + acpRegistryAdvertisesModelCatalog(undefined, { + availableModels: [ + { modelId: "auto", name: "Auto", description: null }, + { modelId: "qmodel", name: "Qwen", description: null }, + ], + currentModelId: "auto", + }), + ).toBe(true); + }); +}); + +const fakeAgentSource = ` +import { readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ + id, + result: { + protocolVersion: 1, + agentCapabilities: { providers: {}, auth: { logout: {} } }, + authMethods: [{ id: "agent-login", name: "Agent Login" }], + agentInfo: { name: "fake", version: "1.5.9" }, + }, + }); + } 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")); + if (!Array.isArray(payload) && typeof payload.provisional === "string") { + send({ + id, + result: { + sessionId: "probe-session", + ...(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 || "transient-a", + options: [ + { value: payload.provisional || "transient-a", name: payload.provisional || "transient-a" }, + { 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; + } + if (payload && !Array.isArray(payload) && typeof payload.fail === "string") { + send({ + id, + error: { code: payload.code ?? -32603, message: payload.fail }, + }); + return; + } + 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: { + sessionId: "probe-session", + models: { + currentModelId: availableModels[0]?.modelId, + availableModels, + }, + ...(configOptions === undefined ? {} : { configOptions }), + }, + }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + } else { + send({ id, result: {} }); + } +}); +`; + +// Reports `effort` levels for its current model only and logs each model switch. +const perModelEffortAgentSource = ` +import { appendFileSync, readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const [logPath, modelsPath] = process.argv.slice(2); +const levels = JSON.parse(readFileSync(modelsPath, "utf8")); +const modelIds = Object.keys(levels); +let current = modelIds[0]; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const configOptions = () => [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: current, + options: modelIds.map((value) => ({ value, name: value })), + }, + ...(levels[current] === null + ? [] + : [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[current][0], + options: levels[current].map((value) => ({ value, name: value })), + }, + ]), +]; +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method, params } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } }); + } else if (method === "session/new") { + send({ id, result: { sessionId: "probe-session", configOptions: configOptions() } }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + } else if (method === "session/set_config_option" && params.configId === "model") { + appendFileSync(logPath, params.value + "\\n"); + current = params.value; + send({ id, result: { configOptions: configOptions() } }); + } else { + send({ id, result: {} }); + } +}); +`; + +const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( + Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), + Layer.provideMerge(IdAllocator.layer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + +it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) => { + it.effect("creates without inspecting the agent, which may fetch the registry", () => + Effect.gen(function* () { + 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: "unconfigured" }), + inspect: () => Effect.die("inspected during creation"), + }), + ); + expect(yield* instance.snapshot.getSnapshot).toMatchObject({ + installed: false, + message: "Checking ACP Registry agent readiness...", + }); + }), + ); + + 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 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" }, + ], + }, + ), + ); + 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" }, + { value: "off", name: "Off" }, + ], + }, + ], + }), + ); + + 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 (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", + 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 }), + ); + 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", "off"]]); + + // 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* 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", () => + 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(["model-a"])); + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ source: "local", commandPath: "agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "agent", + version: null, + distribution: "local", + }), + resolve: () => + Effect.succeed({ + distribution: "local" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + const probed = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.version === "1.5.9"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(probed); + + const nextPublished = yield* instance.snapshot.streamChanges.pipe( + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + const next = yield* Fiber.join(nextPublished); + expect(Option.map(next, (snapshot) => snapshot.version)).toEqual(Option.some("1.5.9")); + }), + ); + + it.effect("keeps options learned for each model across a refresh", () => + 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(["model-a", "model-b"])); + 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 effortBySlug = (snapshot: ServerProvider) => + snapshot.models + .map( + (model) => + `${model.slug}:${(model.capabilities?.optionDescriptors ?? []).map((option) => option.id).join("+")}`, + ) + .join(); + const waitFor = (expected: string) => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortBySlug(snapshot) === expected), + Stream.runHead, + ); + const session = (currentModelId: string) => + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + undefined, + { + currentModelId, + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-b", name: "model-b" }, + ], + }, + ); + + const probed = yield* waitFor("model-a:,model-b:").pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(probed); + const learned = yield* waitFor("model-a:effort,model-b:effort").pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, session("model-b")); + yield* coordinator.publishLiveConfiguration(identity.instanceId, session("model-a")); + yield* Fiber.join(learned); + + yield* instance.snapshot.refresh; + 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, + prepareAcpRegistryLiveConfiguration( + [ + { + 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 } }, + ], + }, + ).toLiveConfiguration({ includeCatalog: false }), + ); + expect(effortBySlug(Option.getOrThrow(yield* Fiber.join(modeTweaked)))).toBe( + "model-a:mode,model-b:mode+variant", + ); + }), + ); + + const makePerModelEffortAgent = Effect.fn("makePerModelEffortAgent")(function* ( + levels: Readonly | null>>, + ) { + 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 logPath = path.join(directory, "switches.log"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, perModelEffortAgentSource); + yield* fileSystem.writeFileString(logPath, ""); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(levels)); + return { + spawn: { command: process.execPath, args: [agentPath, logPath, modelsPath] }, + modelSwitches: fileSystem + .readFileString(logPath) + .pipe(Effect.map((log) => log.split("\n").filter((line) => line.length > 0))), + }; + }); + const createRegistryInstance = ( + instanceId: ProviderInstanceId, + spawn: { readonly command: string; readonly args: ReadonlyArray }, + version: string, + ) => + AcpRegistryDriver.create({ + instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version, + distribution: "npx", + }), + resolve: () => Effect.succeed({ distribution: "npx" as const, spawn }), + }), + ); + const effortLevels = (snapshot: ServerProvider) => + snapshot.models + .map((model) => { + const effort = model.capabilities?.optionDescriptors?.find( + (option) => option.id === "effort", + ); + const levels = effort?.type === "select" ? effort.options.map((option) => option.id) : []; + return `${model.slug}:${levels.join("+")}`; + }) + .join(); + const refreshUntilEffortLevels = ( + instance: Effect.Success>, + expected: string, + ) => + Effect.gen(function* () { + const reached = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === expected), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(reached); + }); + + // A session's report: the model select plus the current model's own effort levels. + const liveSession = ( + models: ReadonlyArray, + model: string, + levels: ReadonlyArray, + ) => + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: model, + options: models.map((value) => ({ value, name: value })), + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[0]!, + options: levels.map((value) => ({ value, name: value })), + }, + ]); + + it.effect("reads each visible model's own reasoning levels before its first session", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_discovery"); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + favorites: [{ provider: instanceId, model: "fav" }], + providerModelPreferences: { [instanceId]: { hiddenModels: ["hidden"], modelOrder: [] } }, + }); + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + plain: null, + other: ["low", "high"], + hidden: ["low"], + fav: ["none", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + "default:medium+high,plain:,other:low+high,hidden:,fav:none+max", + ); + // Favorites first, hidden models skipped, then the agent's own model restored. + expect(yield* agent.modelSwitches).toEqual(["fav", "plain", "other", "default"]); + + // What a live session reports for a model outranks what discovery read for it. + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const models = ["default", "plain", "other", "hidden", "fav"]; + const live = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + effortLevels(snapshot) === "default:high,plain:,other:xhigh,hidden:,fav:none+max", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + expect(Option.isSome(yield* Fiber.join(live))).toBe(true); + }), + ); + + it.effect("reads every model of a catalog larger than one discovery batch in one refresh", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_large_catalog"); + const others = Array.from({ length: 30 }, (_, index) => `model-${index}`); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + providerModelPreferences: { + [instanceId]: { hiddenModels: [], modelOrder: [...others, "opus"] }, + }, + }); + const agent = yield* makePerModelEffortAgent({ + sonnet: ["medium"], + ...Object.fromEntries(others.map((slug) => [slug, ["low"]])), + opus: ["high", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + ["sonnet:medium", ...others.map((slug) => `${slug}:low`), "opus:high+max"].join(), + ); + expect(yield* agent.modelSwitches).toEqual([...others, "opus", "sonnet"]); + }), + ); + + it.effect("keeps discovered reasoning levels across restarts until the agent updates", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_persisted"); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + other: ["low", "high"], + }); + const runInstance = ( + version: string, + expected: string, + then: ( + instance: Effect.Success>, + ) => Effect.Effect = () => Effect.void, + ) => + Effect.scoped( + createRegistryInstance(instanceId, agent.spawn, version).pipe( + Effect.tap((instance) => refreshUntilEffortLevels(instance, expected)), + Effect.flatMap(then), + ), + ); + + yield* runInstance("1.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // Reused after a restart; a live session then replaces the stored levels. + yield* runInstance("1.0.0", "default:medium+high,other:low+high", (instance) => + Effect.gen(function* () { + const replaced = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === "default:high,other:xhigh"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const models = ["default", "other"]; + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + yield* Fiber.join(replaced); + // The session ends with this instance; only the stored levels remain. + yield* coordinator.clearLiveConfiguration(instanceId); + }), + ); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + yield* runInstance("1.0.0", "default:medium+high,other:xhigh"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // An agent update makes every stored level stale. + yield* runInstance("2.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default", "other", "default"]); + }), + ); +}); + +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 setupPeriodicDriver = (options: { + readonly prefix: string; + readonly initialModels: unknown; + readonly wrapCoordinator?: ( + coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"], + ) => AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"]; + readonly wrapFileSystem?: (fs: FileSystem.FileSystem) => FileSystem.FileSystem; + readonly inspect?: () => AcpRegistrySupport.AcpRegistryInspection; + readonly onResolve?: () => Effect.Effect; + }) => + 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"); + yield* fileSystem.makeDirectory(statusCacheDir); + 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 effectiveFileSystem = + options.wrapFileSystem === undefined ? fileSystem : options.wrapFileSystem(fileSystem); + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + 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, + 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 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; + }); + 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); + 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 (yield* decodePersistedAuthState(contents)).authenticated; + }); + return { + directory, + coordinator, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + readPersistedAuthConfirmed, + }; + }); + + 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 }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(initial)).models.map((model) => model.slug), + ).toEqual(["old-model", "other-model"]); + + const sessionWithOptions = ( + currentModelId: string, + effortValue: "low" | "high" | "turbo" = "high", + options?: { readonly includeCatalog?: boolean; readonly includeLegacy?: boolean }, + ) => + prepareAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: effortValue, + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ...(effortValue === "turbo" ? [{ value: "turbo", name: "Turbo" }] : []), + ], + }, + ...(options?.includeLegacy === true + ? [ + { + id: "legacy", + name: "Legacy", + category: "other" as const, + type: "select" as const, + currentValue: "on", + options: [{ value: "on", name: "On" }], + }, + ] + : []), + ], + undefined, + { + currentModelId, + 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 }, + ); + const learnedEffort = 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" && + 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, + sessionWithOptions("other-model", "high", { includeLegacy: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + sessionWithOptions("old-model", "low", { includeLegacy: true }), + ); + yield* Fiber.join(learnedEffort); + + // 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( + Effect.forkScoped({ startImmediately: true }), + ); + 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", + ]); + // 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([ + ["fast", "on"], + ["effort", "low"], + ]); + expect( + updated.models + .find((model) => model.slug === "other-model") + ?.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, 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) => ({ + models: config.models, + effort: config.configOptions.find((option) => option.id === "effort")?.currentValue, + })), + ).toEqual(Option.some({ models: [], effort: "low" })); + + // 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) => + snapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue === "high", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + 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( + 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 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( + cachedAfterSuperseded.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["fast", "on"], + ["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"); + 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 while retrying on the short provisional TTL", + () => + Effect.gen(function* () { + const { coordinator, instance, waitForEnriched, writeModels } = yield* setupPeriodicDriver({ + prefix: "acp-driver-provisional-", + initialModels: ["new-model", "old-model", "other-model"], + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + 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-a", name: "Live A", description: null }, + { id: "live-b", name: "Live B", description: null }, + ], + currentModelId: "live-a", + configOptions: [], + modelsFromModelSelect: true, + }); + yield* Fiber.join(liveCatalogApplied); + + 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((model) => model.slug), + ).toEqual(["live-a", "live-b"]); + + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "live-a", + 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 }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(cachedWithinRetryTtl)).models.map( + (model) => model.slug, + ), + ).toEqual(["live-a", "live-b"]); + + // 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 }), + ); + 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"]); + }), + ); + + 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 }), + ); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "old-model", + configOptions: [effortOption("low")], + modelOptionIds: ["effort"], + modelsFromModelSelect: false, + }); + yield* Fiber.join(optionsBeforeFailure); + + yield* writeModels({ 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.message).toBeTruthy(); + expect(warned.models.map((model) => model.slug)).toEqual([ + "new-model", + "old-model", + "other-model", + ]); + expect( + warned.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.find((option) => option.id === "effort") + ?.currentValue, + ).toBe("low"); + + // 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 }), + ); + 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; + const uninstalledSnap = Option.getOrThrow(yield* Fiber.join(uninstalled)); + expect(uninstalledSnap.installed).toBe(false); + expect(uninstalledSnap.status).toBe("error"); + + // 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"); + expect(afterUninstalledLive.models).toEqual(uninstalledSnap.models); + + // 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( + "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 signOutRejected = yield* Deferred.make(); + let pendingResolveGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let pendingLiveWatch: { + readonly minRevision: number; + readonly done: Deferred.Deferred; + } | null = null; + let injectModeAfterInitialClear = true; + let injectCatalogBeforeSignOutClear = false; + 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); + }); + // 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* () { + 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. + 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, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-clear-", + 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(() => { + 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 (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; + } + 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 + // live revision. + if ( + Option.isSome(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: () => + Effect.gen(function* () { + const gate = pendingResolveGate; + if (gate !== null) { + pendingResolveGate = null; + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + }), + }); + + // 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; + 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"]. + yield* writeModels({ fail: "Sign in required", code: -32000 }); + yield* TestClock.adjust("16 minutes"); + 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(authProbeEntered); + + 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* Deferred.succeed(releaseAuthProbe, 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, + ); + + // 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 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 }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(restored); + + // 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, + }), + ); + 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( + (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 }), + ); + yield* instance.snapshot.refresh; + expect( + Option.getOrThrow(yield* Fiber.join(afterDisable)).models.map((model) => model.slug), + ).toEqual(["placeholder"]); + + // 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( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(restored2); + + // 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, + }), + ); + 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* () { + 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", + ]); + }), + ); + + // 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"]], + ]); + + // 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"); + + const restoredForAuthInvalidate = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + 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", + ]); + }), + ); + + // If a newer live catalog lands right before an unauthenticated probe clears + // 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; + 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, + ); + // 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, { + 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"); + 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)); + 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, 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: [ + { 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((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "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 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: [], + 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; + 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", + ]); + expect( + 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([]); + }), + ); + 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, + }), + ); + const snapAfterBlockedWatcherOption = yield* instance.snapshot.getSnapshot; + expect( + 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 + // 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.nativeSessions === undefined), + 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), + ); + 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 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, + readPersistedAuthConfirmed, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-auth-reopen-", + initialModels: ["new-model", "old-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)), + 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; + 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 + // 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"); + 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(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(yield* readPersistedAuthConfirmed()).toBe(false); + }), + ); + + // 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.nativeSessions === undefined), + 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", + ); + 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 + // 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"); + expect(yield* readPersistedAuthConfirmed()).toBe(false); + 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; + const snapAfterAuthLogoutRefresh = yield* instance.snapshot.getSnapshot; + expect(snapAfterAuthLogoutRefresh.auth.status).toBe("unknown"); + expect( + snapAfterAuthLogoutRefresh.models.flatMap( + (m) => m.capabilities?.optionDescriptors ?? [], + ), + ).toEqual([]); + }), + ); + + // 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"], + 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 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(yield* readPersistedAuthConfirmed()).toBe(true); + yield* instance.acpSessionManagement!.logout(directory); + expect(yield* readPersistedAuthConfirmed()).toBe(false); + 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* 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( + (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, + }), + ); + const snapAfterRacedReady = yield* instance.snapshot.getSnapshot; + expect(snapAfterRacedReady.nativeSessions).toBeUndefined(); + expect( + 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): + // 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* () { + 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: "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-a", + 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.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"); + + // 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* () { + 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"); + + // 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"); + }), + ); + + 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 { 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(() => + secondProbeReleased + ? Deferred.succeed(secondProbeEnteredCommit, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + }), + onResolve: () => + Effect.gen(function* () { + if (gateNextResolve) { + gateNextResolve = false; + yield* Deferred.succeed(secondProbeEntered, undefined); + yield* Deferred.await(releaseSecondProbe); + secondProbeReleased = true; + } + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + 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", + 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 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); + + 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", + ]); + + // 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 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, + instance, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = 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) { + gateNextResolve = false; + yield* Deferred.succeed(secondProbeEntered, undefined); + yield* Deferred.await(releaseSecondProbe); + } + }), + }); + + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); + + // 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; + yield* Deferred.await(secondProbeEntered); + + // Hold the raw watcher callback for this in-flight options-only revision until after the + // probe commits, verifying clearedThroughRevision advances past it and the snapshot stays clean. + holdNextOptionsCallback = true; + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + 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: "high", + options: [ + { id: "low", label: "Low" }, + { id: "high", label: "High" }, + ], + }, + ], + modelOptionIds: ["effort"], + 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", + "new-model", + ]); + // 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"]]); + + // Releasing the delayed raw watcher callback leaves the reconciled snapshot and cache intact. + 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* () { + 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; + const cachedSnapshot = Option.getOrThrow(yield* Fiber.join(cached)); + expect(cachedSnapshot.models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "new-model", + ]); + expect( + cachedSnapshot.models + .find((model) => model.slug === "old-model") + ?.capabilities?.optionDescriptors?.map((option) => [option.id, option.currentValue]), + ).toEqual([ + ["mode", "plan"], + ["effort", "low"], + ]); + }), + ); + + 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 newerCallbackEntered = yield* Deferred.make(); + const releaseNewerCallback = yield* Deferred.make(); + const newerCallbackDone = yield* Deferred.make(); + const secondWatcherSubscribed = yield* Deferred.make(); + let checkProviderInspected = false; + let skipNextLiveRead = false; + let armed = false; + let trackNextWatcher = false; + + const gatedCoordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...coordinator, + getLiveConfigurationWithRevision: (instanceId) => + Effect.gen(function* () { + if (armed) { + if (skipNextLiveRead) { + skipNextLiveRead = false; + } else { + 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, + ) + : 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, + ); + }), + }; + + 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( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + gatedCoordinator, + ), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection(readyInspection), + inspect: () => + Effect.sync(() => { + if (armed && !checkProviderInspected) { + checkProviderInspected = true; + skipNextLiveRead = true; + } + return readyInspection; + }), + 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"]); + + // 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); + expect((yield* instance.snapshot.getSnapshot).models.map((model) => model.slug)).toEqual([ + "old-model", + "other-model", + "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"]), + ); + 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", "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; + 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, + waitForEnriched, + writeModels, + withBlockedForegroundStartup, + } = yield* setupPeriodicDriver({ + prefix: "acp-driver-handoff-", + initialModels: ["old-model", "other-model"], + wrapCoordinator: (base) => ({ + ...base, + 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, + ), + ), + ); + }, + }), + }); + + 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 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( + 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* () { + 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, 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) => + 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"]]); + }), + ); + }), + ); + + 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, + }); -// Reports `effort` levels for its current model only and logs each model switch. -const perModelEffortAgentSource = ` -import { appendFileSync, readFileSync } from "node:fs"; -import { createInterface } from "node:readline"; -const [logPath, modelsPath] = process.argv.slice(2); -const levels = JSON.parse(readFileSync(modelsPath, "utf8")); -const modelIds = Object.keys(levels); -let current = modelIds[0]; -const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); -const configOptions = () => [ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: current, - options: modelIds.map((value) => ({ value, name: value })), - }, - ...(levels[current] === null - ? [] - : [ + 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) => + Option.isSome(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 (using the replayed + // catalog's reasoning rules rather than the probe's disabled-model set or baseline). + injectLiveCatalogAfterClear = true; + 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 }), + ); + 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"]]); + + // 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"]]); + }), + ); + + 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: "effort", - name: "Effort", - category: "thought_level", - type: "select", - currentValue: levels[current][0], - options: levels[current].map((value) => ({ value, name: value })), + id: "model", + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue, + options: choices, }, - ]), -]; -createInterface({ input: process.stdin }).on("line", (line) => { - const { id, method, params } = JSON.parse(line); - if (id === undefined) return; - if (method === "initialize") { - send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } }); - } else if (method === "session/new") { - send({ id, result: { sessionId: "probe-session", configOptions: configOptions() } }); - send({ - method: "session/update", - params: { - sessionId: "probe-session", - update: { sessionUpdate: "available_commands_update", availableCommands: [] }, - }, - }); - } else if (method === "session/set_config_option" && params.configId === "model") { - appendFileSync(logPath, params.value + "\\n"); - current = params.value; - send({ id, result: { configOptions: configOptions() } }); - } else { - send({ id, result: {} }); - } -}); -`; + ]; + 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 driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( - Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), - Layer.provideMerge(IdAllocator.layer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), -); + 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, + ), + }), + }); -it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) => { - it.effect("creates without inspecting the agent, which may fetch the registry", () => - Effect.gen(function* () { - 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: "unconfigured" }), - inspect: () => Effect.die("inspected during creation"), + 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, }), ); - expect(yield* instance.snapshot.getSnapshot).toMatchObject({ - installed: false, - message: "Checking ACP Registry agent readiness...", + 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); + + // 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); + // 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")], }); - }), - ); + 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("m256"); - 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; + 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( + afterRestoreProbe.models + .at(-1) + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).toEqual([["variant", "v1"]]); - 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] }, - }), - }), + // 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 }), ); - const modelSlugs = instance.snapshot.streamChanges.pipe( - Stream.map((snapshot) => snapshot.models.map((model) => model.slug)), + yield* instance.snapshot.refresh; + const afterProbeOverflowWhileLiveM255 = Option.getOrThrow( + yield* Fiber.join(probeOverflowWhileLiveM255), ); - const waitForModels = (expected: ReadonlyArray) => - modelSlugs.pipe( - Stream.filter((slugs) => slugs.join() === expected.join()), - Stream.runHead, - ); + 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); - const probed = yield* waitForModels(["old-model", "other-model"]).pipe( + // 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* instance.snapshot.refresh; - 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" }, - ], + prepareAcpRegistryLiveConfiguration( + selectFrom("m256", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: true }), + ); + yield* Fiber.join(sawBaseM256); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m256", fullChoices)).toLiveConfiguration({ + includeCatalog: true, }), ); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-model", "new-model"])); - - const refreshed = yield* waitForModels(["old-model", "new-model"]).pipe( + const sawRestoredM255 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models[0]?.isDefault === true), + Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* instance.invalidateCaches ?? Effect.void; - yield* instance.snapshot.refresh; - expect(Option.isSome(yield* Fiber.join(refreshed))).toBe(true); - }), - ); - - it.effect("keeps a local agent's reported version through the next readiness check", () => - 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(["model-a"])); - - const instance = yield* AcpRegistryDriver.create({ - instanceId: identity.instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ source: "local", commandPath: "agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "agent", - version: null, - distribution: "local", - }), - resolve: () => - Effect.succeed({ - distribution: "local" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, - }), + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m0", fullChoices)).toLiveConfiguration({ + includeCatalog: false, }), ); - const probed = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.version === "1.5.9"), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), + expect(Option.getOrThrow(yield* Fiber.join(sawRestoredM255)).models.at(-1)?.slug).toBe( + "m255", ); - yield* instance.snapshot.refresh; - yield* Fiber.join(probed); - const nextPublished = yield* instance.snapshot.streamChanges.pipe( + // 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* instance.invalidateCaches ?? Effect.void; - yield* instance.snapshot.refresh; - const next = yield* Fiber.join(nextPublished); - expect(Option.map(next, (snapshot) => snapshot.version)).toEqual(Option.some("1.5.9")); - }), - ); - - it.effect("keeps options learned for each model across a refresh", () => - 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(["model-a", "model-b"])); - 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] }, - }), + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m256", fullChoices)).toLiveConfiguration({ + includeCatalog: true, }), ); - const effortBySlug = (snapshot: ServerProvider) => - snapshot.models - .map( - (model) => - `${model.slug}:${(model.capabilities?.optionDescriptors ?? []).map((option) => option.id).join("+")}`, - ) - .join(); - const waitFor = (expected: string) => - instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => effortBySlug(snapshot) === expected), - Stream.runHead, - ); - const session = (currentModelId: string) => - normalizeAcpRegistryLiveConfiguration( - [ - { - id: "effort", - name: "Effort", - category: "thought_level", - type: "select", - currentValue: "high", - options: [ - { value: "low", name: "Low" }, - { value: "high", name: "High" }, - ], - }, - ], - undefined, - { - currentModelId, - availableModels: [ - { modelId: "model-a", name: "model-a" }, - { modelId: "model-b", name: "model-b" }, - ], - }, - ); - - const probed = yield* waitFor("model-a:,model-b:").pipe( - Effect.forkScoped({ startImmediately: true }), + yield* Fiber.join(sawOverflowM256); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m256", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: true }), ); - yield* instance.snapshot.refresh; - yield* Fiber.join(probed); - const learned = yield* waitFor("model-a:effort,model-b:effort").pipe( + 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, session("model-b")); - yield* coordinator.publishLiveConfiguration(identity.instanceId, session("model-a")); - yield* Fiber.join(learned); - - yield* instance.snapshot.refresh; - expect(effortBySlug(yield* instance.snapshot.getSnapshot)).toBe( - "model-a:effort,model-b:effort", + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration( + selectFrom("m0", withoutM255Choices), + ).toLiveConfiguration({ includeCatalog: false }), ); - }), - ); - - const makePerModelEffortAgent = Effect.fn("makePerModelEffortAgent")(function* ( - levels: Readonly | null>>, - ) { - 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 logPath = path.join(directory, "switches.log"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, perModelEffortAgentSource); - yield* fileSystem.writeFileString(logPath, ""); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(levels)); - return { - spawn: { command: process.execPath, args: [agentPath, logPath, modelsPath] }, - modelSwitches: fileSystem - .readFileString(logPath) - .pipe(Effect.map((log) => log.split("\n").filter((line) => line.length > 0))), - }; - }); - const createRegistryInstance = ( - instanceId: ProviderInstanceId, - spawn: { readonly command: string; readonly args: ReadonlyArray }, - version: string, - ) => - AcpRegistryDriver.create({ - instanceId, - displayName: identity.displayName, - enabled: true, - environment: [], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "test-agent", - version, - distribution: "npx", - }), - resolve: () => Effect.succeed({ distribution: "npx" as const, spawn }), - }), - ); - const effortLevels = (snapshot: ServerProvider) => - snapshot.models - .map((model) => { - const effort = model.capabilities?.optionDescriptors?.find( - (option) => option.id === "effort", - ); - const levels = effort?.type === "select" ? effort.options.map((option) => option.id) : []; - return `${model.slug}:${levels.join("+")}`; - }) - .join(); - const refreshUntilEffortLevels = ( - instance: Effect.Success>, - expected: string, - ) => - Effect.gen(function* () { - const reached = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => effortLevels(snapshot) === expected), + 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* instance.snapshot.refresh; - yield* Fiber.join(reached); - }); - - // A session's report: the model select plus the current model's own effort levels. - const liveSession = ( - models: ReadonlyArray, - model: string, - levels: ReadonlyArray, - ) => - normalizeAcpRegistryLiveConfiguration([ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: model, - options: models.map((value) => ({ value, name: value })), - }, - { - id: "effort", - name: "Effort", - category: "thought_level", - type: "select", - currentValue: levels[0]!, - options: levels.map((value) => ({ value, name: value })), - }, - ]); - - it.effect("reads each visible model's own reasoning levels before its first session", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acpRegistry_discovery"); - yield* (yield* TestProviderHost.TestProviderHostSettings).set({ - ...DEFAULT_SERVER_SETTINGS, - favorites: [{ provider: instanceId, model: "fav" }], - providerModelPreferences: { [instanceId]: { hiddenModels: ["hidden"], modelOrder: [] } }, - }); - const agent = yield* makePerModelEffortAgent({ - default: ["medium", "high"], - plain: null, - other: ["low", "high"], - hidden: ["low"], - fav: ["none", "max"], - }); - const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); - - yield* refreshUntilEffortLevels( - instance, - "default:medium+high,plain:,other:low+high,hidden:,fav:none+max", + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m1", fullChoices)).toLiveConfiguration({ + includeCatalog: false, + }), ); - // Favorites first, hidden models skipped, then the agent's own model restored. - expect(yield* agent.modelSwitches).toEqual(["fav", "plain", "other", "default"]); + expect(Option.getOrThrow(yield* Fiber.join(sawUntaggedM1)).models.at(-1)?.slug).toBe("m256"); - // What a live session reports for a model outranks what discovery read for it. - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const models = ["default", "plain", "other", "hidden", "fav"]; - const live = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - effortLevels(snapshot) === "default:high,plain:,other:xhigh,hidden:,fav:none+max", - ), + // 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( - instanceId, - liveSession(models, "other", ["xhigh"]), + 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"); + // 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( - instanceId, - liveSession(models, "default", ["high"]), + identity.instanceId, + prepareAcpRegistryLiveConfiguration(selectFrom("m1", fullChoices)).toLiveConfiguration({ + includeCatalog: false, + }), ); - expect(Option.isSome(yield* Fiber.join(live))).toBe(true); + yield* Fiber.join(sawDrainedM1); + expect(seenAfterRelease).toEqual([["m1", "m255"]]); }), ); - it.effect("reads every model of a catalog larger than one discovery batch in one refresh", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acpRegistry_large_catalog"); - const others = Array.from({ length: 30 }, (_, index) => `model-${index}`); - yield* (yield* TestProviderHost.TestProviderHostSettings).set({ - ...DEFAULT_SERVER_SETTINGS, - providerModelPreferences: { - [instanceId]: { hiddenModels: [], modelOrder: [...others, "opus"] }, - }, - }); - const agent = yield* makePerModelEffortAgent({ - sonnet: ["medium"], - ...Object.fromEntries(others.map((slug) => [slug, ["low"]])), - opus: ["high", "max"], - }); - const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + 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(); + const cacheHitInCommit = yield* Deferred.make(); + let gateProbe = false; + 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(() => { + trackCacheHitCommit = false; + }).pipe(Effect.andThen(Deferred.succeed(cacheHitInCommit, undefined))) + : Effect.void + ).pipe(Effect.andThen(base.getUrlAuthAction(instanceId))), + 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" }], + }; - yield* refreshUntilEffortLevels( - instance, - ["sonnet:medium", ...others.map((slug) => `${slug}:low`), "opus:high+max"].join(), - ); - expect(yield* agent.modelSwitches).toEqual([...others, "opus", "sonnet"]); - }), - ); + const initial = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(initial); - it.effect("keeps discovered reasoning levels across restarts until the agent updates", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acpRegistry_persisted"); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const agent = yield* makePerModelEffortAgent({ - default: ["medium", "high"], - other: ["low", "high"], - }); - const runInstance = ( - version: string, - expected: string, - then: ( - instance: Effect.Success>, - ) => Effect.Effect = () => Effect.void, - ) => - Effect.scoped( - createRegistryInstance(instanceId, agent.spawn, version).pipe( - Effect.tap((instance) => refreshUntilEffortLevels(instance, expected)), - Effect.flatMap(then), + // 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* runInstance("1.0.0", "default:medium+high,other:low+high"); - expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + 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); - // Reused after a restart; a live session then replaces the stored levels. - yield* runInstance("1.0.0", "default:medium+high,other:low+high", (instance) => - Effect.gen(function* () { - const replaced = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => effortLevels(snapshot) === "default:high,other:xhigh"), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - const models = ["default", "other"]; - yield* coordinator.publishLiveConfiguration( - instanceId, - liveSession(models, "other", ["xhigh"]), - ); - yield* coordinator.publishLiveConfiguration( - instanceId, - liveSession(models, "default", ["high"]), + // 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"]]); + + // 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 }, + }), + ), ); - yield* Fiber.join(replaced); - // The session ends with this instance; only the stored levels remain. - yield* coordinator.clearLiveConfiguration(instanceId); - }), - ); - expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + 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"], + ]); - yield* runInstance("1.0.0", "default:medium+high,other:xhigh"); - expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + // 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); - // An agent update makes every stored level stale. - yield* runInstance("2.0.0", "default:medium+high,other:low+high"); - expect(yield* agent.modelSwitches).toEqual(["other", "default", "other", "default"]); - }), + gateAfterCacheRead = 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, wait until it enters commitEnrichment and drains + // liveSnapshotSemaphore via a follow-up command publish, then inspect getSnapshot. + trackCacheHitCommit = true; + yield* Deferred.succeed(releaseCacheHit, undefined); + 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") + ?.capabilities?.optionDescriptors?.map((d) => [d.id, d.currentValue]), + ).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" }, + ], + }); + + 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) => + base.watchLiveConfiguration( + instanceId, + (configuration, revision) => { + if (!blockReasoningWatcher) return onUpdate(configuration, revision); + blockReasoningWatcher = false; + const gate = releaseReasoningWatcher; + return Deferred.await(gate).pipe( + Effect.andThen(onUpdate(configuration, revision)), + ); + }, + options, + ), + }), + }); + + 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 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 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", + 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: [], + 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 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); + + 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, { + models: [], + currentModelId: "b", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* coordinator.publishLiveConfiguration(identity.instanceId, { + models: [], + currentModelId: "a", + configOptions: [modeOption], + modelOptionIds: [], + modelsFromModelSelect: false, + }); + yield* Deferred.succeed(releaseProbeResolve, undefined); + yield* Fiber.join(refreshFiber); + 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: "" }); + 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 33c5ab9a46663..2ca1692f9e626 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"; @@ -49,11 +50,13 @@ import { type ProviderSnapshotSettings, } from "@t3tools/provider-core/server/snapshotSettings"; import { + ACP_REGISTRY_MAX_MODELS, type AcpRegistryAvailableCommands, type AcpRegistryConfigurationProbe, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, type AcpRegistryModelDiscovery, + cappedAcpRegistryModelPrefixKey, deleteAcpRegistrySession, disableAcpRegistryProvider, listAcpRegistrySessions, @@ -67,6 +70,7 @@ import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator. import * as AcpRegistryAuth from "./auth.ts"; import * as AcpRegistryAuthenticationState from "./authenticationState.ts"; import { + type AcpRegistryLearnedModelOptions, acpRegistryCurrentModelOptions, acpRegistryModelsToDiscover, makeAcpRegistryLearnedModelOptionsStore, @@ -78,6 +82,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); @@ -92,6 +130,68 @@ interface AcpRegistryEnrichmentCache { } | null; } +interface AcpRegistryProbeOptionSchema { + readonly models: ReadonlyArray; + readonly currentModelId: string | null; + readonly configOptions: ReadonlyArray; + readonly modelOptionIds: ReadonlySet; + readonly cappedTailIsOverflow?: boolean; +} + +interface AcceptedAcpRegistryCatalog { + readonly models: ReadonlyArray; + readonly builtInModelCount: number; + readonly modelsFromModelSelect: boolean; + readonly reasoningDisabledModelSlugs: ReadonlySet; + readonly probeOptions: AcpRegistryProbeOptionSchema | null; + readonly probeBaselineModels: ReadonlyArray | null; +} + +const EMPTY_SLUG_SET: ReadonlySet = new Set(); + +const EMPTY_ACCEPTED_CATALOG: AcceptedAcpRegistryCatalog = { + models: [], + builtInModelCount: 0, + modelsFromModelSelect: false, + reasoningDisabledModelSlugs: EMPTY_SLUG_SET, + probeOptions: null, + probeBaselineModels: null, +}; + +function isExplicitSingletonCatalog(catalog: { + readonly builtInModelCount: number; + readonly modelsFromModelSelect: boolean; +}): boolean { + return catalog.builtInModelCount === 1 && catalog.modelsFromModelSelect; +} + +function liveConfigurationReplacesAcceptedCatalog( + configuration: AcpRegistryLiveConfiguration, + accepted: AcceptedAcpRegistryCatalog, +): boolean { + return ( + configuration.models.length > 1 || + (configuration.models.length === 1 && + (configuration.modelsFromModelSelect === true || + (accepted.builtInModelCount <= 1 && !accepted.modelsFromModelSelect))) + ); +} + +export function acpRegistryProbeSupersedesLiveCatalog(input: { + readonly probedModelCount: number; + readonly probedModelsFromModelSelect: boolean; + 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.probedModelsFromModelSelect) return true; + return input.liveModelCount === 1 && !input.liveModelsFromModelSelect; +} + export function isAcpRegistryCacheValid( entry: NonNullable, inspectedVersion: string | null, @@ -109,30 +209,56 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly configuration: AcpRegistryLiveConfiguration; readonly customModels: ReadonlyArray; readonly now: number; + readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; }): AcpRegistryEnrichmentCache { - const { cache, configuration, customModels, now } = input; + const { + cache, + configuration, + customModels, + now, + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + } = 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, + undefined, + { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + 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 && + (overflowTailChanged || + 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, }, }; } @@ -160,6 +286,521 @@ 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) || isReasoningDescriptor(descriptor); +} + +function modelWithSpecificOptions( + model: ServerProviderModel, + descriptors: ReadonlyArray, +): ServerProviderModel { + return { + ...model, + capabilities: + descriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: descriptors }), + }; +} + +function readAdvertisedReasoning( + advertisedReasoning: AcpRegistryLiveConfiguration["advertisedReasoning"], + slug: string, +): NonNullable | undefined { + return advertisedReasoning !== undefined && Object.hasOwn(advertisedReasoning, slug) + ? advertisedReasoning[slug] + : undefined; +} + +export function updateAcpRegistryLearnedModelsFromLive( + 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( + 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 dataChanged = false; + let orderTouched = 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 || + readAdvertisedReasoning(configuration.advertisedReasoning, model.slug) !== undefined; + const isReasoningDisabled = disabledReasoningSlugs.has(model.slug); + if (!isCurrentModel && !hasAdvertisedReasoning && !isReasoningDisabled) continue; + 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 && options?.replaceCurrentLearnedOptions !== 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); + if (model.slug === lastLearnedSlug) lastLearnedSlug = undefined; + dataChanged = true; + } + continue; + } + const updated = modelWithSpecificOptions(model, specific); + if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { + learnedBySlug.delete(model.slug); + learnedBySlug.set(model.slug, updated); + lastLearnedSlug = model.slug; + dataChanged = true; + } else if (model.slug !== lastLearnedSlug) { + learnedBySlug.delete(model.slug); + learnedBySlug.set(model.slug, previous); + lastLearnedSlug = model.slug; + orderTouched = true; + } + } + // 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.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)), + ); + const previous = learnedBySlug.get(slug); + const replace = options?.replaceCurrentLearnedOptions === true; + 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); + dataChanged = true; + } + } else { + const updated: ServerProviderModel = { + slug, + name: configuration.cappedLastModel.name, + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: combined, + }), + }; + if (previous === undefined || !Equal.equals(previous.capabilities, updated.capabilities)) { + learnedBySlug.delete(slug); + learnedBySlug.set(slug, updated); + dataChanged = true; + } else if (slug !== lastLearnedSlug) { + learnedBySlug.delete(slug); + learnedBySlug.set(slug, previous); + orderTouched = 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); + dataChanged = true; + } + 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( + probed: ProviderOptionDescriptor, + live: ProviderOptionDescriptor | undefined, +): Option.Option { + if ( + live === undefined || + live.id !== probed.id || + live.type !== probed.type || + live.currentValue === undefined + ) { + return Option.none(); + } + if (probed.type === "boolean") { + return Option.some({ ...probed, currentValue: live.currentValue as boolean }); + } + return probed.options.some((option) => option.id === live.currentValue) + ? Option.some({ ...probed, currentValue: live.currentValue as string }) + : Option.none(); +} + +/** + * 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, + probe: AcpRegistryProbeOptionSchema, +): Option.Option { + const probedModelById = new Map(probe.models.map((model) => [model.id, model])); + const matchingCappedTail = + live.cappedLastModel !== undefined && + live.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey(probe.models.map((model) => model.id)) === + live.cappedPrefixKey && + 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) ?? + (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 ?? []); + + const probeSharedIds = new Set(); + const sharedDescriptors: Array = []; + for (const descriptor of probe.configOptions) { + if (isModelSpecificDescriptor(descriptor, probe.modelOptionIds)) continue; + 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 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 (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; + for (const descriptor of live.configOptions) { + if (probeSharedIds.has(descriptor.id)) continue; + if (!isModelSpecificDescriptor(descriptor, liveModelOptionIds)) continue; + if (isReasoningDescriptor(descriptor)) { + if (reasoningDisabled) continue; + if (advertisedReasoning != null) { + if (!addedAdvertisedReasoning) { + const retained = compatibleLiveOptionValue(advertisedReasoning, descriptor); + if (Option.isSome(retained)) { + modelDescriptors.push(retained.value); + addedAdvertisedReasoning = true; + } + } + continue; + } + } + modelDescriptors.push(descriptor); + } + } + } + + const overflowFields = matchingCappedTail ?? {}; + const advertisedReasoningFields = + retainedAdvertisedReasoning === undefined + ? {} + : { advertisedReasoning: retainedAdvertisedReasoning }; + 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 + // even when no active config options survive, unless nothing differs from probe default. + if ( + matchingCappedTail === undefined && + retainedAdvertisedReasoning === undefined && + (currentProbedModel === undefined || currentProbedModel.id === probe.currentModelId) + ) { + return Option.none(); + } + return Option.some({ + models: [], + currentModelId: live.currentModelId, + configOptions: [], + modelOptionIds: [], + modelsFromModelSelect: false, + partialOptions: true, + ...replaceModelOptionsFields, + ...overflowFields, + ...advertisedReasoningFields, + }); + } + return Option.some({ + models: [], + // 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, + ...replaceModelOptionsFields, + ...overflowFields, + ...advertisedReasoningFields, + }); +} + +function mergeLearnedModelOptions( + models: ReadonlyArray, + learned: ReadonlyArray, + options?: { + readonly currentModelId?: string | null; + readonly skipModelSlugs?: ReadonlySet; + readonly skipOptionIdsByModel?: ReadonlyMap>; + 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 skipOptionIdsByModel = options?.skipOptionIdsByModel; + 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), + ); + 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) || + skipModelSlugs.has(model.slug) + ) { + return model; + } + const rawPreviousDescriptors = + learnedBySlug.get(model.slug)?.capabilities?.optionDescriptors ?? []; + const skippedOptionIds = skipOptionIdsByModel?.get(model.slug); + const previousDescriptors = + skippedOptionIds !== undefined + ? rawPreviousDescriptors.filter((descriptor) => !skippedOptionIds.has(descriptor.id)) + : rawPreviousDescriptors; + 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) || + currentDescriptors.some( + (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning", + ); + const extra = previousDescriptors.filter( + (descriptor) => + !currentIds.has(descriptor.id) && + (!hasExplicitReasoningState || + descriptor.type !== "select" || + descriptor.role !== "reasoning"), + ); + const combined = + extra.length === 0 ? nextCurrentDescriptors : [...nextCurrentDescriptors, ...extra]; + if (Equal.equals(currentDescriptors, combined)) return model; + changed = true; + return { + ...model, + capabilities: createModelCapabilities({ + optionDescriptors: combined, + }), + }; + }); + return changed ? preserveCappedOverflowTail(models, merged) : models; +} + +export function updateAcpRegistryLearnedModelsFromProbe( + 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 = []; + 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), + ); + 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)); + } + // 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)) { + 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; +} + function modelsFromDiscovery( discovery: | Pick< @@ -183,7 +824,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 ?? [] @@ -329,7 +978,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 ? {} : { @@ -356,54 +1010,339 @@ 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 ? preserveCappedOverflowTail(models, 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); + } + } + } else if (!model.isCustom && !reasoningDisabled) { + const advertised = readAdvertisedReasoning(configuration.advertisedReasoning, model.slug); + if (advertised !== undefined) { + 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); + } + } + } + } + if (Equal.equals(existing, nextDescriptors)) return model; + return { + ...model, + capabilities: + nextDescriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: nextDescriptors }), + }; + }); + const overlaid = preserveCappedOverflowTail(models, updated); + return configuration.preserveDefault === true + ? overlaid + : withAcpRegistryDefaultModel(overlaid, selectedProbedModelId); +} + export function applyAcpRegistryLiveConfiguration( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, customModels: ReadonlyArray, previousModels: ReadonlyArray = provider.models, + options?: { + readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; + readonly probeSharedDescriptors?: ReadonlyArray | undefined; + readonly probeConfigOptions?: ReadonlyArray | undefined; + }, ): 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); - const selectedProbedModelId = + const disabledReasoningSlugs: ReadonlySet = useLiveCatalog + ? EMPTY_SLUG_SET + : (options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET); + const cappedLastModel = + !useLiveCatalog && + configuration.preserveDefault !== true && configuration.currentModelId !== null && - probedModels.some((model) => model.slug === configuration.currentModelId) - ? configuration.currentModelId - : (probedModels.find((model) => model.isDefault)?.slug ?? null); + configuration.cappedLastModel !== undefined && + configuration.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey(probedModels.map((model) => model.slug)) === + configuration.cappedPrefixKey + ? configuration.cappedLastModel + : undefined; + const currentTailSlug = probedModels[ACP_REGISTRY_MAX_MODELS - 1]?.slug; + const providerHasOverflowTail = hasCappedOverflowTail(provider.models, currentTailSlug); + const tailSlotReplacement = + cappedLastModel !== undefined && + 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) || + (configuration.currentModelId !== null && + probedModels.some((model) => model.slug === configuration.currentModelId)); + const selectedProbedModelId = liveCurrentModelInProbed + ? configuration.currentModelId + : (probedModels.find((model) => model.isDefault)?.slug ?? null); + 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(); + 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); + } + } + } + const learnedPreviousModels = previousModels + .filter((model) => !model.isCustom) + .map((model) => { + if ( + model.slug !== tailSlotReplacement.id || + partialOverrideIds.size === 0 || + !model.capabilities?.optionDescriptors?.length + ) { + return model; + } + const kept = model.capabilities.optionDescriptors.filter( + (descriptor) => !partialOverrideIds.has(descriptor.id), + ); + return kept.length === model.capabilities.optionDescriptors.length + ? model + : modelWithSpecificOptions(model, kept); + }); + const replacementBuiltIn = modelsFromDiscovery( + { + models: [tailSlotReplacement], + currentModelId: null, + configOptions: options?.probeSharedDescriptors ?? [], + }, + [], + learnedPreviousModels, + )[0]!; + const nextBuiltInModels = probedModels.map((model, index) => + index === ACP_REGISTRY_MAX_MODELS - 1 ? replacementBuiltIn : model, + ); + const fallbackCustomDescriptors = + options?.probeConfigOptions ?? options?.probeSharedDescriptors ?? []; + const customModelCapabilities = + fallbackCustomDescriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors: fallbackCustomDescriptors }); + return providerModelsFromSettings(nextBuiltInModels, customModels, customModelCapabilities); + })(); + const partialDisabledReasoning = + tailSlotReplacement?.reasoningEffort === null + ? new Set([...disabledReasoningSlugs, tailSlotReplacement.id]) + : disabledReasoningSlugs; + return { + ...snapshot, + status: provider.enabled ? "ready" : provider.status, + models: markCappedOverflowTail( + overlayPartialLiveOptions( + modelsForOverlay, + configuration, + selectedProbedModelId, + partialDisabledReasoning, + ), + nextOverflowTailSlug, + ), + }; + } + // 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 hasDiscoveredCatalog = + options?.hasDiscoveredCatalog === true || options?.preserveSingleModelCatalog === true; + const hasSyntheticDefaultOnly = + !hasDiscoveredCatalog && probedModels.length === 1 && probedModels[0]?.slug === "default"; + const dropUnmatchedModelOptions = + !useLiveCatalog && + !liveCurrentModelInProbed && + !(configuration.currentModelId === null && hasSyntheticDefaultOnly); + const unmatchedModelOptionIds = dropUnmatchedModelOptions + ? new Set(configuration.modelOptionIds ?? []) + : EMPTY_SLUG_SET; + const effectiveConfigOptions = dropUnmatchedModelOptions + ? configuration.configOptions.filter( + (descriptor) => !isModelSpecificDescriptor(descriptor, unmatchedModelOptionIds), + ) + : configuration.configOptions; + const hasAdvertisedReasoning = + !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 (tailSlotReplacement !== undefined) { + retainedDiscoveryModels[ACP_REGISTRY_MAX_MODELS - 1] = tailSlotReplacement; + } const discovery = useLiveCatalog ? configuration : { ...configuration, - models: probedModels.map((model) => ({ - id: model.slug, - name: model.name, - description: null, - })), - currentModelId: selectedProbedModelId, + models: retainedDiscoveryModels, + currentModelId: dropUnmatchedModelOptions + ? configuration.currentModelId + : selectedProbedModelId, + configOptions: effectiveConfigOptions, }; + const nextModels = + !useLiveCatalog && + effectiveConfigOptions.length === 0 && + !hasAdvertisedReasoning && + tailSlotReplacement === undefined && + !liveCurrentModelInProbed + ? stripReasoningForDisabledModels( + withAcpRegistryDefaultModel(provider.models, selectedProbedModelId), + disabledReasoningSlugs, + ) + : 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), - ), + models: markCappedOverflowTail( + dropUnmatchedModelOptions && (effectiveConfigOptions.length > 0 || hasAdvertisedReasoning) + ? withAcpRegistryDefaultModel(nextModels, selectedProbedModelId) + : nextModels, + nextOverflowTailSlug, + ), }; } @@ -421,7 +1360,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( @@ -519,6 +1458,125 @@ export function buildCheckedAcpRegistrySnapshot( }); } +interface DetailedAcpRegistryProviderStatus { + readonly provider: ServerProvider; + readonly probedModels: ReadonlyArray; + readonly probedConfigOptions: ReadonlyArray; + readonly probedModelCount: number; + readonly probedModelsFromModelSelect: boolean; + readonly probedCappedTailIsOverflow: boolean; + readonly probedCurrentModelId: string | null; + readonly probedModelOptionIds: ReadonlySet; + readonly reasoningDisabledModelSlugs: ReadonlySet; +} + +const checkAcpRegistryProviderStatusDetailed = Effect.fn( + "AcpRegistryDriver.checkProviderStatusDetailed", +)(function* ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + readonly modelDiscovery?: Omit & { + readonly onProbed: ( + detailed: DetailedAcpRegistryProviderStatus, + ) => Effect.Effect>; + }; + }, + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.fn.Return< + DetailedAcpRegistryProviderStatus, + never, + AcpRegistrySupport.AcpRegistryCatalog | Requirements +> { + const checkedAt = DateTime.formatIso(yield* DateTime.now); + const withoutProbe = (provider: ServerProvider): DetailedAcpRegistryProviderStatus => ({ + provider, + probedModels: [], + probedConfigOptions: [], + probedModelCount: 0, + probedModelsFromModelSelect: false, + probedCappedTailIsOverflow: false, + probedCurrentModelId: null, + probedModelOptionIds: EMPTY_SLUG_SET, + reasoningDisabledModelSlugs: EMPTY_SLUG_SET, + }); + 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 withoutProbe( + buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: inspected.success, + }), + ); + } + const inspection = inspected.success; + const detailedFromProbe = ( + probe: AcpRegistryConfigurationProbeResult, + ): DetailedAcpRegistryProviderStatus => ({ + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection, + probe, + }), + probedModels: probe.probe.models, + probedConfigOptions: probe.probe.configOptions, + probedModelCount: probe.probe.models.length, + probedModelsFromModelSelect: probe.modelsFromModelSelect === true, + probedCappedTailIsOverflow: probe.cappedTailIsOverflow === true, + probedCurrentModelId: probe.probe.currentModelId, + probedModelOptionIds: new Set(probe.probe.modelOptionIds ?? []), + reasoningDisabledModelSlugs: new Set( + probe.probe.models.filter((model) => model.reasoningEffort === null).map((model) => model.id), + ), + }); + const modelDiscovery = input.modelDiscovery; + const probed = yield* Effect.result( + probeConfiguration({ + instanceId: input.instanceId, + settings: input.settings, + cwd: input.cwd, + environment: providerProbeEnvironment(input.environment), + ...(modelDiscovery === undefined + ? {} + : { + modelDiscovery: { + onProbed: (probe) => modelDiscovery.onProbed(detailedFromProbe(probe)), + onDiscovered: modelDiscovery.onDiscovered, + }, + }), + }), + ); + return Result.isFailure(probed) + ? withoutProbe( + buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection, + probeError: probed.failure, + }), + ) + : detailedFromProbe(probed.success); +}); + export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")( function* ( input: SnapshotIdentity & { @@ -531,63 +1589,21 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check }, 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({ - ...input, - checkedAt, - inspection: { - status: "failed", - message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`, - }, - }); - } - if (inspected.success.status !== "ready") { - return buildCheckedAcpRegistrySnapshot({ - ...input, - checkedAt, - inspection: inspected.success, - }); - } - const inspection = inspected.success; - const modelDiscovery = input.modelDiscovery; - const probed = yield* Effect.result( - probeConfiguration({ - instanceId: input.instanceId, - settings: input.settings, - cwd: input.cwd, - environment: providerProbeEnvironment(input.environment), + const { modelDiscovery, ...rest } = input; + return (yield* checkAcpRegistryProviderStatusDetailed( + { + ...rest, ...(modelDiscovery === undefined ? {} : { modelDiscovery: { - onProbed: (probe) => - modelDiscovery.onProbed( - buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection, probe }), - ), + onProbed: (detailed) => modelDiscovery.onProbed(detailed.provider), onDiscovered: modelDiscovery.onDiscovered, }, }), - }), - ); - return Result.isFailure(probed) - ? buildCheckedAcpRegistrySnapshot({ - ...input, - checkedAt, - inspection: inspected.success, - probeError: probed.failure, - }) - : buildCheckedAcpRegistrySnapshot({ - ...input, - checkedAt, - inspection: inspected.success, - probe: probed.success, - }); + }, + probeConfiguration, + )).provider; }, ); @@ -649,13 +1665,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; @@ -712,27 +1733,341 @@ export const AcpRegistryDriver: ProviderDriver>([]); const learnedModelOptions = yield* makeAcpRegistryLearnedModelOptionsStore({ cacheDir: host.paths.providerStatusCacheDir, instanceId, settings: effectiveConfig, }); + const clearLearnedModels = Ref.set(learnedModels, []).pipe( + Effect.andThen(learnedModelOptions.clear), + ); + const applyDiskLearnedModelOptions = ( + provider: ServerProvider, + learned: AcpRegistryLearnedModelOptions, + options?: { + readonly currentModelId?: string | null; + readonly skipModelSlugs?: ReadonlySet; + readonly reasoningDisabledModelSlugs?: ReadonlySet; + }, + ): ServerProvider => { + const next = withAcpRegistryLearnedModelOptions(provider, learned, options); + return next === provider + ? provider + : { ...next, models: preserveCappedOverflowTail(provider.models, next.models) }; + }; + // 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); + // 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(initialLiveSessionResetRevision); + // Tracks signed-out state so readiness and the watcher reject options-only updates until a + // ready probe or sign-in succeeds. `epoch` advances on sign-out/cache resets so a ready probe + // losing a live-catalog race still reopens replay of pending options unless superseded. + const signedOutState = yield* Ref.make({ signedOut: false, epoch: 0 }); + const markSignedOut = Ref.update(signedOutState, (state) => ({ + signedOut: true, + epoch: state.epoch + 1, + })); + const advanceSignedOutEpoch = Ref.update(signedOutState, (state) => ({ + ...state, + 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); + const resetAppliedLiveRevisions = Ref.set(lastAppliedLiveCatalogRevision, 0).pipe( + Effect.andThen(Ref.set(lastAppliedLiveRevision, 0)), + ); const applyLiveConfiguration = Effect.fn("AcpRegistryDriver.applyLiveConfiguration")(function* ( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, + options?: { + readonly preserveSingleModelCatalog?: boolean | undefined; + readonly reasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly effectiveReasoningDisabledModelSlugs?: ReadonlySet | undefined; + readonly hasDiscoveredCatalog?: boolean | undefined; + readonly replaceCurrentLearnedOptions?: boolean | undefined; + readonly probeSharedDescriptors?: ReadonlyArray | undefined; + readonly probeConfigOptions?: ReadonlyArray | undefined; + }, ) { - const reported = acpRegistryCurrentModelOptions(configuration); - if (reported !== undefined) { - yield* learnedModelOptions.learn(reported.modelId, reported.options, "live"); + const accepted = yield* Ref.get(acceptedCatalog); + const preserveSingleModelCatalog = + options?.preserveSingleModelCatalog ?? isExplicitSingletonCatalog(accepted); + const reasoningDisabledModelSlugs = + options?.reasoningDisabledModelSlugs ?? accepted.reasoningDisabledModelSlugs; + const effectiveReasoningDisabledModelSlugs = + options?.effectiveReasoningDisabledModelSlugs ?? reasoningDisabledModelSlugs; + const hasDiscoveredCatalog = options?.hasDiscoveredCatalog ?? accepted.builtInModelCount > 0; + const disabledForLearning = + configuration.models.length > 0 ? EMPTY_SLUG_SET : reasoningDisabledModelSlugs; + const next = yield* 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 applied = applyAcpRegistryLiveConfiguration( + provider, + configuration, + effectiveConfig.customModels, + previousModels, + { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + probeSharedDescriptors: options?.probeSharedDescriptors, + probeConfigOptions: options?.probeConfigOptions, + }, + ); + return [ + applied, + updateAcpRegistryLearnedModelsFromLive( + learned, + applied.models, + configuration, + disabledForLearning, + { + replaceCurrentLearnedOptions: options?.replaceCurrentLearnedOptions === true, + }, + ), + ]; + }); + if (configuration.partialOptions !== true) { + const reported = acpRegistryCurrentModelOptions(configuration); + if (reported !== undefined) { + yield* learnedModelOptions.learn(reported.modelId, reported.options, "live"); + } else if ( + hasDiscoveredCatalog && + configuration.currentModelId !== null && + configuration.configOptions.length === 0 + ) { + yield* learnedModelOptions.learn(configuration.currentModelId, [], "live"); + } + } else if ( + options?.replaceCurrentLearnedOptions === true && + configuration.currentModelId !== null + ) { + const currentModel = next.models.find( + (model) => !model.isCustom && model.slug === configuration.currentModelId, + ); + if (currentModel !== undefined) { + const modelOptionIds = new Set(configuration.modelOptionIds ?? []); + const currentSpecific = (currentModel.capabilities?.optionDescriptors ?? []).filter( + (descriptor) => isModelSpecificDescriptor(descriptor, modelOptionIds), + ); + yield* learnedModelOptions.learn(configuration.currentModelId, currentSpecific, "live"); + } } - return withAcpRegistryLearnedModelOptions( - applyAcpRegistryLiveConfiguration(provider, configuration, effectiveConfig.customModels), - yield* learnedModelOptions.get, - ); + return applyDiskLearnedModelOptions(next, yield* learnedModelOptions.get, { + currentModelId: configuration.currentModelId, + reasoningDisabledModelSlugs: effectiveReasoningDisabledModelSlugs, + }); }); - const clearLearnedModels = learnedModelOptions.clear; + const applyLiveConfigurationStep = Effect.fn("AcpRegistryDriver.applyLiveConfigurationStep")( + function* ( + current: ServerProvider, + configuration: AcpRegistryLiveConfiguration, + options: { + readonly preserveStatus?: boolean | undefined; + readonly revision: number; + }, + ) { + const acceptedBefore = yield* Ref.get(acceptedCatalog); + const replacesCatalog = liveConfigurationReplacesAcceptedCatalog( + configuration, + acceptedBefore, + ); + const preserveSingleModelCatalog = isExplicitSingletonCatalog(acceptedBefore); + const reasoningDisabledModelSlugs = acceptedBefore.reasoningDisabledModelSlugs; + const hasDiscoveredCatalog = acceptedBefore.builtInModelCount > 0; + const withPreservedStatus = (applied: ServerProvider) => + options.preserveStatus === true + ? { + ...applied, + status: current.status, + ...(current.message === undefined ? {} : { message: current.message }), + } + : applied; + + const probeOptions = acceptedBefore.probeOptions; + if (!replacesCatalog && probeOptions !== null) { + const effectiveConfiguration = + configuration.partialOptions === true + ? Option.some(configuration) + : retainAcpRegistryLiveOptionsAfterProbe(configuration, probeOptions); + const replacedLiveModelId = + (configuration.partialOptions !== true || configuration.replaceModelOptions === true) && + configuration.currentModelId !== null && + (probeOptions.models.some((model) => model.id === configuration.currentModelId) || + (configuration.cappedLastModel !== undefined && + configuration.cappedPrefixKey !== undefined && + cappedAcpRegistryModelPrefixKey(probeOptions.models.map((model) => model.id)) === + configuration.cappedPrefixKey && + configuration.currentModelId === configuration.cappedLastModel.id && + (configuration.cappedTailIsOverflow === true || + probeOptions.cappedTailIsOverflow === true))) + ? configuration.currentModelId + : null; + const skipModelSlugs = + replacedLiveModelId === null ? EMPTY_SLUG_SET : new Set([replacedLiveModelId]); + const skipOptionIdsByModel = (() => { + if (Option.isNone(effectiveConfiguration)) return undefined; + const partial = effectiveConfiguration.value; + 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 (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)) { + 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. + const pureBaseline = acceptedBefore.probeBaselineModels ?? acceptedBefore.models; + const baselineModels = yield* Ref.get(learnedModels).pipe( + Effect.map((learned) => + mergeLearnedModelOptions(pureBaseline, learned, { + skipModelSlugs, + ...(skipOptionIdsByModel === undefined ? {} : { skipOptionIdsByModel }), + reasoningDisabledModelSlugs, + overlayLearnedValues: true, + }), + ), + ); + const baselineProvider = applyDiskLearnedModelOptions( + pureBaseline.length > 0 ? { ...current, models: baselineModels } : current, + yield* learnedModelOptions.get, + { + skipModelSlugs, + reasoningDisabledModelSlugs, + }, + ); + const probeSharedDescriptors = probeOptions.configOptions.filter( + (descriptor) => !isModelSpecificDescriptor(descriptor, probeOptions.modelOptionIds), + ); + const applied = yield* Option.match(effectiveConfiguration, { + onNone: () => + replacedLiveModelId === null + ? Effect.succeed(baselineProvider) + : Ref.update(learnedModels, (learned) => + updateAcpRegistryLearnedModelsFromLive( + learned, + baselineProvider.models, + { + models: [], + currentModelId: replacedLiveModelId, + configOptions: [], + modelOptionIds: Array.from(probeOptions.modelOptionIds), + modelsFromModelSelect: false, + }, + reasoningDisabledModelSlugs, + ), + ).pipe( + Effect.andThen(learnedModelOptions.learn(replacedLiveModelId, [], "live")), + Effect.as(baselineProvider), + ), + onSome: (partial) => + applyLiveConfiguration(baselineProvider, partial, { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + hasDiscoveredCatalog, + replaceCurrentLearnedOptions: replacedLiveModelId !== null, + probeSharedDescriptors, + probeConfigOptions: probeOptions.configOptions, + }), + }); + yield* Ref.update(lastAppliedLiveRevision, (prev) => Math.max(prev, options.revision)); + return withPreservedStatus(applied); + } + + const nextReasoningDisabled = replacesCatalog + ? new Set( + configuration.models + .filter((model) => model.reasoningEffort === null) + .map((model) => model.id), + ) + : acceptedBefore.reasoningDisabledModelSlugs; + const applied = yield* applyLiveConfiguration(current, configuration, { + preserveSingleModelCatalog, + reasoningDisabledModelSlugs, + effectiveReasoningDisabledModelSlugs: nextReasoningDisabled, + hasDiscoveredCatalog, + }); + const next = withPreservedStatus(applied); + const savedToAccepted = + current.installed && (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), + ); + } + } + 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 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 preserveStatus?: boolean; + }, ) { if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); if (input.installed) yield* learnedModelOptions.setVersion(input.version); @@ -743,22 +2078,99 @@ export const AcpRegistryDriver: ProviderDriver + options?.fallbackToAcceptedModels === true && target.enabled && target.installed + ? Ref.get(acceptedCatalog).pipe( + Effect.map((accepted) => + accepted.models.length > 0 ? { ...target, models: accepted.models } : target, + ), + ) + : Effect.succeed(target); if (Option.isNone(runtimeCoordinator)) { - return withAcpRegistryLearnedModelOptions(provider, yield* learnedModelOptions.get); + const withFallback = yield* applyAcceptedModelsFallback(provider); + if ( + !withFallback.enabled || + !withFallback.installed || + options?.applyLiveModels === false + ) { + return withFallback; + } + const accepted = yield* Ref.get(acceptedCatalog); + return applyDiskLearnedModelOptions(withFallback, yield* learnedModelOptions.get, { + reasoningDisabledModelSlugs: accepted.reasoningDisabledModelSlugs, + }); } - const coordinator = runtimeCoordinator.value; - const withCommands = applyAcpRegistryAvailableCommands( - provider, - yield* coordinator.getAvailableCommands(instanceId), - ); - const configuration = yield* coordinator.getLiveConfiguration(instanceId); - const withConfiguration = Option.isSome(configuration) - ? yield* applyLiveConfiguration(withCommands, configuration.value) - : withAcpRegistryLearnedModelOptions(withCommands, yield* learnedModelOptions.get); - return applyAcpRegistryUrlAuthAction( - withConfiguration, - yield* coordinator.getUrlAuthAction(instanceId), + 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 accepted = yield* Ref.get(acceptedCatalog); + const appliedCatalogRev = yield* Ref.get(lastAppliedLiveCatalogRevision); + const appliedRev = yield* Ref.get(lastAppliedLiveRevision); + const steps: Array = + []; + if ( + Option.isSome(liveConfiguration.catalog) && + liveConfiguration.catalog.value.revision > liveConfiguration.clearedThroughRevision && + liveConfiguration.catalog.value.revision > appliedCatalogRev + ) { + steps.push(liveConfiguration.catalog.value); + } + const hasNewCatalogStep = steps.length > 0; + if (!(yield* Ref.get(signedOutState)).signedOut) { + 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); + } + } + } + if (steps.length === 0) { + withConfiguration = applyDiskLearnedModelOptions( + withConfiguration, + yield* learnedModelOptions.get, + { + reasoningDisabledModelSlugs: accepted.reasoningDisabledModelSlugs, + }, + ); + } else { + for (const step of steps) { + withConfiguration = yield* applyLiveConfigurationStep( + withConfiguration, + step.configuration, + { + preserveStatus: options?.preserveStatus, + revision: step.revision, + }, + ); + } + } + 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); @@ -773,7 +2185,14 @@ export const AcpRegistryDriver: ProviderDriver + liveSnapshotSemaphore.withPermit( + withLiveRuntimeState(provider, { + recordLiveRevision: true, + fallbackToAcceptedModels: true, + }), + ), + ), ); const modelsToDiscover = Effect.fn("AcpRegistryDriver.modelsToDiscover")(function* ( provider: ServerProvider, @@ -788,25 +2207,24 @@ export const AcpRegistryDriver: ProviderDriver Effect.Effect) => - checkAcpRegistryProviderStatus( + const enrichProvider = ( + publishProbed: (detailed: DetailedAcpRegistryProviderStatus) => Effect.Effect, + isProbeCurrent: Effect.Effect, + onDiscovered: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + ) => + checkAcpRegistryProviderStatusDetailed( { ...readinessInput, cwd: host.paths.cwd, modelDiscovery: { // Publish what the probe found first; discovery only adds options to it. - onProbed: (provider) => - modelsToDiscover(provider).pipe( - Effect.tap((modelIds) => - modelIds.length === 0 ? Effect.void : publishProbed(provider), - ), - ), - onDiscovered: (configuration) => { - const discovered = acpRegistryCurrentModelOptions(configuration); - return discovered === undefined - ? Effect.void - : learnedModelOptions.learn(discovered.modelId, discovered.options, "discovered"); - }, + onProbed: Effect.fn("AcpRegistryDriver.onProbed")(function* (detailed) { + if (!(yield* isProbeCurrent)) return []; + const modelIds = yield* modelsToDiscover(detailed.provider); + if (modelIds.length === 0) return []; + return (yield* publishProbed(detailed)) ? modelIds : []; + }), + onDiscovered, }, }, probeAcpRegistryConfiguration, @@ -821,63 +2239,99 @@ export const AcpRegistryDriver: ProviderDriver ({ generation: current.generation + 1, entry: null, })); + interface EnrichedAcpRegistryResult extends DetailedAcpRegistryProviderStatus { + readonly generation: number; + readonly fresh: boolean; + readonly probeStartCatalogRevision: number; + readonly probeStartSignedOutEpoch: number; + } const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* ( baseSnapshot: ServerProvider, - publish: (enriched: { - readonly provider: ServerProvider; - readonly generation: number; - }) => Effect.Effect, - ) { - const now = yield* Clock.currentTimeMillis; - const cacheState = yield* Ref.get(enrichmentCache); - const cached = cacheState.entry; - if ( - cached !== null && - isAcpRegistryCacheValid( - cached, - baseSnapshot.version, - effectiveConfig.source === "local", - now, - ) - ) { + publishProgress: (enriched: EnrichedAcpRegistryResult) => Effect.Effect, + ): Effect.fn.Return { + const startState = yield* liveSnapshotSemaphore.withPermit( + Effect.gen(function* () { + const cacheState = yield* Ref.get(enrichmentCache); + const cached = cacheState.entry; + if ( + cached !== null && + isAcpRegistryCacheValid( + cached, + baseSnapshot.version, + effectiveConfig.source === "local", + yield* Clock.currentTimeMillis, + ) + ) { + return { + kind: "cached" as const, + cacheState, + cached, + }; + } + const probeStartSignedOutEpoch = (yield* Ref.get(signedOutState)).epoch; + const probeStartLive = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId) + : AcpRegistryRuntimeCoordinator.EMPTY_LIVE_CONFIGURATION_SNAPSHOT; + return { + kind: "fresh" as const, + cacheState, + probeStartSignedOutEpoch, + probeStartLive, + }; + }), + ); + if (startState.kind === "cached") { return { - provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt }, - generation: cacheState.generation, + provider: { ...startState.cached.provider, checkedAt: baseSnapshot.checkedAt }, + generation: startState.cacheState.generation, + fresh: false, + probeStartCatalogRevision: 0, + probeStartSignedOutEpoch: 0, + probedModels: [], + probedConfigOptions: [], + probedModelCount: 0, + probedModelsFromModelSelect: false, + probedCappedTailIsOverflow: false, + probedCurrentModelId: null, + probedModelOptionIds: EMPTY_SLUG_SET, + reasoningDisabledModelSlugs: EMPTY_SLUG_SET, }; } - const remember = Effect.fn("AcpRegistryDriver.rememberEnrichment")(function* ( - enriched: ServerProvider, - ) { - if (effectiveConfig.source === "local" && enriched.status === "ready") { - yield* Ref.set(reportedLocalVersion, enriched.version); - } - if (enriched.status === "ready") { - const completedAt = yield* Clock.currentTimeMillis; - yield* Ref.update(enrichmentCache, (current) => - current.generation === cacheState.generation - ? { - ...current, - entry: { - provider: enriched, - expiresAt: completedAt + acpRegistryProbeTtlMs(enriched), - }, - } - : current, - ); - } + const toFreshResult = ( + detailed: DetailedAcpRegistryProviderStatus, + ): EnrichedAcpRegistryResult => ({ + ...detailed, + generation: startState.cacheState.generation, + fresh: true, + probeStartCatalogRevision: startState.probeStartLive.catalogRevision, + probeStartSignedOutEpoch: startState.probeStartSignedOutEpoch, }); - const enriched = yield* enrichProvider((provider) => - remember(provider).pipe( - Effect.andThen(publish({ provider, generation: cacheState.generation })), - ), + const isProbeCurrent = Ref.get(enrichmentCache).pipe( + Effect.map((current) => current.generation === startState.cacheState.generation), + ); + const enriched = yield* enrichProvider( + (detailed) => publishProgress(toFreshResult(detailed)), + isProbeCurrent, + (configuration) => + Effect.gen(function* () { + if ((yield* Ref.get(enrichmentCache)).generation !== startState.cacheState.generation) { + return; + } + const discovered = acpRegistryCurrentModelOptions(configuration); + if (discovered !== undefined) { + yield* learnedModelOptions.learn( + discovered.modelId, + discovered.options, + "discovered", + ); + } + }), ); - yield* remember(enriched); - return { provider: enriched, generation: cacheState.generation }; + return toFreshResult(enriched); }); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< @@ -896,23 +2350,209 @@ export const AcpRegistryDriver: ProviderDriver - liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, - ), + fresh, + probeStartCatalogRevision, + probeStartSignedOutEpoch, + probedModels, + probedConfigOptions, + probedModelCount, + probedModelsFromModelSelect, + probedCappedTailIsOverflow, + probedCurrentModelId, + probedModelOptionIds, + reasoningDisabledModelSlugs, + }: EnrichedAcpRegistryResult) => + 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; + const reopenedSignedOut = + fresh && + provider.status === "ready" && + (yield* Ref.modify(signedOutState, (state) => + 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) { + yield* getSnapshot.pipe( + Effect.flatMap((currentSnapshot) => withLiveRuntimeState(currentSnapshot)), + Effect.flatMap(publishSnapshot), + ); + } + return false; + } + let resolved = provider; + if (!fresh) { + if (current.entry === null) return false; + const accepted = yield* Ref.get(acceptedCatalog); + resolved = { + ...current.entry.provider, + checkedAt: provider.checkedAt, + ...(accepted.probeOptions === null && + accepted.models.length > 0 && + current.entry.provider.enabled && + current.entry.provider.installed + ? { models: accepted.models } + : {}), + }; + } + if (fresh && provider.status === "ready") { + if (provider.installed) yield* learnedModelOptions.setVersion(provider.version); + const accepted = yield* Ref.get(acceptedCatalog); + const liveCatalog = Option.filter( + Option.map(liveSnapshot.catalog, (entry) => entry.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, + }); + const probeOptionSchema: AcpRegistryProbeOptionSchema = { + models: probedModels, + currentModelId: probedCurrentModelId, + configOptions: probedConfigOptions, + modelOptionIds: probedModelOptionIds, + cappedTailIsOverflow: probedCappedTailIsOverflow, + }; + // A fresh non-provisional probe supersedes any live session catalog observed before it started. + const clearedThrough = probeSupersedesLiveCatalog + ? Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + { + catalogRevision: probeStartCatalogRevision, + retain: (live) => + retainAcpRegistryLiveOptionsAfterProbe(live, probeOptionSchema), + }, + ) + : Option.some(0) + : Option.none(); + if (probeSupersedesLiveCatalog && Option.isNone(clearedThrough)) return false; + if (effectiveConfig.source === "local") { + yield* Ref.set(reportedLocalVersion, provider.version); + } + if (!probeSupersedesLiveCatalog && 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 = Option.isSome(clearedThrough) + ? updateAcpRegistryLearnedModelsFromProbe(learned, provider.models, { + currentModelId: probedCurrentModelId, + modelOptionIds: probedModelOptionIds, + reasoningDisabledModelSlugs, + }) + : learned; + return [merged, nextLearned] as const; + }); + if ( + Option.isSome(clearedThrough) && + probedCurrentModelId !== null && + probedModelCount > 0 + ) { + const probedCurrentOptions = probedConfigOptions.filter((descriptor) => + probedModelOptionIds.has(descriptor.id), + ); + yield* learnedModelOptions.learn( + probedCurrentModelId, + probedCurrentOptions, + "live", + ); + } + resolved = applyDiskLearnedModelOptions( + models === provider.models ? provider : { ...provider, models }, + yield* learnedModelOptions.get, + { + currentModelId: probedCurrentModelId, + reasoningDisabledModelSlugs, + }, + ); + } + if (Option.isSome(clearedThrough)) { + const supersededLiveSession = + clearedThrough.value > (yield* Ref.get(liveSessionResetRevision)); + yield* resetAppliedLiveRevisions; + 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); + 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, + expiresAt: completedAt + acpRegistryProbeTtlMs(provider), + }, + })); + yield* publishSnapshot(published); + return true; + } + const isUnauthenticated = fresh && resolved.auth.status === "unauthenticated"; + if (isUnauthenticated) { + const clearedForSignOut = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision(instanceId, { + catalogRevision: probeStartCatalogRevision, + }) + : Option.some(0); + if (Option.isNone(clearedForSignOut)) return false; + yield* Ref.set(enrichmentCache, { + generation: current.generation + 1, + entry: null, + }); + yield* clearLearnedModels; + yield* clearAcceptedCatalog; + yield* Ref.set(liveSessionResetRevision, clearedForSignOut.value); + yield* markSignedOut; + yield* resetAppliedLiveRevisions; + } + const preserveTransientFailure = + fresh && resolved.status !== "ready" && !isUnauthenticated; + yield* withLiveRuntimeState(resolved, { + applyLiveModels: !isUnauthenticated, + fallbackToAcceptedModels: preserveTransientFailure, + preserveStatus: preserveTransientFailure, + }).pipe(Effect.flatMap(publishSnapshot)); + return true; + }), ), ); - const enrichment = enrichProviderCached(snapshot, publishEnriched); + const enrichment = enrichProviderCached(snapshot, commitEnrichment); const publishEnrichment = ( Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( @@ -926,7 +2566,7 @@ export const AcpRegistryDriver: ProviderDriver Effect.void, - onSome: publishEnriched, + onSome: (enriched) => commitEnrichment(enriched).pipe(Effect.asVoid), }), ), ); @@ -947,29 +2587,49 @@ 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, revision) => + liveSnapshotSemaphore.withPermit( + Effect.uninterruptible( + Effect.gen(function* () { + const clearedThroughRevision = + yield* runtimeCoordinator.value.getLiveConfigurationClearedThroughRevision( + instanceId, + ); + const appliedRevision = yield* Ref.get(lastAppliedLiveRevision); + if (revision <= clearedThroughRevision || revision < appliedRevision) { + return; + } + const rawCurrent = yield* getSnapshot; + if ( + !rawCurrent.installed || + ((yield* Ref.get(signedOutState)).signedOut && + configuration.models.length === 0) + ) { + return; + } + const accepted = yield* Ref.get(acceptedCatalog); + // 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, + }); + yield* publishSnapshot(next); + }), ), ), - Effect.flatMap(publishSnapshot), - ), + { afterRevision }, ), + ), ); const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( instanceId, @@ -1028,27 +2688,71 @@ export const AcpRegistryDriver: ProviderDriver + liveSnapshotSemaphore.withPermit( + Effect.uninterruptible( + (options?.clearConfirmedAuthentication === true + ? confirmedAuthentication.set(false) + : Effect.void + ).pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen(clearLearnedModels), + Effect.andThen(clearAcceptedCatalog), + Effect.andThen(options?.markSignedOut === true ? markSignedOut : advanceSignedOutEpoch), + Effect.andThen(resetAppliedLiveRevisions), + Effect.andThen( + Option.isSome(runtimeCoordinator) + ? (options?.clearLiveConfiguration === false + ? Effect.void + : runtimeCoordinator.value + .clearLiveConfiguration(instanceId) + .pipe( + Effect.flatMap((clearedThrough) => + Ref.set(liveSessionResetRevision, clearedThrough), + ), + ) + ).pipe( + Effect.andThen( + options?.clearCommands === true + ? runtimeCoordinator.value.clearAvailableCommands(instanceId) + : Effect.void, + ), + ) + : Effect.void, + ), + ), + ), + ); + const clearLiveState = clearCachedState({ + clearCommands: true, + clearConfirmedAuthentication: true, + }); + const clearSignedOutState = clearCachedState({ + clearCommands: true, + clearConfirmedAuthentication: true, + markSignedOut: true, + }); const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({ instanceId, settings: effectiveConfig, cwd: host.paths.cwd, environment: processEnvironment, onChanged: (authenticated) => - confirmedAuthentication - .set(authenticated) - .pipe( - Effect.andThen(authenticated ? Effect.void : clearLiveState), - Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)), - 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), @@ -1057,9 +2761,7 @@ export const AcpRegistryDriver: ProviderDriver controller.refreshMethods ?? Effect.void)), }, - invalidateCaches: (Option.isSome(runtimeCoordinator) - ? runtimeCoordinator.value.clearLiveConfiguration(instanceId) - : Effect.void - ).pipe( - Effect.andThen(clearLearnedModels), - Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)), - ), + // 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: { @@ -1128,7 +2826,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe(Effect.tap(() => clearCachedState())), disableProvider: ({ cwd, providerId }) => provideAcpManagementServices( disableAcpRegistryProvider({ @@ -1138,7 +2836,7 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe(Effect.tap(() => clearCachedState())), logout: (cwd) => { const logout = logoutAcpRegistry({ instanceId, @@ -1149,24 +2847,7 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), - Effect.tap(() => - liveSnapshotSemaphore.withPermit( - invalidateEnrichmentCache.pipe( - Effect.andThen( - Option.isSome(runtimeCoordinator) - ? Effect.all( - [ - runtimeCoordinator.value.clearAvailableCommands(instanceId), - runtimeCoordinator.value.clearLiveConfiguration(instanceId), - ], - { concurrency: "unbounded", discard: true }, - ) - : Effect.void, - ), - ), - ), - ), + Effect.tap(() => clearSignedOutState), ); return Option.isSome(runtimeCoordinator) ? logout.pipe( diff --git a/packages/provider-acp-registry/src/server/learnedModelOptions.ts b/packages/provider-acp-registry/src/server/learnedModelOptions.ts index 2677a5ea3b4e6..2c318dbda880a 100644 --- a/packages/provider-acp-registry/src/server/learnedModelOptions.ts +++ b/packages/provider-acp-registry/src/server/learnedModelOptions.ts @@ -164,19 +164,42 @@ export function acpRegistryCurrentModelOptions( }; } +const EMPTY_SLUG_SET: ReadonlySet = new Set(); + /** Adds learned options to models that are not the session's own and lack them. */ export function withAcpRegistryLearnedModelOptions( provider: ServerProvider, learned: AcpRegistryLearnedModelOptions, + options?: { + readonly currentModelId?: string | null; + readonly skipModelSlugs?: ReadonlySet; + readonly reasoningDisabledModelSlugs?: ReadonlySet; + }, ): ServerProvider { if (learned.size === 0) return provider; + const currentModelId = options?.currentModelId ?? null; + const skipModelSlugs = options?.skipModelSlugs ?? EMPTY_SLUG_SET; + const reasoningDisabledModelSlugs = options?.reasoningDisabledModelSlugs ?? EMPTY_SLUG_SET; let changed = false; const models = provider.models.map((model): ServerProviderModel => { - const options = learned.get(model.slug); - if (model.isCustom || model.isDefault === true || options === undefined) return model; + const learnedOptions = learned.get(model.slug); + if ( + model.isCustom || + model.isDefault === true || + (currentModelId !== null && model.slug === currentModelId) || + skipModelSlugs.has(model.slug) || + learnedOptions === undefined + ) { + return model; + } const current = model.capabilities?.optionDescriptors ?? []; + const isReasoningDisabled = reasoningDisabledModelSlugs.has(model.slug); // Levels the model advertises itself (`_meta`) keep their place. - const missing = options.filter((option) => !current.some(({ id }) => id === option.id)); + const missing = learnedOptions.filter( + (option) => + !current.some(({ id }) => id === option.id) && + (!isReasoningDisabled || option.type !== "select" || option.role !== "reasoning"), + ); if (missing.length === 0) return model; changed = true; return { diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index ddce17eb3b0a8..7d885e569e0b3 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -42,7 +42,7 @@ import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator. import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; const MAX_AUTH_METHODS = 32; -const MAX_MODELS = 256; +export const ACP_REGISTRY_MAX_MODELS = 256; const MAX_ID_LENGTH = 128; const MAX_NAME_LENGTH = 160; const MAX_DESCRIPTION_LENGTH = 1_024; @@ -72,9 +72,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 && @@ -121,17 +121,21 @@ function normalizeModels( const seen = new Set(); 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 +220,65 @@ 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; + // Set on retained post-probe overrides so probe-only options stay untouched. + readonly partialOptions?: boolean; + // Set when a full live update for a non-probe model was retained as partial across a superseding + // probe so replay drops omitted learned options for that model while keeping probe descriptors. + readonly replaceModelOptions?: 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> + >; + // Stable prefix key (first ACP_REGISTRY_MAX_MODELS - 1 models) for capped overflow updates. + readonly cappedPrefixKey?: string; + // 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 normalizeAcpRegistryLiveConfiguration( +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 { + 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; +} + +/** + * 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, -): AcpRegistryLiveConfiguration { +): PreparedAcpRegistryLiveConfiguration { const modelOption = findModelConfigOption(configOptions); const currentModelId = modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId; @@ -245,32 +301,98 @@ export function normalizeAcpRegistryLiveConfiguration( const effortOption = configOptions.find((option) => option.category === "thought_level") ?? configOptions.find(isAcpThoughtLevelOption); - const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => { - const reasoningEffort = advertisedReasoningEffort( - effortOption, - modelState?.availableModels.find((info) => info.modelId === model.id)?._meta, - ); + const metaByModelId = new Map(); + for (const info of modelState?.availableModels ?? []) { + if (!metaByModelId.has(info.modelId)) { + metaByModelId.set(info.modelId, info._meta); + } + } + const attachReasoning = (model: AcpRegistryProbeModel): AcpRegistryProbeModel => { + const reasoningEffort = advertisedReasoningEffort(effortOption, metaByModelId.get(model.id)); return reasoningEffort === undefined ? model : { ...model, reasoningEffort }; - }); - const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }); - const modelOptionIds = new Set( + }; + 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 cappedLastModel = + 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) => + !stripCurrentReasoning || descriptor.type !== "select" || descriptor.role !== "reasoning", + ); + 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; + const advertisedReasoning = extractAcpRegistryAdvertisedReasoning( + advertisedModels, + resolvedCurrentModelId, + ); + const catalogKey = JSON.stringify([ + hasModelSelect, + baseModels.map(({ id, name, description }) => [id, name, description]), + ]); + const cappedPrefixKey = + cappedLastModel === undefined + ? undefined + : cappedAcpRegistryModelPrefixKey(baseModels.map((model) => model.id)); return { - models, - currentModelId: models.some((model) => model.id === boundedCurrentModelId) - ? boundedCurrentModelId - : null, - configOptions: descriptors, - modelOptionIds: descriptors - .filter((descriptor) => modelOptionIds.has(descriptor.id)) - .map((descriptor) => descriptor.id), - modelsFromModelSelect: modelOption !== undefined, + // 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 { + models: includeCatalog ? advertisedModels : [], + currentModelId: resolvedCurrentModelId, + configOptions: descriptors, + modelOptionIds, + modelsFromModelSelect: includeCatalog && hasModelSelect, + ...(!includeCatalog && advertisedReasoning !== undefined ? { advertisedReasoning } : {}), + ...(cappedLastModel !== undefined && cappedPrefixKey !== undefined + ? { + cappedPrefixKey, + cappedLastModel, + ...(cappedTailIsOverflow ? { cappedTailIsOverflow: true } : {}), + } + : {}), + }; + }, }; } +export function normalizeAcpRegistryLiveConfiguration( + configOptions: ReadonlyArray, + modeState?: Parameters[0]["modeState"], + modelState?: EffectAcpSchema.SessionModelState | null, +): AcpRegistryLiveConfiguration { + return prepareAcpRegistryLiveConfiguration( + configOptions, + modeState, + modelState, + ).toLiveConfiguration(); +} + const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({ slashCommands: [], skills: [], @@ -352,7 +474,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 }), }); } @@ -405,6 +532,8 @@ export interface AcpRegistryConfigurationProbeResult { readonly probe: AcpRegistryProbeResult; readonly slashCommands: ReadonlyArray; readonly skills: ReadonlyArray; + readonly modelsFromModelSelect?: boolean; + readonly cappedTailIsOverflow?: boolean; } export type AcpRegistryConfigurationProbe = ( @@ -445,8 +574,9 @@ const discoverAcpRegistryModelOptions = Effect.fn("AcpRegistryProbe.discoverMode ? discovery.onDiscovered(configuration) : Effect.void; }), - // A model the agent refuses keeps no options; the rest still count. + // A model the agent refuses or answers unexpectedly keeps no options; the rest still count. Effect.ignore, + Effect.catchDefect(() => Effect.void), ), { discard: true }, ).pipe(Effect.timeoutOption(MODEL_DISCOVERY_BATCH_TIMEOUT)); @@ -463,7 +593,11 @@ const discoverAcpRegistryModelOptions = Effect.fn("AcpRegistryProbe.discoverMode ? Effect.void : runtime .setConfigOption(modelOption.id, originalModelId, { resendCurrentValue: true }) - .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore), + .pipe( + Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), + Effect.ignore, + Effect.catchDefect(() => Effect.void), + ), ), ), ); @@ -712,6 +846,8 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: session.commands.slashCommands, skills: session.commands.skills, + modelsFromModelSelect: session.liveConfiguration.modelsFromModelSelect === true, + cappedTailIsOverflow: session.liveConfiguration.cappedTailIsOverflow === true, }; // Runs in the probe session before it is deleted, outside the setup deadline. if (input.modelDiscovery !== undefined) { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d4d8b0b54505b..bc5e4d4f5fd9f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -478,7 +478,8 @@ export interface AcpAdapterV2Flavor { configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, modelState: EffectAcpSchema.SessionModelState | null | undefined, - ) => Effect.Effect; + options?: { readonly lastCatalogKey: string | null }, + ) => Effect.Effect; readonly onUrlElicitation?: (input: { readonly elicitationId: string; readonly url: string; @@ -2351,6 +2352,42 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); + // 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; + }>({ 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* (targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { + 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 nextKey = yield* onSessionConfigurationUpdate( + configOptions, + modeState, + modelState, + { lastCatalogKey: key }, + ); + if (typeof nextKey === "string") { + yield* Ref.update(lastPublishedCatalogKey, (current) => + current.epoch === epoch ? { epoch, key: nextKey } : current, + ); + } + }), + ); + }, + ); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { @@ -2370,6 +2407,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* Ref.set(activeSessionSetup, setup); + yield* resetPublishedCatalogKey; }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); @@ -7290,13 +7328,7 @@ 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(runtime); } const normalized = flavor.normalizeSessionUpdate?.(notification) ?? notification; // Turn projection misses compactions that finish while idle or after settlement. @@ -7412,6 +7444,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } 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); @@ -7426,13 +7459,7 @@ 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(targetRuntime); }); const wireAcpRuntimeHandlers = Effect.fnUntraced(function* ( @@ -8571,13 +8598,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* validateModelSelection(modelSelection); yield* Ref.set(configuredModes, yield* readModes); 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(runtime); }); yield* configureSession( @@ -9351,6 +9372,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); yield* Ref.set(activeSessionSetup, null); + yield* resetPublishedCatalogKey; yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again.