diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx index 8b53d81969264..bd7a0a7ff86bc 100644 --- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx @@ -354,7 +354,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm return; const result = await refreshProviders({ environmentId, - input: { reloadSecrets: true }, + input: { refreshModels: true, reloadSecrets: true }, }); if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result); setNotice(gt("Provider status refreshed.")); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4e80e4968ba65..ef5eb91eef4ba 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -5426,7 +5426,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, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..246dc7b5e71c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1009,16 +1009,16 @@ describe("AcpRegistryAdapterV2", () => { })), [ { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["hermes", "auto", "default"], current: "hermes" }, - { models: ["hermes", "auto", "default"], current: null }, - { models: ["hermes", "auto", "default"], current: "auto" }, - { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["auto"], current: null }, + { models: [], current: "hermes" }, + { models: [], current: null }, + { models: [], current: "auto" }, + { models: [], current: "default" }, { models: ["auto"], current: null }, + { models: [], current: null }, { models: ["default"], current: null }, - { models: ["default"], current: null }, + { models: [], current: null }, { models: ["hermes", "auto", "default"], current: "default" }, - { models: ["hermes", "auto", "default"], current: "hermes" }, + { models: [], current: "hermes" }, ], ); }).pipe(Effect.provide(layerTest)), diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 00ed26d599222..1e98d1fa4941e 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -363,6 +363,8 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -424,6 +426,8 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -493,6 +497,8 @@ await import(pathToFileURL(agentPath).href); const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -544,6 +550,8 @@ await import(pathToFileURL(agentPath).href); const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index aec3e2a188eb1..23e82bb7e2e7c 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -51,6 +51,10 @@ version published by the Registry. Their commands are available in a new server sign-in and direct use. Removing an agent's last provider instance removes T3-managed binary files but keeps package installs. To use an existing local binary, set **Executable override** explicitly. +T3 Code checks the Registry for new versions in the background and installs them for T3-managed +agents on the next provider check; a check is skipped while that agent is starting a session. +Refreshing providers in Settings checks the Registry right away. + ## Signing in Open the agent's account section in **Settings → Providers** on web or desktop. Choose diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index bec80c06ddd39..be6f655a94e25 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -25,6 +25,22 @@ interface AvailableCommandsUpdate { interface LiveConfigurationUpdate { readonly instanceId: ProviderInstanceId; readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +interface LiveConfigurationEntry { + readonly configuration: AcpRegistryLiveConfiguration; + readonly revision: number; +} + +interface LiveConfigurationState { + readonly nextRevision: number; + readonly entries: ReadonlyMap; +} + +export interface AcpRegistryLiveConfigurationSnapshot { + readonly configuration: Option.Option; + readonly revision: number; } interface UrlAuthActionUpdate { @@ -67,6 +83,10 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< onUpdate: (commands: AcpRegistryAvailableCommands) => Effect.Effect, ) => Effect.Effect; readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; + readonly clearLiveConfigurationIfRevision: ( + instanceId: ProviderInstanceId, + revision: number, + ) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, @@ -74,9 +94,16 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; + readonly getLiveConfigurationWithRevision: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; readonly watchLiveConfiguration: ( instanceId: ProviderInstanceId, - onUpdate: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + onUpdate: ( + configuration: AcpRegistryLiveConfiguration, + revision: number, + ) => Effect.Effect, + options?: { readonly afterRevision?: number }, ) => Effect.Effect; readonly requestUrlAuthentication: ( instanceId: ProviderInstanceId, @@ -103,9 +130,10 @@ const make = Effect.gen(function* () { new Map(), ); const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurationByInstance = yield* Ref.make( - new Map(), - ); + const liveConfigurations = yield* Ref.make({ + nextRevision: 0, + entries: new Map(), + }); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -206,43 +234,79 @@ const make = Effect.gen(function* () { const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = (instanceId) => - Ref.update(liveConfigurationByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; + Ref.update(liveConfigurations, (current) => { + if (!current.entries.has(instanceId)) return current; + const entries = new Map(current.entries); + entries.delete(instanceId); + return { ...current, entries }; }); + const clearLiveConfigurationIfRevision: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfigurationIfRevision"] = + Effect.fn("AcpRegistryRuntimeCoordinator.clearLiveConfigurationIfRevision")( + function* (instanceId, revision) { + return yield* Ref.modify(liveConfigurations, (current) => { + const entry = current.entries.get(instanceId); + if (entry === undefined) return [true, current] as const; + if (entry.revision !== revision) return [false, current] as const; + const entries = new Map(current.entries); + entries.delete(instanceId); + return [true, { ...current, entries }] as const; + }); + }, + ); + const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = (instanceId, configuration) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, configuration), - ).pipe( - Effect.andThen( + Ref.modify(liveConfigurations, (current) => { + const revision = current.nextRevision + 1; + const entries = new Map(current.entries); + entries.set(instanceId, { configuration, revision }); + return [revision, { nextRevision: revision, entries }] as const; + }).pipe( + Effect.flatMap((revision) => PubSub.publish(liveConfigurationUpdates, { instanceId, configuration, + revision, }), ), Effect.asVoid, ); + const getLiveConfigurationWithRevision: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfigurationWithRevision"] = + Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfigurationWithRevision")( + function* (instanceId) { + const entry = (yield* Ref.get(liveConfigurations)).entries.get(instanceId); + return entry === undefined + ? { configuration: Option.none(), revision: 0 } + : { configuration: Option.some(entry.configuration), revision: entry.revision }; + }, + ); + const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(liveConfigurationByInstance)).get(instanceId)); + return (yield* getLiveConfigurationWithRevision(instanceId)).configuration; }); const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = - (instanceId, onUpdate) => + (instanceId, onUpdate, options) => Effect.scoped( Effect.gen(function* () { const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); - const current = yield* getLiveConfiguration(instanceId); - if (Option.isSome(current)) { - yield* onUpdate(current.value); + let lastDelivered = options?.afterRevision ?? 0; + const current = yield* getLiveConfigurationWithRevision(instanceId); + if (Option.isSome(current.configuration) && current.revision > lastDelivered) { + lastDelivered = current.revision; + yield* onUpdate(current.configuration.value, current.revision); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.configuration)), + Stream.filter( + (update) => update.instanceId === instanceId && update.revision > lastDelivered, + ), + Stream.runForEach((update) => { + lastDelivered = update.revision; + return onUpdate(update.configuration, update.revision); + }), ); }), ); @@ -344,8 +408,10 @@ const make = Effect.gen(function* () { getAvailableCommands, watchAvailableCommands, clearLiveConfiguration, + clearLiveConfigurationIfRevision, publishLiveConfiguration, getLiveConfiguration, + getLiveConfigurationWithRevision, watchLiveConfiguration, requestUrlAuthentication, acceptUrlAuthentication, diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 772ad1c265c2b..f7507b68dc2e3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -2226,6 +2226,99 @@ describe("AcpRegistrySupport", () => { ), ); }); + + it.effect("refreshes stale disk indexes with max-age, offline backoff, and invalidation", () => { + const v1 = makeAgent({ npx: { package: "example-agent@1.0.0" } }); + const v2 = { + ...makeAgent({ npx: { package: "example-agent@2.0.0" } }), + version: "2.0.0", + }; + let currentAgent = v2; + let failNetwork = false; + let requests = 0; + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-refresh-index-", + }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString(`${cacheDir}/acp-registry/registry.json`, makeRegistry(v1)); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.3", + }); + expect(requests).toBe(0); + + // Cold disk cache has no network timestamp, so refreshIndex fetches v2. + expect(yield* resolver.refreshIndex({ maxAgeMs: 60_000, failureBackoffMs: 10_000 })).toBe( + true, + ); + expect(requests).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "2.0.0", + }); + + // Within maxAgeMs, no network call happens. + expect(yield* resolver.refreshIndex({ maxAgeMs: 60_000, failureBackoffMs: 10_000 })).toBe( + false, + ); + expect(requests).toBe(1); + + // After invalidateIndex, an offline failure preserves in-memory v2 and backs off. + yield* resolver.invalidateIndex(); + failNetwork = true; + expect(yield* resolver.refreshIndex({ maxAgeMs: 60_000, failureBackoffMs: 10_000 })).toBe( + false, + ); + expect(requests).toBe(2); + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "2.0.0", + }); + + // Within failureBackoffMs, repeated background refreshes do not hammer the network. + expect(yield* resolver.refreshIndex({ maxAgeMs: 60_000, failureBackoffMs: 10_000 })).toBe( + false, + ); + expect(requests).toBe(2); + + // Explicit invalidateIndex clears backoff so the next refresh retries immediately. + failNetwork = false; + currentAgent = { + ...makeAgent({ npx: { package: "example-agent@2.0.0", args: ["--flag"] } }), + version: "2.0.0", + }; + yield* resolver.invalidateIndex(); + expect(yield* resolver.refreshIndex({ maxAgeMs: 60_000, failureBackoffMs: 10_000 })).toBe( + true, + ); + expect(requests).toBe(3); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + if (failNetwork) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 503 })), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(currentAgent))), + ); + }), + ), + ); + }); }); describe("acpRegistryManagedBinaryDirectories", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 4ce54abc75b5a..417fd79615016 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -192,6 +192,7 @@ export interface AcpRegistryIndex { const decodeRegistryIndexEnvelope = Schema.decodeUnknownEffect(AcpRegistryIndexEnvelope); const decodeRegistryAgent = Schema.decodeUnknownOption(AcpRegistryAgent); const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); +const encodeUnknownJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const decodeNpmPackageManifest = Schema.decodeUnknownEffect( Schema.fromJsonString(NpmPackageManifest), ); @@ -513,6 +514,7 @@ export type AcpRegistryInspection = readonly agentId: string; readonly version: string | null; readonly distribution: AcpRegistryDistributionKind | "local"; + readonly launchIdentity?: string; readonly documentationUrl?: string; }; @@ -525,6 +527,11 @@ export class AcpRegistryCatalog extends Context.Service< readonly prepare: ( input: AcpRegistryPrepareInput, ) => Effect.Effect; + readonly refreshIndex: (options?: { + readonly maxAgeMs?: number; + readonly failureBackoffMs?: number; + }) => Effect.Effect; + readonly invalidateIndex: () => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, environment?: NodeJS.ProcessEnv, @@ -575,6 +582,31 @@ const INSTALL_LOCK_RETRY_DELAY = "100 millis"; const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; +function registryLaunchIdentity(input: { + readonly version: string | null; + readonly distribution: ResolvedAcpRegistryDistribution; + readonly commandOverride?: string; +}): string { + const envEntries = Object.entries(input.distribution.env).toSorted(([left], [right]) => + compareText(left, right), + ); + return JSON.stringify({ + version: input.version, + kind: input.distribution.kind, + ...(input.commandOverride ? { commandOverride: input.commandOverride } : {}), + ...(input.distribution.packageName ? { packageName: input.distribution.packageName } : {}), + ...(input.distribution.binaryTarget + ? { + archive: input.distribution.binaryTarget.archive, + cmd: input.distribution.binaryTarget.cmd, + sha256: input.distribution.binaryTarget.sha256 ?? null, + } + : {}), + args: input.distribution.args, + env: envEntries, + }); +} + function isAlreadyExists(error: PlatformError.PlatformError): boolean { return error.reason._tag === "AlreadyExists"; } @@ -694,10 +726,25 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ? packageInstallRoot(agent, distribution) : path.join(packageInstallRoot(agent, distribution), "bin"); const packageReceiptsDirectory = path.join(registryDirectory, "package-installs"); - const registryRef = yield* Ref.make(undefined); - // When the network last served registryRef; unset while it holds the disk cache. - const registryFetchedAtMs = yield* Ref.make(undefined); - const registryRevision = yield* Ref.make(0); + interface RegistryCacheState { + readonly index: AcpRegistryIndex | undefined; + // Unset while holding a cold disk cache, after a fallback, or after invalidateIndex. + readonly fetchedAtMs: number | undefined; + readonly failedAtMs: number | undefined; + readonly lastFailure: AcpRegistryError | undefined; + readonly fetchRevision: number; + readonly attemptRevision: number; + readonly invalidationGeneration: number; + } + const registryState = yield* Ref.make({ + index: undefined, + fetchedAtMs: undefined, + failedAtMs: undefined, + lastFailure: undefined, + fetchRevision: 0, + attemptRevision: 0, + invalidationGeneration: 0, + }); const registrySemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. const installPermits = new Map(); @@ -951,59 +998,187 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return registry; }); - const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* () { - const observedRevision = yield* Ref.get(registryRevision); + const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { + readonly maxAgeMs?: number; + readonly failureBackoffMs?: number; + readonly observedFetchRevision?: number; + readonly observedAttemptRevision?: number; + }) { + const initial = yield* Ref.get(registryState); + const startFetchRevision = options?.observedFetchRevision ?? initial.fetchRevision; + const startAttemptRevision = options?.observedAttemptRevision ?? initial.attemptRevision; + const maxAgeMs = options?.maxAgeMs; + const failureBackoffMs = options?.failureBackoffMs; return yield* registrySemaphore.withPermits(1)( Effect.gen(function* () { - const currentRevision = yield* Ref.get(registryRevision); - const current = yield* Ref.get(registryRef); - if (current !== undefined && currentRevision !== observedRevision) return current; + const current = yield* Ref.get(registryState); + const now = yield* Clock.currentTimeMillis; + if ( + maxAgeMs !== undefined && + current.index !== undefined && + current.fetchedAtMs !== undefined && + now >= current.fetchedAtMs && + now - current.fetchedAtMs < maxAgeMs + ) { + return { index: current.index, changed: false }; + } + if ( + current.index !== undefined && + (current.fetchRevision !== startFetchRevision || + (failureBackoffMs !== undefined && current.attemptRevision !== startAttemptRevision)) + ) { + return { index: current.index, changed: false }; + } + if ( + failureBackoffMs !== undefined && + current.index === undefined && + current.attemptRevision !== startAttemptRevision && + current.lastFailure !== undefined + ) { + return yield* current.lastFailure; + } + if ( + failureBackoffMs !== undefined && + current.failedAtMs !== undefined && + now >= current.failedAtMs && + now - current.failedAtMs < failureBackoffMs + ) { + if (current.index !== undefined) return { index: current.index, changed: false }; + if (current.lastFailure !== undefined) return yield* current.lastFailure; + } - const { registry, fetched } = yield* fetchRegistry().pipe( - Effect.map((registry) => ({ registry, fetched: true })), + const startInvalidationGeneration = current.invalidationGeneration; + const previousIndex = current.index; + const outcome = yield* fetchRegistry().pipe( + Effect.map((index) => ({ _tag: "fetched" as const, index })), Effect.catch((networkError) => - readCachedRegistry.pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.fail(networkError), - onSome: (registry) => Effect.succeed({ registry, fetched: false }), - }), - ), - ), + Effect.gen(function* () { + // Prefer an already-loaded index over disk so a cache-write failure cannot regress it. + const inMemory = (yield* Ref.get(registryState)).index; + if (inMemory !== undefined) { + return { _tag: "fallback" as const, index: inMemory, error: networkError }; + } + const cached = yield* readCachedRegistry; + if (Option.isSome(cached)) { + return { _tag: "fallback" as const, index: cached.value, error: networkError }; + } + return { _tag: "failed" as const, error: networkError }; + }), ), ); - yield* Ref.set(registryRef, registry); - yield* Ref.set(registryFetchedAtMs, fetched ? yield* Clock.currentTimeMillis : undefined); - yield* Ref.update(registryRevision, (revision) => revision + 1); - return registry; + const completedAt = yield* Clock.currentTimeMillis; + if (outcome._tag === "fetched") { + const changed = + previousIndex !== undefined && + encodeUnknownJson(previousIndex) !== encodeUnknownJson(outcome.index); + yield* Ref.update(registryState, (state) => { + const invalidatedMidFlight = + state.invalidationGeneration !== startInvalidationGeneration; + return { + ...state, + index: outcome.index, + fetchedAtMs: invalidatedMidFlight ? state.fetchedAtMs : completedAt, + failedAtMs: invalidatedMidFlight ? state.failedAtMs : undefined, + lastFailure: invalidatedMidFlight ? state.lastFailure : undefined, + fetchRevision: invalidatedMidFlight ? state.fetchRevision : state.fetchRevision + 1, + attemptRevision: invalidatedMidFlight + ? state.attemptRevision + : state.attemptRevision + 1, + }; + }); + return { index: outcome.index, changed }; + } + yield* Ref.update(registryState, (state) => { + const invalidatedMidFlight = state.invalidationGeneration !== startInvalidationGeneration; + return { + ...state, + index: state.index ?? (outcome._tag === "fallback" ? outcome.index : undefined), + fetchedAtMs: invalidatedMidFlight ? state.fetchedAtMs : undefined, + failedAtMs: invalidatedMidFlight ? state.failedAtMs : completedAt, + lastFailure: invalidatedMidFlight ? state.lastFailure : outcome.error, + attemptRevision: invalidatedMidFlight + ? state.attemptRevision + : state.attemptRevision + 1, + }; + }); + if (outcome._tag === "fallback") { + return { index: outcome.index, changed: false }; + } + return yield* outcome.error; }), ); }); - const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* () { - const current = yield* Ref.get(registryRef); - const fetchedAtMs = yield* Ref.get(registryFetchedAtMs); + const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* ( + maxAgeMs = REGISTRY_SEARCH_MAX_AGE_MS, + failureBackoffMs?: number, + ) { + const current = yield* Ref.get(registryState); const now = yield* Clock.currentTimeMillis; // A clock moved back makes the stamp untrustworthy, so it counts as stale. if ( - current !== undefined && - fetchedAtMs !== undefined && - now >= fetchedAtMs && - now - fetchedAtMs < REGISTRY_SEARCH_MAX_AGE_MS + current.index !== undefined && + current.fetchedAtMs !== undefined && + now >= current.fetchedAtMs && + now - current.fetchedAtMs < maxAgeMs ) { - return current; + return { index: current.index, changed: false }; } - return yield* refreshRegistry(); + if ( + failureBackoffMs !== undefined && + current.index !== undefined && + current.failedAtMs !== undefined && + now >= current.failedAtMs && + now - current.failedAtMs < failureBackoffMs + ) { + return { index: current.index, changed: false }; + } + return yield* refreshRegistry({ + maxAgeMs, + ...(failureBackoffMs === undefined ? {} : { failureBackoffMs }), + observedFetchRevision: current.fetchRevision, + observedAttemptRevision: current.attemptRevision, + }); + }); + + const refreshIndex: AcpRegistryCatalog["Service"]["refreshIndex"] = Effect.fn( + "AcpRegistryCatalog.refreshIndex", + )(function* (options) { + const result = + options?.maxAgeMs === undefined + ? yield* refreshRegistry( + options?.failureBackoffMs === undefined + ? undefined + : { failureBackoffMs: options.failureBackoffMs }, + ) + : yield* recentRegistry(options.maxAgeMs, options.failureBackoffMs); + return result.changed; + }); + + const invalidateIndex: AcpRegistryCatalog["Service"]["invalidateIndex"] = Effect.fn( + "AcpRegistryCatalog.invalidateIndex", + )(function* () { + yield* Ref.update(registryState, (current) => ({ + ...current, + fetchedAtMs: undefined, + failedAtMs: undefined, + lastFailure: undefined, + invalidationGeneration: current.invalidationGeneration + 1, + })); }); const loadRegistry = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { - const current = yield* Ref.get(registryRef); + const current = (yield* Ref.get(registryState)).index; if (current !== undefined) return current; const cached = yield* readCachedRegistry; - if (Option.isNone(cached)) return yield* refreshRegistry(); - yield* Ref.set(registryRef, cached.value); - return cached.value; + if (Option.isNone(cached)) return (yield* refreshRegistry()).index; + // Publish without waiting on an in-flight refresh, while letting a completed refresh win. + return yield* Ref.modify(registryState, (state) => + state.index !== undefined + ? ([state.index, state] as const) + : ([cached.value, { ...state, index: cached.value }] as const), + ); }); const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( @@ -1746,7 +1921,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { - const registry = yield* recentRegistry(); + const { index: registry } = yield* recentRegistry(); const ranked = []; const managerAvailability = new Map(); for (const agent of registry.agents) { @@ -1798,7 +1973,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const prepare: AcpRegistryCatalog["Service"]["prepare"] = Effect.fn("AcpRegistryCatalog.prepare")( function* (input) { - const registry = yield* refreshRegistry(); + const { index: registry } = yield* refreshRegistry(); const agent = yield* findAgent(registry, input.agentId); const distribution = yield* compatibleDistribution(agent, "auto"); if (distribution.kind === "binary") { @@ -1864,6 +2039,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const commandOverride = settings.commandPath.trim(); + const launchIdentity = registryLaunchIdentity({ + version: commandOverride.length > 0 ? null : agent.version, + distribution, + ...(commandOverride.length > 0 ? { commandOverride } : {}), + }); if (commandOverride.length > 0) { const available = (yield* resolveExecutable(commandOverride, environment ?? hostEnvironment)) !== undefined; @@ -1873,6 +2053,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: null, distribution: distribution.kind, + launchIdentity, ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -1922,6 +2103,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: "binary", + launchIdentity, ...(documentationUrl ? { documentationUrl } : {}), } as const; }), @@ -1937,6 +2119,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: distribution.kind, + launchIdentity, ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -2069,11 +2252,21 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (error) => error.reason === "download_failed", (error) => Effect.gen(function* () { - const latest = yield* refreshRegistry().pipe(Effect.mapError(() => error)); + const { index: latest } = yield* refreshRegistry().pipe(Effect.mapError(() => error)); const agentId = settings.agentId.trim(); - const versionIn = (index: AcpRegistryIndex) => - index.agents.find((agent) => agent.id === agentId)?.version; - if (versionIn(latest) === versionIn(registry)) return yield* error; + const identityIn = (index: AcpRegistryIndex) => { + const agent = index.agents.find((candidate) => candidate.id === agentId); + if (agent === undefined) return undefined; + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + return distribution === undefined + ? undefined + : registryLaunchIdentity({ version: agent.version, distribution }); + }; + if (identityIn(latest) === identityIn(registry)) return yield* error; return yield* resolveWithRegistry(settings, cwd, environment, latest); }), ), @@ -2176,6 +2369,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return AcpRegistryCatalog.of({ search, prepare, + refreshIndex, + invalidateIndex, inspect, resolve, uninstallManagedBinary, diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..e6485d7c47120 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -41,6 +41,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { + acpRegistryLiveCatalogKey, normalizeAcpRegistryCommands, normalizeAcpRegistryLiveConfiguration, normalizeAcpRegistryWebUrl, @@ -374,11 +375,24 @@ 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 normalized = normalizeAcpRegistryLiveConfiguration( + configOptions, + modeState, + modelState, + ); + const catalogKey = acpRegistryLiveCatalogKey(normalized); + const includeCatalog = + catalogKey.length > 0 && catalogKey !== updateOptions?.lastCatalogKey; + const published = includeCatalog + ? normalized + : normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState, { + includeCatalog: false, + }); + return runtimeCoordinator + .publishLiveConfiguration(options.instanceId, published) + .pipe(Effect.as(catalogKey.length > 0 ? catalogKey : null)); + }, onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); if (normalizedUrl === undefined || elicitationId.trim().length === 0) { diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 45f72554152b6..a3ffc89b447e7 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -54,6 +54,8 @@ const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { resolve: () => Effect.succeed(resolved), search: () => Effect.die("unused"), prepare: () => Effect.die("unused"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, uninstallManagedBinary: () => Effect.die("unused"), }; diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 80b1c3f870f1c..49a3c7cef4797 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -13,6 +13,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -63,6 +64,8 @@ function catalogWithInspection( return { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, inspect: () => Effect.succeed(inspection), resolve: () => Effect.die("unused resolve"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -864,6 +867,36 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.generation).toBe(5); expect(updated.entry).toBeNull(); }); + + it("preserves cache generation and expiry on options-only live updates", () => { + const optionsOnly = { + models: [], + currentModelId: "qmodel", + configOptions: [], + modelsFromModelSelect: false, + }; + const emptyCache = { generation: 4, entry: null }; + expect( + updateAcpRegistryEnrichmentCache({ + cache: emptyCache, + configuration: optionsOnly, + customModels: [], + now: 5_000, + }), + ).toBe(emptyCache); + + const provider = providerWithModels(settledConfiguration.models, "auto"); + const populatedCache = { generation: 2, entry: { provider, expiresAt: 1_000 } }; + const updated = updateAcpRegistryEnrichmentCache({ + cache: populatedCache, + configuration: optionsOnly, + customModels: [], + now: 5_000, + }); + expect(updated.generation).toBe(2); + expect(updated.entry?.expiresAt).toBe(1_000); + expect(updated.entry?.provider.models.find((m) => m.slug === "qmodel")?.isDefault).toBe(true); + }); }); describe("acpRegistryAdvertisesModelCatalog", () => { @@ -1465,4 +1498,241 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = expect(yield* agent.modelSwitches).toEqual(["other", "default", "other", "default"]); }), ); + + it.effect( + "refreshes stale registry indexes in the background for installed and uninstalled agents", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-upd-" }); + 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-v1", "other-model"])); + + let inspection: AcpRegistrySupport.AcpRegistryInspection = { + status: "unsupported", + agentId: "test-agent", + version: "1.0.0", + }; + let invalidations = 0; + let refreshes = 0; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: ProviderInstanceId.make("acpRegistry_refresh_index"), + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection(inspection), + inspect: () => Effect.sync(() => inspection), + invalidateIndex: () => + Effect.sync(() => { + invalidations += 1; + }), + refreshIndex: () => + Effect.sync(() => { + refreshes += 1; + if (inspection.status === "unsupported") { + inspection = { + status: "ready", + agentId: "test-agent", + version: "1.0.0", + distribution: "npx", + launchIdentity: "v1", + }; + return true; + } + if ( + invalidations > 0 && + inspection.status === "ready" && + inspection.version === "1.0.0" + ) { + inspection = { + status: "ready", + agentId: "test-agent", + version: "2.0.0", + distribution: "npx", + launchIdentity: "v2", + }; + return true; + } + return false; + }), + resolve: () => + Effect.succeed({ + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + + const waitForVersion = (version: string) => + instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.installed && + snapshot.version === version && + snapshot.models.some((model) => model.slug === `model-v${version[0]}`), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + + const recovered = yield* waitForVersion("1.0.0"); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(recovered))).toBe(true); + expect(refreshes).toBeGreaterThanOrEqual(1); + + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-v2", "other-model"])); + const upgraded = yield* waitForVersion("2.0.0"); + yield* instance.invalidateCaches ?? Effect.void; + expect(invalidations).toBe(1); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(upgraded))).toBe(true); + }), + ); + + it.effect( + "supersedes stale live session models on a fresh probe while letting newer live sessions win", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-live-" }); + 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-a", "new-b"])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_periodic_supersede"); + + let resolveGate: + | { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } + | undefined; + + const instance = yield* 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: "1.0.0", + distribution: "npx", + }), + resolve: () => + Effect.gen(function* () { + const gate = resolveGate; + if (gate !== undefined) { + yield* Deferred.succeed(gate.entered, undefined); + yield* Deferred.await(gate.release); + } + return { + distribution: "npx" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }), + ); + + const waitForModels = (expected: ReadonlyArray) => + instance.snapshot.streamChanges.pipe( + Stream.map((snapshot) => snapshot.models.map((model) => model.slug)), + Stream.filter((slugs) => slugs.join() === expected.join()), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + + // Stale session catalog already present before a fresh probe runs. + yield* coordinator.publishLiveConfiguration( + instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "old-a", + availableModels: [ + { modelId: "old-a", name: "old-a" }, + { modelId: "old-b", name: "old-b" }, + ], + }), + ); + + const superseded = yield* waitForModels(["old-a", "new-b"]); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(superseded))).toBe(true); + expect(Option.isNone(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + + // Next readiness check keeps the accepted catalog after live config was cleared. + yield* instance.snapshot.refresh; + expect((yield* instance.snapshot.getSnapshot).models.map((m) => m.slug)).toEqual([ + "old-a", + "new-b", + ]); + + // A newer live update published while a probe is in flight is preserved after probe reconciliation. + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["old-a", "probed-c"])); + resolveGate = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + yield* Deferred.await(resolveGate.entered); + + const optionsOnlyLive = normalizeAcpRegistryLiveConfiguration( + [], + undefined, + { + currentModelId: "probed-c", + availableModels: [ + { modelId: "old-a", name: "old-a" }, + { modelId: "probed-c", name: "probed-c" }, + ], + }, + { includeCatalog: false }, + ); + yield* coordinator.publishLiveConfiguration(instanceId, optionsOnlyLive); + + const reconciled = yield* waitForModels(["old-a", "probed-c"]); + yield* Deferred.succeed(resolveGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(reconciled))).toBe(true); + // The live update that arrived mid-probe was not cleared by the older probe. + expect(Option.isSome(yield* coordinator.getLiveConfiguration(instanceId))).toBe(true); + expect( + (yield* instance.snapshot.getSnapshot).models.find((m) => m.slug === "probed-c") + ?.isDefault, + ).toBe(true); + }), + ); + + it("invalidates cached enrichment when launchIdentity changes at the same version", () => { + const provider = providerWithModels([{ id: "m1", name: "M1", description: null }], "m1"); + expect( + isAcpRegistryCacheValid( + { provider, launchIdentity: "id-a", expiresAt: 1000 }, + "1.0.0", + false, + 500, + "id-a", + ), + ).toBe(true); + expect( + isAcpRegistryCacheValid( + { provider, launchIdentity: "id-a", expiresAt: 1000 }, + "1.0.0", + false, + 500, + "id-b", + ), + ).toBe(false); + }); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 1a283f7be976c..9757b49c98c5c 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -77,6 +77,7 @@ 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; +const REGISTRY_REFRESH_FAILURE_BACKOFF_MS = 60 * 1_000; function acpRegistryProbeTtlMs(provider: ServerProvider): number { const discoveredModels = provider.models.filter((model) => !model.isCustom); @@ -87,6 +88,7 @@ interface AcpRegistryEnrichmentCache { readonly generation: number; readonly entry: { readonly provider: ServerProvider; + readonly launchIdentity?: string; readonly expiresAt: number; } | null; } @@ -96,10 +98,12 @@ export function isAcpRegistryCacheValid( inspectedVersion: string | null, local: boolean, now: number, + inspectedLaunchIdentity?: string, ): boolean { return ( entry.expiresAt > now && - ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion) + ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion) && + (inspectedLaunchIdentity === undefined || entry.launchIdentity === inspectedLaunchIdentity) ); } @@ -111,10 +115,8 @@ export function updateAcpRegistryEnrichmentCache(input: { }): AcpRegistryEnrichmentCache { const { cache, configuration, customModels, now } = 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 a live catalog update advances the epoch; options-only updates must not discard an in-flight probe. + return configuration.models.length > 0 ? { ...cache, generation: cache.generation + 1 } : cache; } const provider = applyAcpRegistryLiveConfiguration( cache.entry.provider, @@ -122,16 +124,18 @@ export function updateAcpRegistryEnrichmentCache(input: { customModels, ); if (Equal.equals(provider, cache.entry.provider)) return cache; + const catalogChanged = !Equal.equals( + cache.entry.provider.models.filter((model) => !model.isCustom).map((model) => model.slug), + provider.models.filter((model) => !model.isCustom).map((model) => model.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, + // Advance the epoch and renew TTL only when the live session actually changed the model catalog. + generation: catalogChanged ? cache.generation + 1 : cache.generation, entry: { ...cache.entry, provider, - expiresAt: now + acpRegistryProbeTtlMs(provider), + expiresAt: catalogChanged ? now + acpRegistryProbeTtlMs(provider) : cache.entry.expiresAt, }, }; } @@ -710,11 +714,24 @@ export const AcpRegistryDriver: ProviderDriver | null>(null); + const observeLiveRevision = (revision: number) => + Ref.update(lastObservedLiveRevision, (current) => Math.max(current, revision)); + const isSyntheticDefaultOnly = (models: ReadonlyArray) => { + const builtIn = models.filter((model) => !model.isCustom); + return builtIn.length === 0 || (builtIn.length === 1 && builtIn[0]?.slug === "default"); + }; const clearLearnedModels = learnedModelOptions.clear; const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, ) { - if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); + if (input.auth.status === "unauthenticated") { + yield* confirmedAuthentication.set(false); + yield* Ref.set(lastAcceptedCatalog, null); + } if (input.installed) yield* learnedModelOptions.setVersion(input.version); const provider = input.enabled && @@ -723,18 +740,38 @@ export const AcpRegistryDriver: ProviderDriver model.isCustom); + return withAcpRegistryLearnedModelOptions( + { ...candidate, models: [...accepted, ...custom] }, + learned, + ); + } + return withAcpRegistryLearnedModelOptions(candidate, learned); + }); if (Option.isNone(runtimeCoordinator)) { - return withAcpRegistryLearnedModelOptions(provider, yield* learnedModelOptions.get); + return yield* withAcceptedFallback(provider); } 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); + const liveSnapshot = yield* coordinator.getLiveConfigurationWithRevision(instanceId); + yield* observeLiveRevision(liveSnapshot.revision); + const base = yield* withAcceptedFallback(withCommands); + const withConfiguration = Option.isSome(liveSnapshot.configuration) + ? yield* applyLiveConfiguration(base, liveSnapshot.configuration.value) + : base; return applyAcpRegistryUrlAuthAction( withConfiguration, yield* coordinator.getUrlAuthAction(instanceId), @@ -768,8 +805,14 @@ export const AcpRegistryDriver: ProviderDriver Effect.Effect) => - checkAcpRegistryProviderStatus( + const enrichProvider = Effect.fn("AcpRegistryDriver.enrichProvider")(function* ( + publishProbed: ( + provider: ServerProvider, + modelsFromModelSelect: boolean, + ) => Effect.Effect, + ) { + const modelsFromSelectRef = yield* Ref.make(false); + const provider = yield* checkAcpRegistryProviderStatus( { ...readinessInput, cwd: host.paths.cwd, @@ -778,7 +821,11 @@ export const AcpRegistryDriver: ProviderDriver modelsToDiscover(provider).pipe( Effect.tap((modelIds) => - modelIds.length === 0 ? Effect.void : publishProbed(provider), + modelIds.length === 0 + ? Effect.void + : Ref.get(modelsFromSelectRef).pipe( + Effect.flatMap((fromSelect) => publishProbed(provider, fromSelect)), + ), ), ), onDiscovered: (configuration) => { @@ -789,7 +836,12 @@ export const AcpRegistryDriver: ProviderDriver + probeAcpRegistryConfiguration(input).pipe( + Effect.tap((result) => + Ref.set(modelsFromSelectRef, result.modelsFromModelSelect === true), + ), + ), ).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -797,6 +849,19 @@ export const AcpRegistryDriver: ProviderDriver 0; + const clearLiveState = ( + Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value + .clearLiveConfiguration(instanceId) + .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId))) + : Effect.void + ).pipe(Effect.andThen(clearLearnedModels), Effect.andThen(Ref.set(lastAcceptedCatalog, null))); const enrichmentCache = yield* Ref.make({ generation: 0, entry: null, @@ -811,8 +876,31 @@ export const AcpRegistryDriver: ProviderDriver Effect.Effect, ) { + if (hasRegistryAgent) { + yield* catalog + .refreshIndex({ + maxAgeMs: PROBE_SUCCESS_TTL_MS, + failureBackoffMs: REGISTRY_REFRESH_FAILURE_BACKOFF_MS, + }) + .pipe(Effect.ignore); + } + const currentInspection = hasRegistryAgent + ? yield* catalog.inspect(effectiveConfig, processEnvironment).pipe(Effect.option) + : Option.none(); + const inspectedVersion = + Option.isSome(currentInspection) && currentInspection.value.status === "ready" + ? currentInspection.value.version + : baseSnapshot.version; + const inspectedLaunchIdentity = + Option.isSome(currentInspection) && currentInspection.value.status === "ready" + ? currentInspection.value.launchIdentity + : undefined; const now = yield* Clock.currentTimeMillis; const cacheState = yield* Ref.get(enrichmentCache); const cached = cacheState.entry; @@ -820,16 +908,32 @@ export const AcpRegistryDriver: ProviderDriver - remember(provider).pipe( - Effect.andThen(publish({ provider, generation: cacheState.generation })), - ), + const { provider: enriched, modelsFromModelSelect } = yield* enrichProvider( + (provider, fromSelect) => + remember(provider).pipe( + Effect.andThen( + publish({ + provider, + generation: cacheState.generation, + fresh: true, + probeStartLiveRevision, + modelsFromModelSelect: fromSelect, + runtimeChanged, + }), + ), + ), ); yield* remember(enriched); - return { provider: enriched, generation: cacheState.generation }; + return { + provider: enriched, + generation: cacheState.generation, + fresh: true, + probeStartLiveRevision, + modelsFromModelSelect, + runtimeChanged, + }; }); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< @@ -870,29 +994,77 @@ export const AcpRegistryDriver: ProviderDriver buildInitialAcpRegistrySnapshot(readinessInput), checkProvider, - enrichSnapshot: Effect.fn("enrichSnapshot")(function ({ + enrichSnapshot: Effect.fn("enrichSnapshot")(function* ({ snapshot, getSnapshot, publishSnapshot, }) { - if (!snapshot.installed) return Effect.void; + let targetSnapshot = snapshot; + if (!targetSnapshot.installed) { + if (!hasRegistryAgent) return; + const refresh = catalog + .refreshIndex({ + maxAgeMs: PROBE_SUCCESS_TTL_MS, + failureBackoffMs: REGISTRY_REFRESH_FAILURE_BACKOFF_MS, + }) + .pipe(Effect.orElseSucceed(() => false)); + const refreshed = yield* Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value.runBackgroundProbe(effectiveConfig.agentId, refresh) + : refresh.pipe(Effect.asSome); + if (Option.isNone(refreshed)) return; + targetSnapshot = yield* checkProvider; + if (!targetSnapshot.installed) { + if (refreshed.value) { + yield* liveSnapshotSemaphore.withPermit(publishSnapshot(targetSnapshot)); + } + return; + } + yield* liveSnapshotSemaphore.withPermit(publishSnapshot(targetSnapshot)); + } const publishEnriched = ({ provider, generation, + fresh, + probeStartLiveRevision, + modelsFromModelSelect, + runtimeChanged, }: { readonly provider: ServerProvider; readonly generation: number; + readonly fresh: boolean; + readonly probeStartLiveRevision: number; + readonly modelsFromModelSelect: boolean; + readonly runtimeChanged: boolean; }) => liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, - ), - ), + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + if (current.generation !== generation) return; + if (fresh && provider.status === "ready") { + const probedBuiltIn = provider.models.filter((model) => !model.isCustom); + const authoritativeProbe = + probedBuiltIn.length > 1 || (probedBuiltIn.length === 1 && modelsFromModelSelect); + if (runtimeChanged || authoritativeProbe) { + const cleared = Option.isSome(runtimeCoordinator) + ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision( + instanceId, + probeStartLiveRevision, + ) + : true; + if (cleared) { + if (runtimeChanged) { + yield* clearLiveState; + } + if (authoritativeProbe) { + yield* Ref.set(lastAcceptedCatalog, probedBuiltIn); + } + } + } + } + yield* publishSnapshot(yield* withLiveRuntimeState(provider)); + }), ); - const enrichment = enrichProviderCached(snapshot, publishEnriched); + const enrichment = enrichProviderCached(targetSnapshot, publishEnriched); const publishEnrichment = ( Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( @@ -910,7 +1082,7 @@ 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.gen(function* () { + const live = + yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId); + // A fresh probe cleared this revision; replaying it would restore a stale catalog. + if (live.revision !== revision && Option.isNone(live.configuration)) return; + yield* observeLiveRevision(revision); + const current = yield* getSnapshot; + const updated = yield* applyLiveConfiguration(current, configuration); + if (configuration.models.length > 0) { + const builtIn = updated.models.filter((model) => !model.isCustom); + if ( + builtIn.length > 1 || + (builtIn.length === 1 && configuration.modelsFromModelSelect === true) + ) { + yield* Ref.set(lastAcceptedCatalog, builtIn); + } + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + }), + ); + yield* publishSnapshot(updated); + }), ), - Effect.flatMap(publishSnapshot), - ), + { afterRevision }, ), + ), ); const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( instanceId, @@ -964,7 +1151,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)), - ), + invalidateCaches: liveSnapshotSemaphore + .withPermit( + (Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value.clearLiveConfiguration(instanceId) + : Effect.void + ).pipe( + Effect.andThen(clearLearnedModels), + Effect.andThen(Ref.set(lastAcceptedCatalog, null)), + Effect.andThen(invalidateEnrichmentCache), + ), + ) + .pipe(Effect.andThen(hasRegistryAgent ? catalog.invalidateIndex() : Effect.void)), orchestrationAdapter, textGeneration: yield* makeAcpRegistryTextGeneration({ instanceId, @@ -1112,7 +1297,19 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe( + Effect.tap(() => + liveSnapshotSemaphore.withPermit( + (Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value.clearLiveConfiguration(instanceId) + : Effect.void + ).pipe( + Effect.andThen(Ref.set(lastAcceptedCatalog, null)), + Effect.andThen(invalidateEnrichmentCache), + ), + ), + ), + ), disableProvider: ({ cwd, providerId }) => provideAcpManagementServices( disableAcpRegistryProvider({ @@ -1122,7 +1319,19 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))), + ).pipe( + Effect.tap(() => + liveSnapshotSemaphore.withPermit( + (Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value.clearLiveConfiguration(instanceId) + : Effect.void + ).pipe( + Effect.andThen(Ref.set(lastAcceptedCatalog, null)), + Effect.andThen(invalidateEnrichmentCache), + ), + ), + ), + ), logout: (cwd) => { const logout = logoutAcpRegistry({ instanceId, @@ -1137,6 +1346,8 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( invalidateEnrichmentCache.pipe( + Effect.andThen(Ref.set(lastAcceptedCatalog, null)), + Effect.andThen(clearLearnedModels), Effect.andThen( Option.isSome(runtimeCoordinator) ? Effect.all( diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 4d2751a5dafbc..c3562fd7f3a27 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -218,10 +218,20 @@ export interface AcpRegistryLiveConfiguration { readonly modelsFromModelSelect?: boolean; } +export function acpRegistryLiveCatalogKey( + configuration: Pick, +): string { + if (configuration.models.length === 0) return ""; + return `${configuration.modelsFromModelSelect ? "select" : "list"}:${configuration.models + .map((model) => `${model.id}\0${model.name}`) + .join("\u001f")}`; +} + export function normalizeAcpRegistryLiveConfiguration( configOptions: ReadonlyArray, modeState?: Parameters[0]["modeState"], modelState?: EffectAcpSchema.SessionModelState | null, + options?: { readonly includeCatalog?: boolean }, ): AcpRegistryLiveConfiguration { const modelOption = findModelConfigOption(configOptions); const currentModelId = @@ -258,8 +268,9 @@ export function normalizeAcpRegistryLiveConfiguration( .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config") .map((option) => option.id), ); + const includeCatalog = options?.includeCatalog !== false; return { - models, + models: includeCatalog ? models : [], currentModelId: models.some((model) => model.id === boundedCurrentModelId) ? boundedCurrentModelId : null, @@ -267,7 +278,7 @@ export function normalizeAcpRegistryLiveConfiguration( modelOptionIds: descriptors .filter((descriptor) => modelOptionIds.has(descriptor.id)) .map((descriptor) => descriptor.id), - modelsFromModelSelect: modelOption !== undefined, + modelsFromModelSelect: includeCatalog && modelOption !== undefined, }; } @@ -405,6 +416,7 @@ export interface AcpRegistryConfigurationProbeResult { readonly probe: AcpRegistryProbeResult; readonly slashCommands: ReadonlyArray; readonly skills: ReadonlyArray; + readonly modelsFromModelSelect?: boolean; } export type AcpRegistryConfigurationProbe = ( @@ -502,17 +514,7 @@ const isolateDeepSeekProbeHistory = Effect.fn("AcpRegistryProbe.isolateDeepSeekP ); export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeConfiguration")( - function* ( - input: AcpRegistryConfigurationProbeInput, - ): Effect.fn.Return< - AcpRegistryConfigurationProbeResult, - AcpRegistryOperationError, - | AcpRegistrySupport.AcpRegistryCatalog - | ChildProcessSpawner.ChildProcessSpawner - | FileSystem.FileSystem - | Path.Path - | SecureRandom.SecureRandom - > { + function* (input: AcpRegistryConfigurationProbeInput) { const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const probeTimeoutMs = resolveProviderProbeTimeoutMs( "acp_registry", @@ -523,11 +525,12 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo const random = yield* SecureRandom.SecureRandom; const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); + // Downloads and package installs have their own bounded timeouts inside AcpRegistryCatalog. + const resolved = yield* catalog + .resolve(input.settings, input.cwd, input.environment) + .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)); + const openSession = Effect.gen(function* () { - // Resolution may install packages; bound it by the probe deadline. - const resolved = yield* catalog - .resolve(input.settings, input.cwd, input.environment) - .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)); const spawn = yield* isolateDeepSeekProbeHistory( input.settings.commandPath, resolved.spawn, @@ -692,7 +695,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo Effect.fail( new AcpRegistryOperationError({ reason: "probe_failed", - message: `The ACP agent did not resolve and create a test session within ${probeTimeoutMs / 1_000} seconds. Package installation or agent startup may be slow; this check retries on the next provider refresh.`, + message: `The ACP agent did not create a test session within ${probeTimeoutMs / 1_000} seconds. Agent startup may be slow; this check retries on the next provider refresh.`, }), ), }), @@ -712,6 +715,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: session.commands.slashCommands, skills: session.commands.skills, + modelsFromModelSelect: session.liveConfiguration.modelsFromModelSelect === true, }; // Runs in the probe session before it is deleted, outside the setup deadline. if (input.modelDiscovery !== undefined) { @@ -724,12 +728,12 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo } return result; }).pipe( - Effect.scoped, Effect.mapError((error) => error._tag === "AcpRegistryOperationError" ? error : acpRegistryProbeFailure(error), ), ); }, + Effect.scoped, ); const MANAGEMENT_TIMEOUT = Duration.seconds(60); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index b7bc82757fe5d..d928e9fa87b81 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -483,7 +483,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; @@ -2356,6 +2357,41 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); + const lastPublishedCatalogKey = yield* Ref.make<{ + readonly epoch: number; + readonly key: string | null; + }>({ epoch: 0, key: null }); + const sessionConfigurationPublishPermit = yield* Semaphore.make(1); + const resetPublishedCatalogKey = Ref.update(lastPublishedCatalogKey, (current) => ({ + epoch: current.epoch + 1, + key: null, + })); + // Per-update session config publication shares the enclosing session update/config span. + const publishSessionConfiguration = Effect.fnUntraced(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 (nextKey === null || typeof nextKey === "string") { + yield* Ref.update(lastPublishedCatalogKey, (current) => + current.epoch === epoch ? { epoch, key: nextKey } : current, + ); + } + }), + ); + }); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { @@ -2375,6 +2411,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); @@ -7300,13 +7337,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. @@ -7422,6 +7453,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); @@ -7436,13 +7468,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* ( @@ -8581,13 +8607,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( @@ -9361,6 +9381,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.