From 069132b7531002eaf66fae620fabee1f723c75b0 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 06:32:06 +0000 Subject: [PATCH 01/28] fix(acp-registry): refresh stale registry cache so installed agents update --- .../src/provider/AcpRegistryProbe.test.ts | 3 + .../src/server/AcpRegistrySupport.test.ts | 110 +++++++++++++ .../src/server/AcpRegistrySupport.ts | 16 +- .../src/server/auth.test.ts | 1 + .../src/server/driver.test.ts | 146 ++++++++++++++++++ .../src/server/driver.ts | 8 + 6 files changed, 282 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 6c0766d1cf7d8..c7e33e0a577ec 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -362,6 +362,7 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -423,6 +424,7 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -492,6 +494,7 @@ await import(pathToFileURL(agentPath).href); const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 398c48be3f68c..7474dcaa97153 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -960,6 +960,116 @@ describe("AcpRegistrySupport", () => { ); }); + it.effect("refreshes a cached registry index according to maxAgeMs and explicit refresh", () => { + const makeBinaryAgent = (version: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: `https://registry.test/example-agent-${version}.bin`, + cmd: "./bin/example-agent", + }, + }, + }), + version, + }); + let upstream = makeBinaryAgent("1.2.4"); + let online = true; + let registryRequests = 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(makeBinaryAgent("1.2.3")), + ); + const installedV1 = `${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(`${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin`, { + recursive: true, + }); + yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.2.3\n"); + yield* fileSystem.chmod(installedV1, 0o755); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + + // Cold inspection stays on disk with no network request. + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.3", + }); + expect(registryRequests).toBe(0); + + // Refreshing a disk-loaded index fetches the latest version once, then reuses it until maxAgeMs. + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(registryRequests).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.4", + }); + + upstream = makeBinaryAgent("1.2.5"); + yield* TestClock.adjust("14 minutes"); + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(registryRequests).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); + + yield* TestClock.adjust("1 minute"); + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(registryRequests).toBe(2); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); + + // Explicit refresh bypasses the reuse window and lets resolve install the new binary. + upstream = makeBinaryAgent("1.2.6"); + yield* resolver.refreshIndex(); + expect(registryRequests).toBe(3); + const resolved = yield* resolver.resolve(settings(), "/workspace", {}); + expect(resolved.spawn.command).toContain( + "/tools/example-agent/1.2.6/linux-x86_64/bin/example-agent", + ); + + // Offline refresh keeps the cached index and retries on the next refreshIndex call. + online = false; + yield* resolver.refreshIndex(); + expect(registryRequests).toBe(4); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); + + online = true; + upstream = makeBinaryAgent("1.2.7"); + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(registryRequests).toBe(5); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + registryRequests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(upstream)) + : new Response("unavailable", { status: 503 }), + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(`#!/bin/sh\necho ${upstream.version}\n`), + ), + ); + }), + ), + ); + }); + it.effect( "prepares the registry version despite an older PATH binary and permits explicit overrides", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index d3ab397d7aaeb..5eb65fc0bc5a4 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -525,6 +525,9 @@ export class AcpRegistryCatalog extends Context.Service< readonly prepare: ( input: AcpRegistryPrepareInput, ) => Effect.Effect; + readonly refreshIndex: (options?: { + readonly maxAgeMs?: number; + }) => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, environment?: NodeJS.ProcessEnv, @@ -974,7 +977,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); }); - const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* () { + const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* ( + maxAgeMs = REGISTRY_SEARCH_MAX_AGE_MS, + ) { const current = yield* Ref.get(registryRef); const fetchedAtMs = yield* Ref.get(registryFetchedAtMs); const now = yield* Clock.currentTimeMillis; @@ -983,13 +988,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct current !== undefined && fetchedAtMs !== undefined && now >= fetchedAtMs && - now - fetchedAtMs < REGISTRY_SEARCH_MAX_AGE_MS + now - fetchedAtMs < maxAgeMs ) { return current; } return yield* refreshRegistry(); }); + const refreshIndex: AcpRegistryCatalog["Service"]["refreshIndex"] = Effect.fn( + "AcpRegistryCatalog.refreshIndex", + )(function* (options) { + yield* options?.maxAgeMs === undefined ? refreshRegistry() : recentRegistry(options.maxAgeMs); + }); + const loadRegistry = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { const current = yield* Ref.get(registryRef); if (current !== undefined) return current; @@ -2154,6 +2165,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return AcpRegistryCatalog.of({ search, prepare, + refreshIndex, inspect, resolve, uninstallManagedBinary, diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 45f72554152b6..5edff88623800 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -54,6 +54,7 @@ const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { resolve: () => Effect.succeed(resolved), search: () => Effect.die("unused"), prepare: () => Effect.die("unused"), + refreshIndex: () => 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 684eb21d7456b..c2e503b2574f2 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -9,12 +9,15 @@ 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 TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -61,6 +64,7 @@ function catalogWithInspection( return { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.void, inspect: () => Effect.succeed(inspection), resolve: () => Effect.die("unused resolve"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -1188,4 +1192,146 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); }), ); + + it.effect("refreshes a cached registry index on enrichment and explicit cache invalidation", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-update-" }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + const registryUrl = "https://registry.test/registry.json"; + const makeRegistry = (version: string) => + JSON.stringify({ + version: "1.0.0", + agents: [ + { + id: "test-agent", + name: "Test Agent", + version, + description: "Test binary agent", + distribution: { + binary: { + "linux-x86_64": { + archive: `https://registry.test/test-agent-${version}.bin`, + cmd: "./bin/test-agent", + }, + }, + }, + }, + ], + }); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); + yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(directory, "acp-registry", "registry.json"), + makeRegistry("1.0.0"), + ); + const installedV1 = path.join( + directory, + "tools", + "test-agent", + "1.0.0", + "linux-x86_64", + "bin", + "test-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); + yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); + yield* fileSystem.chmod(installedV1, 0o755); + + let latestVersion = "2.0.0"; + let registryRequests = 0; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + registryRequests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(latestVersion))), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(`#!/bin/sh\necho ${latestVersion}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + const waitForEnriched = () => + instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ); + + // Initial enrichment refreshes the disk-cached 1.0.0 index and installs 2.0.0. + const upgradedToV2 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const first = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); + expect(first.version).toBe("2.0.0"); + expect( + yield* fileSystem.exists( + path.join(directory, "tools", "test-agent", "2.0.0", "linux-x86_64", "bin", "test-agent"), + ), + ).toBe(true); + + // Explicit cache invalidation refreshes past the in-memory reuse window and installs 3.0.0. + latestVersion = "3.0.0"; + const upgradedToV3 = yield* waitForEnriched().pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + const second = Option.getOrThrow(yield* Fiber.join(upgradedToV3)); + expect(second.version).toBe("3.0.0"); + expect( + yield* fileSystem.exists( + path.join(directory, "tools", "test-agent", "3.0.0", "linux-x86_64", "bin", "test-agent"), + ), + ).toBe(true); + + // Disabled instances must not fetch the registry on cache invalidation. + const disabledRequestsBefore = registryRequests; + const disabled = yield* AcpRegistryDriver.create({ + instanceId: ProviderInstanceId.make("acpRegistry_disabled"), + displayName: "Disabled ACP", + enabled: false, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + yield* disabled.invalidateCaches ?? Effect.void; + expect(registryRequests).toBe(disabledRequestsBefore); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 46d8ed3219aa4..fdea0c90ad0e0 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -793,6 +793,9 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 06:50:25 +0000 Subject: [PATCH 02/28] fix(acp-registry): refresh stale index when uninstalled and guard cold disk read --- .../src/server/AcpRegistrySupport.ts | 11 +- .../src/server/driver.test.ts | 167 ++++++++++++++++++ .../src/server/driver.ts | 12 +- 3 files changed, 186 insertions(+), 4 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 5eb65fc0bc5a4..44a490de3f88c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1007,8 +1007,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const cached = yield* readCachedRegistry; if (Option.isNone(cached)) return yield* refreshRegistry(); - yield* Ref.set(registryRef, cached.value); - return cached.value; + return yield* registrySemaphore.withPermits(1)( + Effect.gen(function* () { + // A refresh that completed during the disk read owns the stored index. + const latest = yield* Ref.get(registryRef); + if (latest !== undefined) return latest; + yield* Ref.set(registryRef, cached.value); + return cached.value; + }), + ); }); const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index c2e503b2574f2..d961e5ba9fd8c 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 HostProcess from "@t3tools/shared/HostProcess"; 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"; @@ -23,6 +24,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; @@ -1335,3 +1337,168 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }), ); }); + +it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { + it.effect( + "recovers when a refreshed index moves from compatible to incompatible and back without cache invalidation", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "acp-driver-recover-", + }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + const registryUrl = "https://registry.test/registry.json"; + const makeRegistry = (version: string, target: "linux-x86_64" | "darwin-aarch64") => + JSON.stringify({ + version: "1.0.0", + agents: [ + { + id: "test-agent", + name: "Test Agent", + version, + description: "Test binary agent", + distribution: { + binary: { + [target]: { + archive: `https://registry.test/test-agent-${version}.bin`, + cmd: "./bin/test-agent", + }, + }, + }, + }, + ], + }); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); + yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(directory, "acp-registry", "registry.json"), + makeRegistry("1.0.0", "linux-x86_64"), + ); + const installedV1 = path.join( + directory, + "tools", + "test-agent", + "1.0.0", + "linux-x86_64", + "bin", + "test-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); + yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); + yield* fileSystem.chmod(installedV1, 0o755); + + let remoteVersion = "2.0.0"; + let remoteTarget: "linux-x86_64" | "darwin-aarch64" = "darwin-aarch64"; + let resolvedProbes = 0; + const restoredRefreshDone = yield* Deferred.make(); + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeRegistry(remoteVersion, remoteTarget) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + refreshIndex: (options) => + realCatalog + .refreshIndex(options) + .pipe( + Effect.tap(() => + remoteVersion === "3.0.0" + ? Deferred.succeed(restoredRefreshDone, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.tap(() => + Effect.sync(() => { + resolvedProbes += 1; + }), + ), + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // 1. Compatible 1.0.0 transitions to incompatible 2.0.0. + const becameUnsupported = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => !snapshot.installed && snapshot.version === "2.0.0"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const unsupported = Option.getOrThrow(yield* Fiber.join(becameUnsupported)); + expect(unsupported.status).toBe("error"); + + // 2. Upstream restores a compatible 3.0.0; post-TTL refresh updates the index while keeping probe suppressed. + const resolvedBeforeRecovery = resolvedProbes; + remoteVersion = "3.0.0"; + remoteTarget = "linux-x86_64"; + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(restoredRefreshDone); + expect(resolvedProbes).toBe(resolvedBeforeRecovery); + + // 3. The next periodic refresh recovers and installs 3.0.0 without invalidateCaches. + const recovered = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.installed && + snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const ready = Option.getOrThrow(yield* Fiber.join(recovered)); + expect(ready.status).toBe("ready"); + expect(resolvedProbes).toBeGreaterThan(resolvedBeforeRecovery); + expect( + yield* fileSystem.exists( + path.join( + directory, + "tools", + "test-agent", + "3.0.0", + "linux-x86_64", + "bin", + "test-agent", + ), + ), + ).toBe(true); + }), + ); +}); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index fdea0c90ad0e0..5f2a70acbc5fa 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -832,7 +832,13 @@ export const AcpRegistryDriver: ProviderDriver 0 + ? catalog.refreshIndex({ maxAgeMs: PROBE_SUCCESS_TTL_MS }).pipe(Effect.ignore) + : Effect.void; + } const publishEnrichment = ( Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( @@ -1013,7 +1019,9 @@ export const AcpRegistryDriver: ProviderDriver 0 ? catalog.refreshIndex().pipe(Effect.ignore) : Effect.void, ), From b0c43d6a65b8455e51293e51829d3aa57010ef76 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:56:34 +0000 Subject: [PATCH 03/28] test(acp-registry): leave binary install to the driver test Co-Authored-By: Claude Opus 5.5 --- .../src/server/AcpRegistrySupport.test.ts | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 7474dcaa97153..c7e0e2a7e9757 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1024,16 +1024,12 @@ describe("AcpRegistrySupport", () => { expect(registryRequests).toBe(2); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); - // Explicit refresh bypasses the reuse window and lets resolve install the new binary. upstream = makeBinaryAgent("1.2.6"); yield* resolver.refreshIndex(); expect(registryRequests).toBe(3); - const resolved = yield* resolver.resolve(settings(), "/workspace", {}); - expect(resolved.spawn.command).toContain( - "/tools/example-agent/1.2.6/linux-x86_64/bin/example-agent", - ); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); - // Offline refresh keeps the cached index and retries on the next refreshIndex call. + // An offline refresh keeps the cached index and retries on the next call. online = false; yield* resolver.refreshIndex(); expect(registryRequests).toBe(4); @@ -1048,21 +1044,13 @@ describe("AcpRegistrySupport", () => { Effect.scoped, Effect.provide( layerResolver((request) => { - if (request.url === registryUrl) { - registryRequests += 1; - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - online - ? new Response(makeRegistry(upstream)) - : new Response("unavailable", { status: 503 }), - ), - ); - } + registryRequests += 1; return Effect.succeed( HttpClientResponse.fromWeb( request, - new Response(`#!/bin/sh\necho ${upstream.version}\n`), + online + ? new Response(makeRegistry(upstream)) + : new Response("unavailable", { status: 503 }), ), ); }), From f0aa4e7276862484138e0b35828294e17083ba68 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:59:07 +0000 Subject: [PATCH 04/28] test(acp-registry): share the installed-binary fixture between driver tests Co-Authored-By: Claude Opus 5.5 --- .../src/server/driver.test.ts | 176 ++++++------------ 1 file changed, 62 insertions(+), 114 deletions(-) diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index d961e5ba9fd8c..9451c9313ae7a 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -955,6 +955,55 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); `; +type RegistryTarget = "linux-x86_64" | "darwin-aarch64"; + +const registryUrl = "https://registry.test/registry.json"; + +const makeBinaryRegistry = (version: string, target: RegistryTarget = "linux-x86_64") => + JSON.stringify({ + version: "1.0.0", + agents: [ + { + id: "test-agent", + name: "Test Agent", + version, + description: "Test binary agent", + distribution: { + binary: { + [target]: { + archive: `https://registry.test/test-agent-${version}.bin`, + cmd: "./bin/test-agent", + }, + }, + }, + }, + ], + }); + +// A disk-cached 1.0.0 index with its binary installed, as left behind by an earlier session. +const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* (prefix: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); + yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(directory, "acp-registry", "registry.json"), + makeBinaryRegistry("1.0.0"), + ); + const installedV1 = installedBinaryPath(path, directory, "1.0.0"); + yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); + yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); + yield* fileSystem.chmod(installedV1, 0o755); + return { directory, agentPath, modelsPath }; +}); + +const installedBinaryPath = (path: Path.Path, directory: string, version: string) => + path.join(directory, "tools", "test-agent", version, "linux-x86_64", "bin", "test-agent"); + const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), Layer.provideMerge(IdAllocator.layer), @@ -1199,49 +1248,8 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-update-" }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - const registryUrl = "https://registry.test/registry.json"; - const makeRegistry = (version: string) => - JSON.stringify({ - version: "1.0.0", - agents: [ - { - id: "test-agent", - name: "Test Agent", - version, - description: "Test binary agent", - distribution: { - binary: { - "linux-x86_64": { - archive: `https://registry.test/test-agent-${version}.bin`, - cmd: "./bin/test-agent", - }, - }, - }, - }, - ], - }); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); - yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); - yield* fileSystem.writeFileString( - path.join(directory, "acp-registry", "registry.json"), - makeRegistry("1.0.0"), - ); - const installedV1 = path.join( - directory, - "tools", - "test-agent", - "1.0.0", - "linux-x86_64", - "bin", - "test-agent", - ); - yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); - yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); - yield* fileSystem.chmod(installedV1, 0o755); + const { directory, agentPath, modelsPath } = + yield* seedInstalledBinaryAgent("acp-driver-update-"); let latestVersion = "2.0.0"; let registryRequests = 0; @@ -1258,7 +1266,10 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = if (request.url === registryUrl) { registryRequests += 1; return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(latestVersion))), + HttpClientResponse.fromWeb( + request, + new Response(makeBinaryRegistry(latestVersion)), + ), ); } return Effect.succeed( @@ -1302,11 +1313,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = yield* instance.snapshot.refresh; const first = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); expect(first.version).toBe("2.0.0"); - expect( - yield* fileSystem.exists( - path.join(directory, "tools", "test-agent", "2.0.0", "linux-x86_64", "bin", "test-agent"), - ), - ).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); // Explicit cache invalidation refreshes past the in-memory reuse window and installs 3.0.0. latestVersion = "3.0.0"; @@ -1317,11 +1324,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = yield* instance.snapshot.refresh; const second = Option.getOrThrow(yield* Fiber.join(upgradedToV3)); expect(second.version).toBe("3.0.0"); - expect( - yield* fileSystem.exists( - path.join(directory, "tools", "test-agent", "3.0.0", "linux-x86_64", "bin", "test-agent"), - ), - ).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); // Disabled instances must not fetch the registry on cache invalidation. const disabledRequestsBefore = registryRequests; @@ -1345,54 +1348,11 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "acp-driver-recover-", - }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - const registryUrl = "https://registry.test/registry.json"; - const makeRegistry = (version: string, target: "linux-x86_64" | "darwin-aarch64") => - JSON.stringify({ - version: "1.0.0", - agents: [ - { - id: "test-agent", - name: "Test Agent", - version, - description: "Test binary agent", - distribution: { - binary: { - [target]: { - archive: `https://registry.test/test-agent-${version}.bin`, - cmd: "./bin/test-agent", - }, - }, - }, - }, - ], - }); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); - yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); - yield* fileSystem.writeFileString( - path.join(directory, "acp-registry", "registry.json"), - makeRegistry("1.0.0", "linux-x86_64"), - ); - const installedV1 = path.join( - directory, - "tools", - "test-agent", - "1.0.0", - "linux-x86_64", - "bin", - "test-agent", - ); - yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); - yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); - yield* fileSystem.chmod(installedV1, 0o755); + const { directory, agentPath, modelsPath } = + yield* seedInstalledBinaryAgent("acp-driver-recover-"); let remoteVersion = "2.0.0"; - let remoteTarget: "linux-x86_64" | "darwin-aarch64" = "darwin-aarch64"; + let remoteTarget: RegistryTarget = "darwin-aarch64"; let resolvedProbes = 0; const restoredRefreshDone = yield* Deferred.make(); const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ @@ -1410,7 +1370,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { request, new Response( request.url === registryUrl - ? makeRegistry(remoteVersion, remoteTarget) + ? makeBinaryRegistry(remoteVersion, remoteTarget) : `#!/bin/sh\necho ${remoteVersion}\n`, ), ), @@ -1486,19 +1446,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { const ready = Option.getOrThrow(yield* Fiber.join(recovered)); expect(ready.status).toBe("ready"); expect(resolvedProbes).toBeGreaterThan(resolvedBeforeRecovery); - expect( - yield* fileSystem.exists( - path.join( - directory, - "tools", - "test-agent", - "3.0.0", - "linux-x86_64", - "bin", - "test-agent", - ), - ), - ).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); }), ); }); From 65d098e39b1cd6e4aef939e4953eae0487408222 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 07:31:19 +0000 Subject: [PATCH 05/28] fix(acp-registry): keep cold disk loads lock-free and prefer in-memory index on refresh failure --- .../src/server/AcpRegistrySupport.test.ts | 96 +++++++++++++++++-- .../src/server/AcpRegistrySupport.ts | 27 +++--- .../src/server/driver.test.ts | 52 ++++++---- 3 files changed, 135 insertions(+), 40 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index c7e0e2a7e9757..7c5b2b0680edd 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1029,7 +1029,11 @@ describe("AcpRegistrySupport", () => { expect(registryRequests).toBe(3); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); - // An offline refresh keeps the cached index and retries on the next call. + // An offline refresh prefers the in-memory index over a stale disk cache and retries next time. + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(makeBinaryAgent("1.2.3")), + ); online = false; yield* resolver.refreshIndex(); expect(registryRequests).toBe(4); @@ -1798,16 +1802,26 @@ describe("AcpRegistrySupport", () => { }); it.effect("inspects from disk without waiting for a registry refresh", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, + }); + const agent = makeNpxAgent("1.2.3"); + let upstreamVersion = "1.2.4"; let requests = 0; + let refreshGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-inspect-", }); const registryDirectory = `${cacheDir}/acp-registry`; + const registryCachePath = `${registryDirectory}/registry.json`; yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); - yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(agent)); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, @@ -1816,16 +1830,86 @@ describe("AcpRegistrySupport", () => { }); const inspection = yield* resolver.inspect(settings()); - expect(inspection).toMatchObject({ status: "ready", agentId: agent.id }); + expect(inspection).toMatchObject({ status: "ready", agentId: agent.id, version: "1.2.3" }); expect(requests).toBe(0); + + // Cold inspection returns the disk cache immediately even while a refresh holds the semaphore. + refreshGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const resolverWhileRefreshing = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const refreshFiber = yield* resolverWhileRefreshing + .refreshIndex() + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(refreshGate.started); + expect(yield* resolverWhileRefreshing.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.3", + }); + yield* Deferred.succeed(refreshGate.release, undefined); + yield* Fiber.join(refreshFiber); + expect(yield* resolverWhileRefreshing.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.4", + }); + + // A disk read that finishes after a concurrent refresh must not overwrite the refreshed index. + refreshGate = null; + upstreamVersion = "1.2.5"; + const diskReadStarted = yield* Deferred.make(); + const releaseDiskRead = yield* Deferred.make(); + const delayedFileSystem: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === registryCachePath + ? fileSystem.readFileString(filePath, encoding).pipe( + Effect.tap(() => Deferred.succeed(diskReadStarted, undefined)), + Effect.tap(() => Deferred.await(releaseDiskRead)), + ) + : fileSystem.readFileString(filePath, encoding), + }; + const resolverDuringDiskRead = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, delayedFileSystem)); + const diskInspectFiber = yield* resolverDuringDiskRead + .inspect(settings()) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(diskReadStarted); + yield* resolverDuringDiskRead.refreshIndex(); + yield* Deferred.succeed(releaseDiskRead, undefined); + expect(yield* Fiber.join(diskInspectFiber)).toMatchObject({ + status: "ready", + version: "1.2.5", + }); + expect(yield* resolverDuringDiskRead.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.5", + }); }).pipe( Effect.scoped, Effect.provide( layerResolver((request) => { requests += 1; - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), + const gate = refreshGate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + new Response(makeRegistry(makeNpxAgent(upstreamVersion))), + ), ); + return gate === null + ? respond + : Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); }), ), ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 44a490de3f88c..e0ed0792af9de 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -959,14 +959,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const { registry, fetched } = yield* fetchRegistry().pipe( Effect.map((registry) => ({ registry, fetched: true })), 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(registryRef); + if (inMemory !== undefined) return { registry: inMemory, fetched: false }; + const cached = yield* readCachedRegistry; + if (Option.isSome(cached)) return { registry: cached.value, fetched: false }; + return yield* networkError; + }), ), ); yield* Ref.set(registryRef, registry); @@ -1007,14 +1007,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const cached = yield* readCachedRegistry; if (Option.isNone(cached)) return yield* refreshRegistry(); - return yield* registrySemaphore.withPermits(1)( - Effect.gen(function* () { - // A refresh that completed during the disk read owns the stored index. - const latest = yield* Ref.get(registryRef); - if (latest !== undefined) return latest; - yield* Ref.set(registryRef, cached.value); - return cached.value; - }), + // Publish without waiting on an in-flight refresh, while letting a completed refresh win. + return yield* Ref.modify(registryRef, (latest) => + latest !== undefined ? ([latest, latest] as const) : ([cached.value, cached.value] as const), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 9451c9313ae7a..03dc23b543d0c 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -955,11 +955,19 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); `; -type RegistryTarget = "linux-x86_64" | "darwin-aarch64"; +const isWindowsHost = HostProcess.Platform.defaultValue() === "win32"; +const testHostPlatform: NodeJS.Platform = isWindowsHost ? "win32" : "linux"; +const compatibleRegistryTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = isWindowsHost + ? "windows-x86_64" + : "linux-x86_64"; +const incompatibleRegistryTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = "darwin-aarch64"; const registryUrl = "https://registry.test/registry.json"; -const makeBinaryRegistry = (version: string, target: RegistryTarget = "linux-x86_64") => +const makeBinaryRegistry = ( + version: string, + target: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget, +) => JSON.stringify({ version: "1.0.0", agents: [ @@ -997,12 +1005,22 @@ const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* const installedV1 = installedBinaryPath(path, directory, "1.0.0"); yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); - yield* fileSystem.chmod(installedV1, 0o755); + if (!isWindowsHost) { + yield* fileSystem.chmod(installedV1, 0o755); + } return { directory, agentPath, modelsPath }; }); const installedBinaryPath = (path: Path.Path, directory: string, version: string) => - path.join(directory, "tools", "test-agent", version, "linux-x86_64", "bin", "test-agent"); + path.join( + directory, + "tools", + "test-agent", + version, + compatibleRegistryTarget, + "bin", + "test-agent", + ); const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), @@ -1258,7 +1276,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = toolsDir: path.join(directory, "tools"), registryUrl, }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Platform, testHostPlatform), Effect.provideService(HostProcess.Architecture, "x64"), Effect.provideService( HttpClient.HttpClient, @@ -1352,15 +1370,15 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* seedInstalledBinaryAgent("acp-driver-recover-"); let remoteVersion = "2.0.0"; - let remoteTarget: RegistryTarget = "darwin-aarch64"; - let resolvedProbes = 0; + let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = incompatibleRegistryTarget; + let resolveAttempts = 0; const restoredRefreshDone = yield* Deferred.make(); const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, toolsDir: path.join(directory, "tools"), registryUrl, }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Platform, testHostPlatform), Effect.provideService(HostProcess.Architecture, "x64"), Effect.provideService( HttpClient.HttpClient, @@ -1391,12 +1409,10 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { ), ), resolve: (settings, cwd, environment) => - realCatalog.resolve(settings, cwd, environment).pipe( - Effect.tap(() => - Effect.sync(() => { - resolvedProbes += 1; - }), - ), + Effect.sync(() => { + resolveAttempts += 1; + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), Effect.map((resolved) => ({ ...resolved, spawn: { command: process.execPath, args: [agentPath, modelsPath] }, @@ -1423,13 +1439,13 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { expect(unsupported.status).toBe("error"); // 2. Upstream restores a compatible 3.0.0; post-TTL refresh updates the index while keeping probe suppressed. - const resolvedBeforeRecovery = resolvedProbes; + const attemptsBeforeRecovery = resolveAttempts; remoteVersion = "3.0.0"; - remoteTarget = "linux-x86_64"; + remoteTarget = compatibleRegistryTarget; yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; yield* Deferred.await(restoredRefreshDone); - expect(resolvedProbes).toBe(resolvedBeforeRecovery); + expect(resolveAttempts).toBe(attemptsBeforeRecovery); // 3. The next periodic refresh recovers and installs 3.0.0 without invalidateCaches. const recovered = yield* instance.snapshot.streamChanges.pipe( @@ -1445,7 +1461,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* instance.snapshot.refresh; const ready = Option.getOrThrow(yield* Fiber.join(recovered)); expect(ready.status).toBe("ready"); - expect(resolvedProbes).toBeGreaterThan(resolvedBeforeRecovery); + expect(resolveAttempts).toBeGreaterThan(attemptsBeforeRecovery); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); }), ); From bbf5710cb73fa552e5907115c2cc5b798f4f6f73 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 09:11:47 +0000 Subject: [PATCH 06/28] fix(acp-registry): make registry refresh non-blocking, backed off, and immediate on recovery --- .../src/provider/AcpRegistryProbe.test.ts | 3 + docs/user/providers-acp.md | 2 + .../src/server/AcpRegistrySupport.test.ts | 117 +++++---- .../src/server/AcpRegistrySupport.ts | 137 +++++++--- .../src/server/auth.test.ts | 3 +- .../src/server/driver.test.ts | 224 +++++++++++++--- .../src/server/driver.ts | 246 +++++++++++------- 7 files changed, 520 insertions(+), 212 deletions(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index c7e33e0a577ec..fa8111aaac185 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -363,6 +363,7 @@ describe("ACP Registry probe", () => { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -425,6 +426,7 @@ describe("ACP Registry probe", () => { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -495,6 +497,7 @@ await import(pathToFileURL(agentPath).href); search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + invalidateIndex: () => Effect.die("unused invalidateIndex"), 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 453c777e3c8c0..50ac68d8dfa05 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -46,6 +46,8 @@ connect through `app.t3.codes`, T3 Connect, or a relay. Agents install under `tools///` inside T3 home. T3 Code verifies SHA-256 when the Registry entry provides one; entries without a checksum retain the Registry's HTTPS distribution guarantee. +T3 Code refreshes the Registry index in the background so installed agents pick up new Registry +versions; refreshing providers in **Settings → Providers** checks immediately. Registry `npx` and `uvx` packages use T3-owned npm prefixes and Python tool directories at the exact version published by the Registry. Their commands are available in a new server terminal for sign-in and direct use. Removing an agent's last provider instance removes T3-managed binary files diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 7c5b2b0680edd..90a99f8f94e5a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -985,12 +985,6 @@ describe("AcpRegistrySupport", () => { `${cacheDir}/acp-registry/registry.json`, makeRegistry(makeBinaryAgent("1.2.3")), ); - const installedV1 = `${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent`; - yield* fileSystem.makeDirectory(`${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin`, { - recursive: true, - }); - yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.2.3\n"); - yield* fileSystem.chmod(installedV1, 0o755); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, @@ -999,49 +993,53 @@ describe("AcpRegistrySupport", () => { }); // Cold inspection stays on disk with no network request. - expect(yield* resolver.inspect(settings())).toMatchObject({ - status: "ready", - version: "1.2.3", - }); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.3" }); expect(registryRequests).toBe(0); // Refreshing a disk-loaded index fetches the latest version once, then reuses it until maxAgeMs. - yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); expect(registryRequests).toBe(1); - expect(yield* resolver.inspect(settings())).toMatchObject({ - status: "ready", - version: "1.2.4", - }); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); upstream = makeBinaryAgent("1.2.5"); yield* TestClock.adjust("14 minutes"); - yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); expect(registryRequests).toBe(1); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); yield* TestClock.adjust("1 minute"); - yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(2); expect(registryRequests).toBe(2); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); + // Explicit invalidation clears the reuse window without discarding the in-memory index. upstream = makeBinaryAgent("1.2.6"); - yield* resolver.refreshIndex(); + yield* resolver.invalidateIndex(); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); expect(registryRequests).toBe(3); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); - // An offline refresh prefers the in-memory index over a stale disk cache and retries next time. + // An offline refresh prefers the in-memory index over a stale disk cache and backs off background retries. yield* fileSystem.writeFileString( `${cacheDir}/acp-registry/registry.json`, makeRegistry(makeBinaryAgent("1.2.3")), ); online = false; - yield* resolver.refreshIndex(); + yield* resolver.invalidateIndex(); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); expect(registryRequests).toBe(4); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); online = true; upstream = makeBinaryAgent("1.2.7"); - yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000 }); + yield* TestClock.adjust("59 seconds"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(4); + + yield* TestClock.adjust("1 second"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); expect(registryRequests).toBe(5); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); }).pipe( @@ -1807,7 +1805,6 @@ describe("AcpRegistrySupport", () => { version, }); const agent = makeNpxAgent("1.2.3"); - let upstreamVersion = "1.2.4"; let requests = 0; let refreshGate: { readonly started: Deferred.Deferred; @@ -1844,7 +1841,7 @@ describe("AcpRegistrySupport", () => { registryUrl, }); const refreshFiber = yield* resolverWhileRefreshing - .refreshIndex() + .refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }) .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(refreshGate.started); expect(yield* resolverWhileRefreshing.inspect(settings())).toMatchObject({ @@ -1857,10 +1854,41 @@ describe("AcpRegistrySupport", () => { status: "ready", version: "1.2.4", }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + const gate = refreshGate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb(request, new Response(makeRegistry(makeNpxAgent("1.2.4")))), + ); + return gate === null + ? respond + : Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + }); + + it.effect("keeps a refreshed index when an overlapping disk read finishes later", () => { + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-disk-race-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + const registryCachePath = `${registryDirectory}/registry.json`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); - // A disk read that finishes after a concurrent refresh must not overwrite the refreshed index. - refreshGate = null; - upstreamVersion = "1.2.5"; const diskReadStarted = yield* Deferred.make(); const releaseDiskRead = yield* Deferred.make(); const delayedFileSystem: FileSystem.FileSystem = { @@ -1873,44 +1901,37 @@ describe("AcpRegistrySupport", () => { ) : fileSystem.readFileString(filePath, encoding), }; - const resolverDuringDiskRead = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, delayedFileSystem)); - const diskInspectFiber = yield* resolverDuringDiskRead + + const diskInspectFiber = yield* resolver .inspect(settings()) .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(diskReadStarted); - yield* resolverDuringDiskRead.refreshIndex(); + expect( + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }), + ).toBe(1); yield* Deferred.succeed(releaseDiskRead, undefined); + expect(yield* Fiber.join(diskInspectFiber)).toMatchObject({ status: "ready", - version: "1.2.5", + version: "1.2.4", }); - expect(yield* resolverDuringDiskRead.inspect(settings())).toMatchObject({ + expect(yield* resolver.inspect(settings())).toMatchObject({ status: "ready", - version: "1.2.5", + version: "1.2.4", }); }).pipe( Effect.scoped, Effect.provide( - layerResolver((request) => { - requests += 1; - const gate = refreshGate; - const respond = Effect.sync(() => - HttpClientResponse.fromWeb( - request, - new Response(makeRegistry(makeNpxAgent(upstreamVersion))), - ), - ); - return gate === null - ? respond - : Deferred.succeed(gate.started, undefined).pipe( - Effect.andThen(Deferred.await(gate.release)), - Effect.andThen(respond), - ); - }), + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(makeNpxAgent("1.2.4")))), + ), + ), ), ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index e0ed0792af9de..ed039bf88efb3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -525,9 +525,11 @@ export class AcpRegistryCatalog extends Context.Service< readonly prepare: ( input: AcpRegistryPrepareInput, ) => Effect.Effect; - readonly refreshIndex: (options?: { - readonly maxAgeMs?: number; - }) => Effect.Effect; + readonly refreshIndex: (options: { + readonly maxAgeMs: number; + readonly failureBackoffMs: number; + }) => Effect.Effect; + readonly invalidateIndex: () => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, environment?: NodeJS.ProcessEnv, @@ -691,10 +693,24 @@ 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; + // When the network last served index; unset until fetched, on fallback, or after invalidateIndex. + readonly fetchedAtMs: number | undefined; + // When a network fetch last failed; lets background max-age refreshes back off while offline. + readonly failedAtMs: number | undefined; + // Advances when a refresh finishes with an index (fetched or fallback) so concurrent callers coalesce. + readonly attemptRevision: number; + // Advances only when a network fetch succeeds and updates index. + readonly indexRevision: number; + } + const registryState = yield* Ref.make({ + index: undefined, + fetchedAtMs: undefined, + failedAtMs: undefined, + attemptRevision: 0, + indexRevision: 0, + }); const registrySemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. const installPermits = new Map(); @@ -948,31 +964,54 @@ 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* ( + observedAttemptRevision?: number, + ) { + const startRevision = + observedAttemptRevision ?? (yield* Ref.get(registryState)).attemptRevision; 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); + if (current.index !== undefined && current.attemptRevision !== startRevision) { + return { index: current.index, indexRevision: current.indexRevision }; + } - const { registry, fetched } = yield* fetchRegistry().pipe( - Effect.map((registry) => ({ registry, fetched: true })), + const result = yield* fetchRegistry().pipe( + Effect.map((index) => ({ index, refreshed: true })), Effect.catch((networkError) => Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + yield* Effect.logDebug("ACP Registry index refresh failed", { + reason: networkError.reason, + detail: networkError.detail, + }); // Prefer an already-loaded index over disk so a cache-write failure cannot regress it. - const inMemory = yield* Ref.get(registryRef); - if (inMemory !== undefined) return { registry: inMemory, fetched: false }; + const inMemory = (yield* Ref.get(registryState)).index; + if (inMemory !== undefined) return { index: inMemory, refreshed: false }; const cached = yield* readCachedRegistry; - if (Option.isSome(cached)) return { registry: cached.value, fetched: false }; + if (Option.isSome(cached)) return { index: cached.value, refreshed: false }; + yield* Ref.update(registryState, (state) => ({ ...state, failedAtMs: now })); return yield* 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 now = yield* Clock.currentTimeMillis; + const indexRevision = yield* Ref.modify(registryState, (state) => { + const nextIndexRevision = result.refreshed + ? state.indexRevision + 1 + : state.indexRevision; + return [ + nextIndexRevision, + { + index: result.index, + fetchedAtMs: result.refreshed ? now : undefined, + failedAtMs: result.refreshed ? undefined : now, + attemptRevision: state.attemptRevision + 1, + indexRevision: nextIndexRevision, + }, + ] as const; + }); + return { index: result.index, indexRevision }; }), ); }); @@ -980,37 +1019,56 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* ( maxAgeMs = REGISTRY_SEARCH_MAX_AGE_MS, ) { - const current = yield* Ref.get(registryRef); - const fetchedAtMs = yield* Ref.get(registryFetchedAtMs); + const state = 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 < maxAgeMs + state.index !== undefined && + state.fetchedAtMs !== undefined && + now >= state.fetchedAtMs && + now - state.fetchedAtMs < maxAgeMs ) { - return current; + return { index: state.index, indexRevision: state.indexRevision }; } - return yield* refreshRegistry(); + return yield* refreshRegistry(state.attemptRevision); }); const refreshIndex: AcpRegistryCatalog["Service"]["refreshIndex"] = Effect.fn( "AcpRegistryCatalog.refreshIndex", - )(function* (options) { - yield* options?.maxAgeMs === undefined ? refreshRegistry() : recentRegistry(options.maxAgeMs); + )(function* ({ maxAgeMs, failureBackoffMs }) { + const state = yield* Ref.get(registryState); + const now = yield* Clock.currentTimeMillis; + if ( + state.failedAtMs !== undefined && + now >= state.failedAtMs && + now - state.failedAtMs < failureBackoffMs + ) { + return state.indexRevision; + } + return (yield* recentRegistry(maxAgeMs)).indexRevision; + }); + + const invalidateIndex: AcpRegistryCatalog["Service"]["invalidateIndex"] = Effect.fn( + "AcpRegistryCatalog.invalidateIndex", + )(function* () { + yield* Ref.update(registryState, (state) => ({ + ...state, + fetchedAtMs: undefined, + failedAtMs: undefined, + })); }); 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(); + 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(registryRef, (latest) => - latest !== undefined ? ([latest, latest] as const) : ([cached.value, cached.value] as const), - ); + return yield* Ref.modify(registryState, (state) => { + const index = state.index ?? cached.value; + return [index, state.index !== undefined ? state : { ...state, index }] as const; + }); }); const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( @@ -1752,7 +1810,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 = registry.agents.flatMap((agent) => { const distribution = resolveAcpRegistryDistribution({ agent, @@ -1799,7 +1857,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") { @@ -2060,7 +2118,7 @@ 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; @@ -2168,6 +2226,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct search, prepare, refreshIndex, + invalidateIndex, inspect, resolve, uninstallManagedBinary, diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 5edff88623800..10d349b8bd8c5 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -54,7 +54,8 @@ const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { resolve: () => Effect.succeed(resolved), search: () => Effect.die("unused"), prepare: () => Effect.die("unused"), - refreshIndex: () => Effect.void, + refreshIndex: () => Effect.die("unused"), + invalidateIndex: () => Effect.die("unused"), 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 03dc23b543d0c..ca4a354547d2a 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -66,7 +66,8 @@ function catalogWithInspection( return { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), - refreshIndex: () => Effect.void, + refreshIndex: () => Effect.succeed(0), + invalidateIndex: () => Effect.void, inspect: () => Effect.succeed(inspection), resolve: () => Effect.die("unused resolve"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -1318,14 +1319,16 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = config: decodeSettings({ agentId: "test-agent" }), }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); - const waitForEnriched = () => + const waitForEnriched = (version: string) => instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.filter( + (snapshot) => snapshot.version === version && snapshot.nativeSessions !== undefined, + ), Stream.runHead, ); // Initial enrichment refreshes the disk-cached 1.0.0 index and installs 2.0.0. - const upgradedToV2 = yield* waitForEnriched().pipe( + const upgradedToV2 = yield* waitForEnriched("2.0.0").pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; @@ -1335,7 +1338,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = // Explicit cache invalidation refreshes past the in-memory reuse window and installs 3.0.0. latestVersion = "3.0.0"; - const upgradedToV3 = yield* waitForEnriched().pipe( + const upgradedToV3 = yield* waitForEnriched("3.0.0").pipe( Effect.forkScoped({ startImmediately: true }), ); yield* instance.invalidateCaches ?? Effect.void; @@ -1344,8 +1347,9 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = expect(second.version).toBe("3.0.0"); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); - // Disabled instances must not fetch the registry on cache invalidation. + // Disabled instances must not invalidate the shared registry freshness or fetch on refresh. const disabledRequestsBefore = registryRequests; + latestVersion = "4.0.0"; const disabled = yield* AcpRegistryDriver.create({ instanceId: ProviderInstanceId.make("acpRegistry_disabled"), displayName: "Disabled ACP", @@ -1354,6 +1358,8 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = config: decodeSettings({ agentId: "test-agent" }), }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); yield* disabled.invalidateCaches ?? Effect.void; + yield* disabled.snapshot.refresh; + yield* catalog.refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }); expect(registryRequests).toBe(disabledRequestsBefore); }), ); @@ -1366,13 +1372,13 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent("acp-driver-recover-"); let remoteVersion = "2.0.0"; let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = incompatibleRegistryTarget; let resolveAttempts = 0; - const restoredRefreshDone = yield* Deferred.make(); const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, toolsDir: path.join(directory, "tools"), @@ -1398,16 +1404,6 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { ); const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, - refreshIndex: (options) => - realCatalog - .refreshIndex(options) - .pipe( - Effect.tap(() => - remoteVersion === "3.0.0" - ? Deferred.succeed(restoredRefreshDone, undefined).pipe(Effect.asVoid) - : Effect.void, - ), - ), resolve: (settings, cwd, environment) => Effect.sync(() => { resolveAttempts += 1; @@ -1438,30 +1434,200 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { const unsupported = Option.getOrThrow(yield* Fiber.join(becameUnsupported)); expect(unsupported.status).toBe("error"); - // 2. Upstream restores a compatible 3.0.0; post-TTL refresh updates the index while keeping probe suppressed. - const attemptsBeforeRecovery = resolveAttempts; - remoteVersion = "3.0.0"; - remoteTarget = compatibleRegistryTarget; + // 2. Live updates on the uninstalled snapshot cannot flip it back to ready; a post-TTL refresh to another incompatible version publishes it without probing. + const attemptsWhileUnsupported = resolveAttempts; + remoteVersion = "2.1.0"; + const unsupportedSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil((snapshot) => !snapshot.installed && snapshot.version === "2.1.0"), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "model-a", + availableModels: [{ modelId: "model-a", name: "model-a" }], + }), + ); yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; - yield* Deferred.await(restoredRefreshDone); - expect(resolveAttempts).toBe(attemptsBeforeRecovery); + const duringUnsupported = yield* Fiber.join(unsupportedSnapshots); + expect( + duringUnsupported.every((snapshot) => !snapshot.installed && snapshot.status === "error"), + ).toBe(true); + expect(resolveAttempts).toBe(attemptsWhileUnsupported); - // 3. The next periodic refresh recovers and installs 3.0.0 without invalidateCaches. - const recovered = yield* instance.snapshot.streamChanges.pipe( - Stream.filter( + // 3. Upstream restores compatible 3.0.0; one post-TTL refresh clears the error before probing and installs 3.0.0. + remoteVersion = "3.0.0"; + remoteTarget = compatibleRegistryTarget; + const recoverySnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( (snapshot) => snapshot.installed && snapshot.version === "3.0.0" && snapshot.nativeSessions !== undefined, ), - Stream.runHead, + Stream.runCollect, Effect.forkScoped({ startImmediately: true }), ); + yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; - const ready = Option.getOrThrow(yield* Fiber.join(recovered)); + const snapshots = yield* Fiber.join(recoverySnapshots); + const recheckedIndex = snapshots.findIndex( + (snapshot) => + snapshot.installed && + snapshot.version === "3.0.0" && + snapshot.nativeSessions === undefined, + ); + expect(recheckedIndex).toBeGreaterThanOrEqual(0); + const ready = snapshots[snapshots.length - 1]!; + expect(recheckedIndex).toBeLessThan(snapshots.length - 1); expect(ready.status).toBe("ready"); - expect(resolveAttempts).toBeGreaterThan(attemptsBeforeRecovery); + expect(ready.version).toBe("3.0.0"); + expect(ready.nativeSessions).toBeDefined(); + expect(resolveAttempts).toBeGreaterThan(attemptsWhileUnsupported); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); + }), + ); + + it.effect( + "publishes cold and cached probes immediately without waiting for a slow registry refresh", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-slow-refresh-", + ); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + + let remoteVersion = "2.0.0"; + const initialGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + let gate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = initialGate; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ); + const activeGate = request.url === registryUrl ? gate : null; + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // On cold startup, the disk-cached 1.0.0 probe publishes before the slow 2.0.0 registry fetch finishes. + const coldReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const upgradedToV2 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(initialGate.started); + expect(Option.isSome(yield* Fiber.join(coldReady))).toBe(true); + + yield* Deferred.succeed(initialGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(upgradedToV2))).toBe(true); + + // A live-session update at +10m extends enrichmentCache past +16m while the registry index expires. + yield* TestClock.adjust("10 minutes"); + const liveUpdated = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "model-c")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "model-a", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-c", name: "model-c" }, + ], + }), + ); + expect(Option.isSome(yield* Fiber.join(liveUpdated))).toBe(true); + + // At +16m, the registry fetch blocks, yet the cached 2.0.0 probe publishes immediately before release. + remoteVersion = "3.0.0"; + const secondGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = secondGate; + const cachedPublished = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const upgradedToV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "3.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("6 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(secondGate.started); + expect(Option.isSome(yield* Fiber.join(cachedPublished))).toBe(true); + + yield* Deferred.succeed(secondGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(upgradedToV3))).toBe(true); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); }), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 5f2a70acbc5fa..d93b9d9439f8e 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -71,6 +71,8 @@ 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_INDEX_MAX_AGE_MS = 15 * 60 * 1_000; +const REGISTRY_FAILURE_BACKOFF_MS = 60 * 1_000; function acpRegistryProbeTtlMs(provider: ServerProvider): number { const discoveredModels = provider.models.filter((model) => !model.isCustom); @@ -704,9 +706,17 @@ export const AcpRegistryDriver: ProviderDriver 0; + const lastSeenIndexRevision = yield* Ref.make(0); + const refreshRegistryIndex = Effect.fn("AcpRegistryDriver.refreshRegistryIndex")(function* () { + return yield* catalog + .refreshIndex({ + maxAgeMs: REGISTRY_INDEX_MAX_AGE_MS, + failureBackoffMs: REGISTRY_FAILURE_BACKOFF_MS, + }) + .pipe(Effect.catch(() => Ref.get(lastSeenIndexRevision))); + }); const enrichmentCache = yield* Ref.make({ generation: 0, entry: null, @@ -793,9 +816,6 @@ export const AcpRegistryDriver: ProviderDriver buildInitialAcpRegistrySnapshot(readinessInput), checkProvider, - enrichSnapshot: Effect.fn("enrichSnapshot")(function ({ + enrichSnapshot: Effect.fn("enrichSnapshot")(function* ({ snapshot, getSnapshot, publishSnapshot, }) { - if (!snapshot.installed) { - return effectiveConfig.enabled && - effectiveConfig.source !== "local" && - effectiveConfig.agentId.length > 0 - ? catalog.refreshIndex({ maxAgeMs: PROBE_SUCCESS_TTL_MS }).pipe(Effect.ignore) - : Effect.void; - } - const publishEnrichment = ( - Option.isSome(runtimeCoordinator) + const runProbeAndPublish = (targetSnapshot: ServerProvider) => + (Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( effectiveConfig.source === "local" ? `local:${instanceId}` : effectiveConfig.agentId, - enrichProviderCached(snapshot), + enrichProviderCached(targetSnapshot), ) - : enrichProviderCached(snapshot).pipe(Effect.asSome) - ).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.void, - onSome: ({ provider, generation }) => - liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, + : enrichProviderCached(targetSnapshot).pipe(Effect.asSome) + ).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.void, + onSome: ({ provider, generation }) => + liveSnapshotSemaphore.withPermit( + Ref.get(enrichmentCache).pipe( + Effect.flatMap((current) => + current.generation === generation + ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) + : Effect.void, + ), ), ), - ), - }), - ), - ); - if (Option.isNone(runtimeCoordinator)) return publishEnrichment; + }), + ), + ); + const runWithLiveWatchers = (enrichment: Effect.Effect) => { + if (Option.isNone(runtimeCoordinator)) return enrichment; - const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( - instanceId, - ({ slashCommands, skills }) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - publishSnapshot({ - ...current, - slashCommands, - skills, - }), + const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( + instanceId, + ({ slashCommands, skills }) => + liveSnapshotSemaphore.withPermit( + getSnapshot.pipe( + Effect.flatMap((current) => + current.installed + ? publishSnapshot({ + ...current, + slashCommands, + skills, + }) + : Effect.void, + ), ), ), - ), - ); - const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( - instanceId, - (configuration) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => applyLiveConfiguration(current, configuration)), - Effect.tap(() => - Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => - Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - }), - ), - ), + ); + const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( + instanceId, + (configuration) => + liveSnapshotSemaphore.withPermit( + getSnapshot.pipe( + Effect.flatMap((current) => + current.installed + ? applyLiveConfiguration(current, configuration).pipe( + Effect.tap(() => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + }), + ), + ), + ), + ), + Effect.flatMap(publishSnapshot), + ) + : Effect.void, ), ), - Effect.flatMap(publishSnapshot), ), - ), - ); - const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( - instanceId, - (action) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - publishSnapshot( - applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)), + ); + const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( + instanceId, + (action) => + liveSnapshotSemaphore.withPermit( + getSnapshot.pipe( + Effect.flatMap((current) => + current.installed + ? publishSnapshot( + applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)), + ) + : Effect.void, ), ), ), + ); + return Effect.all( + [enrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction], + { + concurrency: "unbounded", + discard: true, + }, + ); + }; + const publishUninstalled = (rechecked: ServerProvider) => + liveSnapshotSemaphore.withPermit( + clearLiveState.pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen( + Equal.equals({ ...rechecked, checkedAt: snapshot.checkedAt }, snapshot) + ? Effect.void + : publishSnapshot(rechecked), + ), ), - ); - return Effect.all( - [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction], - { - concurrency: "unbounded", - discard: true, - }, - ); + ); + if (!snapshot.installed) { + if (!tracksRegistryIndex) return; + const revision = yield* refreshRegistryIndex(); + if (revision === (yield* Ref.get(lastSeenIndexRevision))) return; + yield* clearLiveState; + const rechecked = yield* checkProvider; + if (!rechecked.installed) { + yield* publishUninstalled(rechecked); + yield* Ref.set(lastSeenIndexRevision, revision); + return; + } + yield* liveSnapshotSemaphore.withPermit(publishSnapshot(rechecked)); + yield* Ref.set(lastSeenIndexRevision, revision); + yield* runWithLiveWatchers(runProbeAndPublish(rechecked)); + return; + } + const publishEnrichment = Effect.gen(function* () { + // Probe or restore cached models before awaiting the network so startup and refreshes stay fast. + yield* runProbeAndPublish(snapshot); + if (!tracksRegistryIndex) return; + const revision = yield* refreshRegistryIndex(); + if (revision === (yield* Ref.get(lastSeenIndexRevision))) return; + const rechecked = yield* checkProvider; + if (!rechecked.installed) { + yield* publishUninstalled(rechecked); + yield* Ref.set(lastSeenIndexRevision, revision); + return; + } + if (rechecked.version !== snapshot.version) { + yield* runProbeAndPublish(rechecked); + } + yield* Ref.set(lastSeenIndexRevision, revision); + }); + yield* runWithLiveWatchers(publishEnrichment); }), }).pipe( Effect.mapError( @@ -963,13 +1032,6 @@ export const AcpRegistryDriver: ProviderDriver 0 - ? catalog.refreshIndex().pipe(Effect.ignore) - : Effect.void, - ), + Effect.andThen(tracksRegistryIndex ? catalog.invalidateIndex() : Effect.void), ), orchestrationAdapter, textGeneration: makeUnsupportedTextGeneration(), From 4a82474ba6ee579c2c1785c1c3ac523a4e5672ba Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 09:29:37 +0000 Subject: [PATCH 07/28] fix(mobile): Refresh providers in Settings refetches models like web Mobile sent only reloadSecrets, so the server skipped invalidateModelCaches and an ACP Registry agent kept a fresh index for up to 15 minutes. Co-Authored-By: Claude Opus 5.5 --- .../features/settings/SettingsEnvironmentDetailRouteScreen.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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.")); From 56c642d1a0bf70aeef2412ff2c0ceb2eacea8f72 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 09:39:07 +0000 Subject: [PATCH 08/28] fix(acp-registry): harden refresh backoff, invalidation races, metadata updates, and skipped probes --- docs/user/providers-acp.md | 3 +- .../src/server/AcpRegistrySupport.test.ts | 245 ++++++++++++++++++ .../src/server/AcpRegistrySupport.ts | 72 +++-- .../src/server/driver.test.ts | 222 +++++++++++++++- .../src/server/driver.ts | 53 +++- 5 files changed, 567 insertions(+), 28 deletions(-) diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 50ac68d8dfa05..0fb3173c49640 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -47,7 +47,8 @@ connect through `app.t3.codes`, T3 Connect, or a relay. Agents install under `tools///` inside T3 home. T3 Code verifies SHA-256 when the Registry entry provides one; entries without a checksum retain the Registry's HTTPS distribution guarantee. T3 Code refreshes the Registry index in the background so installed agents pick up new Registry -versions; refreshing providers in **Settings → Providers** checks immediately. +versions. Refreshing providers in **Settings → Providers** clears cached data. An installed agent's +Registry check runs after its probe finishes. Registry `npx` and `uvx` packages use T3-owned npm prefixes and Python tool directories at the exact version published by the Registry. Their commands are available in a new server terminal for sign-in and direct use. Removing an agent's last provider instance removes T3-managed binary files diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 90a99f8f94e5a..44677d9468c8c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1060,6 +1060,251 @@ describe("AcpRegistrySupport", () => { ); }); + it.effect( + "backs off queued and subsequent background refreshes when uncached and offline while keeping prepare eligible", + () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + let online = false; + let registryRequests = 0; + let gate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-backoff-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; + + const firstGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = firstGate; + const firstRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstGate.started); + const queuedRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + + yield* Deferred.succeed(firstGate.release, undefined); + expect((yield* Fiber.join(firstRefresh)).reason).toBe("registry_unavailable"); + expect((yield* Fiber.join(queuedRefresh)).reason).toBe("registry_unavailable"); + expect(registryRequests).toBe(1); + + // Subsequent background refreshes during the backoff window fail fast without hitting the network. + gate = null; + yield* TestClock.adjust("59 seconds"); + expect((yield* resolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason).toBe( + "registry_unavailable", + ); + expect(registryRequests).toBe(1); + + // The first background retry after backoff expires fetches again and recovers. + online = true; + yield* TestClock.adjust("1 second"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(2); + + // Explicit prepare remains eligible to fetch immediately even during a cold offline backoff window. + const secondCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-backoff-prepare-", + }); + const secondResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: secondCacheDir, + toolsDir: `${secondCacheDir}/tools`, + registryUrl, + }); + online = false; + expect((yield* secondResolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason).toBe( + "registry_unavailable", + ); + expect(registryRequests).toBe(3); + + online = true; + expect( + (yield* secondResolver.prepare({ agentId: "missing-agent" }).pipe(Effect.flip)).reason, + ).toBe("agent_not_found"); + expect(registryRequests).toBe(4); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + registryRequests += 1; + const activeGate = gate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(agent)) + : new Response("unavailable", { status: 503 }), + ), + ); + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + }, + ); + + it.effect( + "does not mark a refresh fresh or backed off when invalidated after response receipt", + () => { + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, + }); + let upstream = makeNpxAgent("1.2.4"); + let online = true; + let registryRequests = 0; + let fetchGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-invalidate-race-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + const registryCachePath = `${registryDirectory}/registry.json`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); + + let writeGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + const gatedFileSystem: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => { + const activeGate = + writeGate !== null && filePath.startsWith(`${registryCachePath}.`) ? writeGate : null; + return activeGate === null + ? fileSystem.writeFileString(filePath, data, options) + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(fileSystem.writeFileString(filePath, data, options)), + ); + }, + }; + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, gatedFileSystem)); + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; + + // 1. Invalidate after HTTP response receipt (during writeRegistryCache) before cache publication. + const firstWriteGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + writeGate = firstWriteGate; + const firstRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstWriteGate.started); + expect(registryRequests).toBe(1); + yield* resolver.invalidateIndex(); + yield* Deferred.succeed(firstWriteGate.release, undefined); + + // The fetched index is kept as fallback, while freshness stays unset so the next refresh fetches. + expect(yield* Fiber.join(firstRefresh)).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); + + // 2. A post-invalidation caller queued behind an in-flight pre-invalidation fetch does not coalesce. + upstream = makeNpxAgent("1.2.5"); + const secondWriteGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + writeGate = secondWriteGate; + const secondRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(secondWriteGate.started); + expect(registryRequests).toBe(2); + + yield* resolver.invalidateIndex(); + upstream = makeNpxAgent("1.2.6"); + writeGate = null; + const queuedPostInvalidation = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(secondWriteGate.release, undefined); + + expect(yield* Fiber.join(secondRefresh)).toBe(2); + expect(yield* Fiber.join(queuedPostInvalidation)).toBe(3); + expect(registryRequests).toBe(3); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); + + // Attempts that started after invalidation still set freshness normally. + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(3); + + // 3. A failed refresh started before invalidation does not restore failure backoff. + yield* resolver.invalidateIndex(); + online = false; + const offlineGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = offlineGate; + const failedRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(offlineGate.started); + expect(registryRequests).toBe(4); + yield* resolver.invalidateIndex(); + yield* Deferred.succeed(offlineGate.release, undefined); + expect(yield* Fiber.join(failedRefresh)).toBe(3); + + online = true; + fetchGate = null; + upstream = makeNpxAgent("1.2.7"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); + expect(registryRequests).toBe(5); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + registryRequests += 1; + const activeGate = fetchGate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(upstream)) + : new Response("unavailable", { status: 503 }), + ), + ); + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + }, + ); + it.effect( "prepares the registry version despite an older PATH binary and permits explicit overrides", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index ed039bf88efb3..cde3c76f034b4 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -699,17 +699,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly fetchedAtMs: number | undefined; // When a network fetch last failed; lets background max-age refreshes back off while offline. readonly failedAtMs: number | undefined; + // Last network failure; lets background refreshes fail fast during backoff when uncached. + readonly lastFailure: AcpRegistryError | undefined; // Advances when a refresh finishes with an index (fetched or fallback) so concurrent callers coalesce. readonly attemptRevision: number; // Advances only when a network fetch succeeds and updates index. readonly indexRevision: number; + // Advances on invalidateIndex so an in-flight attempt started earlier cannot mark the cache fresh or backed off. + readonly invalidationGeneration: number; } const registryState = yield* Ref.make({ index: undefined, fetchedAtMs: undefined, failedAtMs: undefined, + lastFailure: undefined, attemptRevision: 0, indexRevision: 0, + invalidationGeneration: 0, }); const registrySemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. @@ -964,49 +970,78 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return registry; }); - const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* ( - observedAttemptRevision?: number, - ) { + const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { + readonly observedAttemptRevision?: number; + readonly failureBackoffMs?: number; + }) { const startRevision = - observedAttemptRevision ?? (yield* Ref.get(registryState)).attemptRevision; + options?.observedAttemptRevision ?? (yield* Ref.get(registryState)).attemptRevision; + const failureBackoffMs = options?.failureBackoffMs; return yield* registrySemaphore.withPermits(1)( Effect.gen(function* () { const current = yield* Ref.get(registryState); if (current.index !== undefined && current.attemptRevision !== startRevision) { return { index: current.index, indexRevision: current.indexRevision }; } + if (failureBackoffMs !== undefined && current.failedAtMs !== undefined) { + const now = yield* Clock.currentTimeMillis; + if (now >= current.failedAtMs && now - current.failedAtMs < failureBackoffMs) { + if (current.index !== undefined) { + return { index: current.index, indexRevision: current.indexRevision }; + } + if (current.lastFailure !== undefined) { + return yield* current.lastFailure; + } + } + } + const startInvalidationGeneration = current.invalidationGeneration; const result = yield* fetchRegistry().pipe( - Effect.map((index) => ({ index, refreshed: true })), + Effect.map((index) => ({ index, refreshed: true as const })), Effect.catch((networkError) => Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; yield* Effect.logDebug("ACP Registry index refresh failed", { reason: networkError.reason, - detail: networkError.detail, + stage: "fetch_registry", }); // 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 { index: inMemory, refreshed: false }; + if (inMemory !== undefined) { + return { index: inMemory, refreshed: false as const, failure: networkError }; + } const cached = yield* readCachedRegistry; - if (Option.isSome(cached)) return { index: cached.value, refreshed: false }; - yield* Ref.update(registryState, (state) => ({ ...state, failedAtMs: now })); + if (Option.isSome(cached)) { + return { index: cached.value, refreshed: false as const, failure: networkError }; + } + yield* Ref.update(registryState, (state) => + state.invalidationGeneration === startInvalidationGeneration + ? { ...state, failedAtMs: now, lastFailure: networkError } + : state, + ); return yield* networkError; }), ), ); const now = yield* Clock.currentTimeMillis; const indexRevision = yield* Ref.modify(registryState, (state) => { + const invalidatedDuringFetch = + state.invalidationGeneration !== startInvalidationGeneration; const nextIndexRevision = result.refreshed ? state.indexRevision + 1 : state.indexRevision; return [ nextIndexRevision, { + ...state, index: result.index, - fetchedAtMs: result.refreshed ? now : undefined, - failedAtMs: result.refreshed ? undefined : now, - attemptRevision: state.attemptRevision + 1, + fetchedAtMs: result.refreshed && !invalidatedDuringFetch ? now : undefined, + failedAtMs: !result.refreshed && !invalidatedDuringFetch ? now : undefined, + lastFailure: + !result.refreshed && !invalidatedDuringFetch ? result.failure : undefined, + attemptRevision: invalidatedDuringFetch + ? state.attemptRevision + : state.attemptRevision + 1, indexRevision: nextIndexRevision, }, ] as const; @@ -1018,6 +1053,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* ( maxAgeMs = REGISTRY_SEARCH_MAX_AGE_MS, + failureBackoffMs?: number, ) { const state = yield* Ref.get(registryState); const now = yield* Clock.currentTimeMillis; @@ -1030,7 +1066,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) { return { index: state.index, indexRevision: state.indexRevision }; } - return yield* refreshRegistry(state.attemptRevision); + return yield* refreshRegistry({ + observedAttemptRevision: state.attemptRevision, + ...(failureBackoffMs === undefined ? {} : { failureBackoffMs }), + }); }); const refreshIndex: AcpRegistryCatalog["Service"]["refreshIndex"] = Effect.fn( @@ -1043,9 +1082,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct now >= state.failedAtMs && now - state.failedAtMs < failureBackoffMs ) { - return state.indexRevision; + if (state.index !== undefined) return state.indexRevision; + if (state.lastFailure !== undefined) return yield* state.lastFailure; } - return (yield* recentRegistry(maxAgeMs)).indexRevision; + return (yield* recentRegistry(maxAgeMs, failureBackoffMs)).indexRevision; }); const invalidateIndex: AcpRegistryCatalog["Service"]["invalidateIndex"] = Effect.fn( @@ -1055,6 +1095,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ...state, fetchedAtMs: undefined, failedAtMs: undefined, + lastFailure: undefined, + invalidationGeneration: state.invalidationGeneration + 1, })); }); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index ca4a354547d2a..dce7264efdaa7 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -968,6 +968,7 @@ const registryUrl = "https://registry.test/registry.json"; const makeBinaryRegistry = ( version: string, target: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget, + options?: { readonly website?: string }, ) => JSON.stringify({ version: "1.0.0", @@ -977,6 +978,7 @@ const makeBinaryRegistry = ( name: "Test Agent", version, description: "Test binary agent", + ...(options?.website ? { website: options.website } : {}), distribution: { binary: { [target]: { @@ -990,7 +992,10 @@ const makeBinaryRegistry = ( }); // A disk-cached 1.0.0 index with its binary installed, as left behind by an earlier session. -const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* (prefix: string) { +const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* ( + prefix: string, + options?: { readonly website?: string }, +) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix }); @@ -1001,7 +1006,7 @@ const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); yield* fileSystem.writeFileString( path.join(directory, "acp-registry", "registry.json"), - makeBinaryRegistry("1.0.0"), + makeBinaryRegistry("1.0.0", compatibleRegistryTarget, options), ); const installedV1 = installedBinaryPath(path, directory, "1.0.0"); yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); @@ -1631,4 +1636,217 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); }), ); + + it.effect( + "publishes same-version metadata changes with cached enrichment and retries skipped version probes after a session ends", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-meta-session-", + { website: "https://example.test/v1" }, + ); + + let remoteVersion = "1.0.0"; + let remoteWebsite: string | undefined = "https://example.test/v1-updated"; + let registryRequests = 0; + let resolveAttempts = 0; + let onInspect: + | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) + | null = null; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + registryRequests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + makeBinaryRegistry( + remoteVersion, + compatibleRegistryTarget, + remoteWebsite ? { website: remoteWebsite } : undefined, + ), + ), + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(`#!/bin/sh\necho ${remoteVersion}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + realCatalog + .inspect(settings, environment) + .pipe( + Effect.tap((inspection) => + onInspect === null ? Effect.void : onInspect(inspection), + ), + ), + resolve: (settings, cwd, environment) => + Effect.sync(() => { + resolveAttempts += 1; + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // 1. Same-version metadata update publishes the new documentationUrl while preserving cached models, commands, and auth actions. + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "status" }], + skills: [], + }); + const authActionReady = yield* Deferred.make(); + const authWatcher = yield* coordinator + .watchUrlAuthAction(identity.instanceId, (action) => + action === null + ? Effect.void + : Deferred.succeed(authActionReady, undefined).pipe(Effect.asVoid), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + const authRequest = yield* coordinator + .requestUrlAuthentication(identity.instanceId, { + elicitationId: "auth-1", + url: "https://example.test/auth", + message: "Continue in your browser", + }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(authActionReady); + yield* Fiber.interrupt(authWatcher); + const updatedDocs = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v1-updated" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const withUpdatedDocs = Option.getOrThrow(yield* Fiber.join(updatedDocs)); + expect(withUpdatedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(withUpdatedDocs.slashCommands).toEqual([{ name: "status" }]); + expect(withUpdatedDocs.auth.action).toMatchObject({ + elicitationId: "auth-1", + url: "https://example.test/auth", + }); + const resolvesAfterDocsUpdate = resolveAttempts; + yield* Fiber.interrupt(authRequest); + + // Removing website clears setup.documentationUrl via the cached probe without re-probing. + remoteWebsite = undefined; + const clearedDocs = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === undefined && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("1 minute"); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + const withClearedDocs = Option.getOrThrow(yield* Fiber.join(clearedDocs)); + expect(withClearedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(resolveAttempts).toBe(resolvesAfterDocsUpdate); + + // 2. When a foreground session skips a version-change probe, lastSeenIndexRevision stays pending and the next refresh after the session ends runs it. + remoteVersion = "2.0.0"; + remoteWebsite = "https://example.test/v2"; + const sessionStarted = yield* Deferred.make(); + const releaseSession = yield* Deferred.make(); + const sessionFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(sessionStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseSession)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(sessionStarted); + + const firstV2Recheck = yield* Deferred.make(); + onInspect = (inspection) => + inspection.status === "ready" && inspection.version === "2.0.0" + ? Deferred.succeed(firstV2Recheck, undefined).pipe(Effect.asVoid) + : Effect.void; + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(firstV2Recheck); + + // A second refresh while the session is still active rechecks v2 again because the skipped probe kept the revision pending. + let v2InspectsDuringSecondRefresh = 0; + const secondRefreshRechecked = yield* Deferred.make(); + onInspect = (inspection) => + inspection.status === "ready" && inspection.version === "2.0.0" + ? Effect.sync(() => { + v2InspectsDuringSecondRefresh += 1; + return v2InspectsDuringSecondRefresh; + }).pipe( + Effect.flatMap((count) => + count >= 2 + ? Deferred.succeed(secondRefreshRechecked, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ) + : Effect.void; + yield* instance.snapshot.refresh; + yield* Deferred.await(secondRefreshRechecked); + expect(resolveAttempts).toBe(resolvesAfterDocsUpdate); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(false); + + // Once the session ends, the next refresh runs the pending v2 probe without needing another registry fetch. + onInspect = null; + yield* Deferred.succeed(releaseSession, undefined); + yield* Fiber.join(sessionFiber); + const requestsBeforeRecovery = registryRequests; + const upgradedToV2 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v2" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const recovered = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); + expect(recovered.version).toBe("2.0.0"); + expect(registryRequests).toBe(requestsBeforeRecovery); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index d93b9d9439f8e..856d1949d5709 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -433,6 +433,21 @@ function applyAcpRegistryUrlAuthAction( }; } +function applyRegistryReadinessMetadata( + provider: ServerProvider, + baseSnapshot: ServerProvider, +): ServerProvider { + const documentationUrl = baseSnapshot.setup?.documentationUrl; + if (provider.setup === undefined || provider.setup.documentationUrl === documentationUrl) { + return provider; + } + const { documentationUrl: _previous, ...setup } = provider.setup; + return { + ...provider, + setup: documentationUrl === undefined ? setup : { ...setup, documentationUrl }, + }; +} + const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")( function* (input: SnapshotIdentity & { readonly settings: AcpRegistrySettings }) { const checkedAt = DateTime.formatIso(yield* DateTime.now); @@ -812,7 +827,10 @@ export const AcpRegistryDriver: ProviderDriver Effect.void, + onNone: () => Effect.succeed(false), onSome: ({ provider, generation }) => liveSnapshotSemaphore.withPermit( Ref.get(enrichmentCache).pipe( Effect.flatMap((current) => current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, + ? withLiveRuntimeState(provider).pipe( + Effect.flatMap(publishSnapshot), + Effect.as(true), + ) + : Effect.succeed(false), ), ), ), @@ -973,13 +994,19 @@ export const AcpRegistryDriver: ProviderDriver + published ? Ref.set(lastSeenIndexRevision, revision) : Effect.void, + ), + Effect.asVoid, + ), + ); return; } const publishEnrichment = Effect.gen(function* () { // Probe or restore cached models before awaiting the network so startup and refreshes stay fast. - yield* runProbeAndPublish(snapshot); + const initialPublished = yield* runProbeAndPublish(snapshot); if (!tracksRegistryIndex) return; const revision = yield* refreshRegistryIndex(); if (revision === (yield* Ref.get(lastSeenIndexRevision))) return; @@ -989,10 +1016,16 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 10:17:16 +0000 Subject: [PATCH 09/28] fix(acp-registry): track launch identity, clear stale live state on upgrade, and gate revision on applied publishes --- docs/user/providers-acp.md | 9 +- .../src/server/AcpRegistrySupport.test.ts | 234 +++++++++-- .../src/server/AcpRegistrySupport.ts | 115 +++++- .../src/server/driver.test.ts | 246 ++++++++++-- .../src/server/driver.ts | 380 +++++++++++++----- .../src/server/managedProvider.test.ts | 11 +- .../src/server/managedProvider.ts | 62 +-- 7 files changed, 845 insertions(+), 212 deletions(-) diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 0fb3173c49640..b00e5585745c5 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -46,14 +46,17 @@ connect through `app.t3.codes`, T3 Connect, or a relay. Agents install under `tools///` inside T3 home. T3 Code verifies SHA-256 when the Registry entry provides one; entries without a checksum retain the Registry's HTTPS distribution guarantee. -T3 Code refreshes the Registry index in the background so installed agents pick up new Registry -versions. Refreshing providers in **Settings → Providers** clears cached data. An installed agent's -Registry check runs after its probe finishes. Registry `npx` and `uvx` packages use T3-owned npm prefixes and Python tool directories at the exact version published by the Registry. Their commands are available in a new server terminal for 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 refreshes the Registry index in the background and automatically installs new versions of +enabled Registry agents alongside earlier versions, deferring background updates while that agent is +starting a session. Refreshing providers (in **Settings → Providers** on web and desktop, or +**Refresh providers** in environment settings on mobile) requests a fresh Registry check once the +installed agent finishes its status check. + ## 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/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 44677d9468c8c..a6e1d3efbb6e1 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1002,15 +1002,20 @@ describe("AcpRegistrySupport", () => { expect(registryRequests).toBe(1); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); + // Refreshing after maxAgeMs when upstream is unchanged renews freshness without advancing indexRevision. + yield* TestClock.adjust("15 minutes"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(2); + upstream = makeBinaryAgent("1.2.5"); yield* TestClock.adjust("14 minutes"); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); - expect(registryRequests).toBe(1); + expect(registryRequests).toBe(2); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); yield* TestClock.adjust("1 minute"); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(2); - expect(registryRequests).toBe(2); + expect(registryRequests).toBe(3); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); // Explicit invalidation clears the reuse window without discarding the in-memory index. @@ -1018,7 +1023,7 @@ describe("AcpRegistrySupport", () => { yield* resolver.invalidateIndex(); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); - expect(registryRequests).toBe(3); + expect(registryRequests).toBe(4); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); // An offline refresh prefers the in-memory index over a stale disk cache and backs off background retries. @@ -1029,18 +1034,18 @@ describe("AcpRegistrySupport", () => { online = false; yield* resolver.invalidateIndex(); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); - expect(registryRequests).toBe(4); + expect(registryRequests).toBe(5); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); online = true; upstream = makeBinaryAgent("1.2.7"); yield* TestClock.adjust("59 seconds"); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); - expect(registryRequests).toBe(4); + expect(registryRequests).toBe(5); yield* TestClock.adjust("1 second"); expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); - expect(registryRequests).toBe(5); + expect(registryRequests).toBe(6); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); }).pipe( Effect.scoped, @@ -1064,6 +1069,16 @@ describe("AcpRegistrySupport", () => { "backs off queued and subsequent background refreshes when uncached and offline while keeping prepare eligible", () => { const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + const newAgent = { + ...makeAgent({ + binary: { + "darwin-aarch64": { archive: archiveUrl, cmd: "new-agent" }, + }, + }), + id: "new-agent", + name: "New Agent", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + let upstreamAgents: ReadonlyArray = [agent]; let online = false; let registryRequests = 0; let gate: { @@ -1100,52 +1115,125 @@ describe("AcpRegistrySupport", () => { expect((yield* Fiber.join(queuedRefresh)).reason).toBe("registry_unavailable"); expect(registryRequests).toBe(1); - // Subsequent background refreshes during the backoff window fail fast without hitting the network. - gate = null; + // Subsequent background refreshes during the backoff window fail fast before acquiring the semaphore. yield* TestClock.adjust("59 seconds"); + const prepareHoldGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = prepareHoldGate; + online = true; + const holdingPrepare = yield* resolver + .prepare({ agentId: "missing-agent" }) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(prepareHoldGate.started); expect((yield* resolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason).toBe( "registry_unavailable", ); - expect(registryRequests).toBe(1); + expect(holdingPrepare.pollUnsafe()).toBeUndefined(); + expect(registryRequests).toBe(2); + yield* Deferred.succeed(prepareHoldGate.release, undefined); + expect((yield* Fiber.join(holdingPrepare)).reason).toBe("agent_not_found"); - // The first background retry after backoff expires fetches again and recovers. + // Clock moving backwards below failedAtMs disables backoff suppression on both fast and semaphore paths. + const clockBackDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-clock-back-", + }); + const clockBackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: clockBackDir, + toolsDir: `${clockBackDir}/tools`, + registryUrl, + }); + gate = null; + online = false; + yield* TestClock.adjust("10 minutes"); + expect( + (yield* clockBackResolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason, + ).toBe("registry_unavailable"); + const requestsAfterClockFailure = registryRequests; online = true; - yield* TestClock.adjust("1 second"); - expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); - expect(registryRequests).toBe(2); + yield* TestClock.setTime(0); + expect(yield* clockBackResolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(requestsAfterClockFailure + 1); - // Explicit prepare remains eligible to fetch immediately even during a cold offline backoff window. - const secondCacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-cold-backoff-prepare-", + // Concurrent cold uncached inspect() calls coalesce behind one failing network fetch. + const coldInspectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-inspect-coalesce-", }); - const secondResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: secondCacheDir, - toolsDir: `${secondCacheDir}/tools`, + const coldInspectResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldInspectDir, + toolsDir: `${coldInspectDir}/tools`, registryUrl, }); + const coldInspectGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = coldInspectGate; online = false; - expect((yield* secondResolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason).toBe( - "registry_unavailable", + const requestsBeforeColdInspect = registryRequests; + const firstInspect = yield* coldInspectResolver + .inspect(settings()) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldInspectGate.started); + const secondInspect = yield* coldInspectResolver + .inspect(settings()) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(coldInspectGate.release, undefined); + expect((yield* Fiber.join(firstInspect)).reason).toBe("registry_unavailable"); + expect((yield* Fiber.join(secondInspect)).reason).toBe("registry_unavailable"); + expect(registryRequests).toBe(requestsBeforeColdInspect + 1); + + // A queued prepare() must not reuse a cached fallback from a failing background refresh. + const queuedPrepareDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-queued-prepare-", + }); + yield* fileSystem.makeDirectory(`${queuedPrepareDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${queuedPrepareDir}/acp-registry/registry.json`, + makeRegistry({ ...agent, id: "older-agent" }), ); - expect(registryRequests).toBe(3); - + const queuedPrepareResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: queuedPrepareDir, + toolsDir: `${queuedPrepareDir}/tools`, + registryUrl, + }); + const fallbackGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = fallbackGate; + online = false; + upstreamAgents = [agent, newAgent]; + const requestsBeforeQueuedPrepare = registryRequests; + const failingBackground = yield* queuedPrepareResolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fallbackGate.started); + const queuedPrepare = yield* queuedPrepareResolver + .prepare({ agentId: newAgent.id }) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + expect(queuedPrepare.pollUnsafe()).toBeUndefined(); + // Flip online after the background refresh already captured 503 so only the queued prepare retries online. online = true; - expect( - (yield* secondResolver.prepare({ agentId: "missing-agent" }).pipe(Effect.flip)).reason, - ).toBe("agent_not_found"); - expect(registryRequests).toBe(4); + gate = null; + yield* Deferred.succeed(fallbackGate.release, undefined); + expect(yield* Fiber.join(failingBackground)).toBe(0); + // Reaching unsupported_distribution (instead of agent_not_found from older-agent) proves prepare retried. + expect((yield* Fiber.join(queuedPrepare)).reason).toBe("unsupported_distribution"); + expect(registryRequests).toBe(requestsBeforeQueuedPrepare + 2); }).pipe( Effect.scoped, Effect.provide( layerResolver((request) => { registryRequests += 1; const activeGate = gate; + const shouldSucceed = online; + const body = JSON.stringify({ version: "1.0.0", agents: upstreamAgents }); const respond = Effect.sync(() => HttpClientResponse.fromWeb( request, - online - ? new Response(makeRegistry(agent)) - : new Response("unavailable", { status: 503 }), + shouldSucceed ? new Response(body) : new Response("unavailable", { status: 503 }), ), ); return activeGate === null @@ -1245,6 +1333,7 @@ describe("AcpRegistrySupport", () => { const queuedPostInvalidation = yield* resolver .refreshIndex(refreshOptions) .pipe(Effect.forkScoped({ startImmediately: true })); + expect(queuedPostInvalidation.pollUnsafe()).toBeUndefined(); yield* Deferred.succeed(secondWriteGate.release, undefined); expect(yield* Fiber.join(secondRefresh)).toBe(2); @@ -1279,6 +1368,91 @@ describe("AcpRegistrySupport", () => { expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); expect(registryRequests).toBe(5); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); + + // 4. An uncached cold failure started before invalidation also does not record backoff. + const coldCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-invalidate-race-", + }); + const coldResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldCacheDir, + toolsDir: `${coldCacheDir}/tools`, + registryUrl, + }); + online = false; + const coldOfflineGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = coldOfflineGate; + const coldFailedRefresh = yield* coldResolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldOfflineGate.started); + yield* coldResolver.invalidateIndex(); + yield* Deferred.succeed(coldOfflineGate.release, undefined); + expect((yield* Fiber.join(coldFailedRefresh)).reason).toBe("registry_unavailable"); + + online = true; + fetchGate = null; + expect(yield* coldResolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(7); + + // 5. Same-version package swaps change launchIdentity while documentation-only updates keep it identical. + const packageSwapDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-launch-identity-", + }); + const swapResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: packageSwapDir, + toolsDir: `${packageSwapDir}/tools`, + registryUrl, + }); + const toolchain = yield* makeFakeNpmToolchain(packageSwapDir); + upstream = { + ...makeAgent({ npx: { package: "@example/old@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-a", + }; + yield* swapResolver.refreshIndex(refreshOptions); + const oldPackageInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + expect(oldPackageInspection).toMatchObject({ + status: "ready", + version: "1.0.0", + documentationUrl: "https://example.test/docs-a", + }); + + upstream = { + ...makeAgent({ npx: { package: "@example/new@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-a", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const newPackageInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + expect(newPackageInspection).toMatchObject({ status: "ready", version: "1.0.0" }); + expect( + oldPackageInspection.status === "ready" && + newPackageInspection.status === "ready" && + oldPackageInspection.launchIdentity !== newPackageInspection.launchIdentity, + ).toBe(true); + + upstream = { + ...makeAgent({ npx: { package: "@example/new@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-b", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const docsOnlyInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + expect(docsOnlyInspection).toMatchObject({ + status: "ready", + version: "1.0.0", + documentationUrl: "https://example.test/docs-b", + }); + expect( + newPackageInspection.status === "ready" && + docsOnlyInspection.status === "ready" && + newPackageInspection.launchIdentity === docsOnlyInspection.launchIdentity, + ).toBe(true); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index cde3c76f034b4..0c36beca6c6bf 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -26,6 +26,7 @@ import * as Duration from "effect/Duration"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -513,6 +514,7 @@ export type AcpRegistryInspection = readonly agentId: string; readonly version: string | null; readonly distribution: AcpRegistryDistributionKind | "local"; + readonly launchIdentity?: string; readonly documentationUrl?: string; }; @@ -580,6 +582,58 @@ 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).sort(([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, + }); +} + +type RegistryFetchFailureStage = + | "invalid_url" + | "http_request" + | "request_timeout" + | "response_read" + | "response_timeout" + | "response_too_large" + | "invalid_utf8" + | "invalid_json" + | "invalid_index" + | "unknown"; + +function classifyRegistryFetchFailure(error: AcpRegistryError): RegistryFetchFailureStage { + if (error.detail.startsWith("ACP Registry index URL must use HTTPS.")) return "invalid_url"; + if (error.detail.startsWith("Timed out fetching ACP Registry index.")) return "request_timeout"; + if (error.detail.startsWith("Could not fetch ACP Registry index from ")) return "http_request"; + if (error.detail.startsWith("Timed out reading ACP Registry response body.")) { + return "response_timeout"; + } + if (error.detail.startsWith("Could not read ACP Registry response body.")) return "response_read"; + if (error.detail.startsWith("ACP Registry index exceeds ")) return "response_too_large"; + if (error.detail.startsWith("ACP Registry index is not valid UTF-8.")) return "invalid_utf8"; + if (error.detail.startsWith("ACP Registry returned invalid JSON.")) return "invalid_json"; + if (error.detail.startsWith("ACP Registry returned an invalid index.")) return "invalid_index"; + return "unknown"; +} + function isAlreadyExists(error: PlatformError.PlatformError): boolean { return error.reason._tag === "AlreadyExists"; } @@ -699,11 +753,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly fetchedAtMs: number | undefined; // When a network fetch last failed; lets background max-age refreshes back off while offline. readonly failedAtMs: number | undefined; - // Last network failure; lets background refreshes fail fast during backoff when uncached. + // Last network failure; lets coalesced or backed-off callers fail fast when uncached. readonly lastFailure: AcpRegistryError | undefined; - // Advances when a refresh finishes with an index (fetched or fallback) so concurrent callers coalesce. + // Advances only on a successful non-invalidated network fetch; shared by all queued callers. + readonly fetchRevision: number; + // Advances on any completed non-invalidated refresh attempt (fetch, fallback, or uncached failure). readonly attemptRevision: number; - // Advances only when a network fetch succeeds and updates index. + // Advances only when a network fetch succeeds with a different index than the previous one. readonly indexRevision: number; // Advances on invalidateIndex so an in-flight attempt started earlier cannot mark the cache fresh or backed off. readonly invalidationGeneration: number; @@ -713,6 +769,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct fetchedAtMs: undefined, failedAtMs: undefined, lastFailure: undefined, + fetchRevision: 0, attemptRevision: 0, indexRevision: 0, invalidationGeneration: 0, @@ -971,18 +1028,34 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { + readonly observedFetchRevision?: number; readonly observedAttemptRevision?: number; readonly failureBackoffMs?: number; + readonly coalesceFailure?: boolean; }) { - const startRevision = - options?.observedAttemptRevision ?? (yield* Ref.get(registryState)).attemptRevision; + const initialState = yield* Ref.get(registryState); + const startFetchRevision = options?.observedFetchRevision ?? initialState.fetchRevision; + const startAttemptRevision = options?.observedAttemptRevision ?? initialState.attemptRevision; const failureBackoffMs = options?.failureBackoffMs; + const coalesceFailure = options?.coalesceFailure ?? failureBackoffMs !== undefined; return yield* registrySemaphore.withPermits(1)( Effect.gen(function* () { const current = yield* Ref.get(registryState); - if (current.index !== undefined && current.attemptRevision !== startRevision) { + if ( + current.index !== undefined && + (current.fetchRevision !== startFetchRevision || + (failureBackoffMs !== undefined && current.attemptRevision !== startAttemptRevision)) + ) { return { index: current.index, indexRevision: current.indexRevision }; } + if ( + coalesceFailure && + current.index === undefined && + current.attemptRevision !== startAttemptRevision && + current.lastFailure !== undefined + ) { + return yield* current.lastFailure; + } if (failureBackoffMs !== undefined && current.failedAtMs !== undefined) { const now = yield* Clock.currentTimeMillis; if (now >= current.failedAtMs && now - current.failedAtMs < failureBackoffMs) { @@ -1003,7 +1076,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const now = yield* Clock.currentTimeMillis; yield* Effect.logDebug("ACP Registry index refresh failed", { reason: networkError.reason, - stage: "fetch_registry", + stage: classifyRegistryFetchFailure(networkError), }); // Prefer an already-loaded index over disk so a cache-write failure cannot regress it. const inMemory = (yield* Ref.get(registryState)).index; @@ -1016,7 +1089,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } yield* Ref.update(registryState, (state) => state.invalidationGeneration === startInvalidationGeneration - ? { ...state, failedAtMs: now, lastFailure: networkError } + ? { + ...state, + failedAtMs: now, + lastFailure: networkError, + attemptRevision: state.attemptRevision + 1, + } : state, ); return yield* networkError; @@ -1027,9 +1105,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const indexRevision = yield* Ref.modify(registryState, (state) => { const invalidatedDuringFetch = state.invalidationGeneration !== startInvalidationGeneration; - const nextIndexRevision = result.refreshed - ? state.indexRevision + 1 - : state.indexRevision; + const indexChanged = + result.refreshed && + (state.index === undefined || !Equal.equals(result.index, state.index)); + const nextIndexRevision = indexChanged ? state.indexRevision + 1 : state.indexRevision; return [ nextIndexRevision, { @@ -1039,6 +1118,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct failedAtMs: !result.refreshed && !invalidatedDuringFetch ? now : undefined, lastFailure: !result.refreshed && !invalidatedDuringFetch ? result.failure : undefined, + fetchRevision: + result.refreshed && !invalidatedDuringFetch + ? state.fetchRevision + 1 + : state.fetchRevision, attemptRevision: invalidatedDuringFetch ? state.attemptRevision : state.attemptRevision + 1, @@ -1067,6 +1150,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return { index: state.index, indexRevision: state.indexRevision }; } return yield* refreshRegistry({ + observedFetchRevision: state.fetchRevision, observedAttemptRevision: state.attemptRevision, ...(failureBackoffMs === undefined ? {} : { failureBackoffMs }), }); @@ -1105,7 +1189,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (current !== undefined) return current; const cached = yield* readCachedRegistry; - if (Option.isNone(cached)) return (yield* refreshRegistry()).index; + if (Option.isNone(cached)) return (yield* refreshRegistry({ coalesceFailure: true })).index; // Publish without waiting on an in-flight refresh, while letting a completed refresh win. return yield* Ref.modify(registryState, (state) => { const index = state.index ?? cached.value; @@ -1975,6 +2059,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: null, distribution: distribution.kind, + launchIdentity: registryLaunchIdentity({ + version: null, + distribution, + commandOverride, + }), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -2024,6 +2113,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: "binary", + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), ...(documentationUrl ? { documentationUrl } : {}), } as const; }), @@ -2039,6 +2129,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: distribution.kind, + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index dce7264efdaa7..b416a6d482bab 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -805,11 +805,17 @@ describe("acpRegistrySnapshotReadiness", () => { describe("acpRegistryEnrichmentCache", () => { it("reuses a local probe until expiry even when inspection has no version", () => { - const entry = { provider: providerWithModels([], null), expiresAt: 1_000 }; + const entry = { + provider: providerWithModels([], null), + expiresAt: 1_000, + launchIdentity: "launch-a", + }; expect(isAcpRegistryCacheValid(entry, null, true, 999)).toBe(true); expect(isAcpRegistryCacheValid(entry, null, true, 1_000)).toBe(false); expect(isAcpRegistryCacheValid(entry, "2.0.0", false, 999)).toBe(false); expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999)).toBe(true); + expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999, "launch-a")).toBe(true); + expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999, "launch-b")).toBe(false); }); const settledConfiguration = { models: [ @@ -968,7 +974,11 @@ const registryUrl = "https://registry.test/registry.json"; const makeBinaryRegistry = ( version: string, target: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget, - options?: { readonly website?: string }, + options?: { + readonly website?: string; + readonly archiveSuffix?: string; + readonly extraAgentVersion?: string; + }, ) => JSON.stringify({ version: "1.0.0", @@ -982,12 +992,30 @@ const makeBinaryRegistry = ( distribution: { binary: { [target]: { - archive: `https://registry.test/test-agent-${version}.bin`, + archive: `https://registry.test/test-agent-${version}${options?.archiveSuffix ?? ""}.bin`, cmd: "./bin/test-agent", }, }, }, }, + ...(options?.extraAgentVersion + ? [ + { + id: "other-agent", + name: "Other Agent", + version: options.extraAgentVersion, + description: "Unrelated agent", + distribution: { + binary: { + [target]: { + archive: `https://registry.test/other-agent-${options.extraAgentVersion}.bin`, + cmd: "./bin/other-agent", + }, + }, + }, + }, + ] + : []), ], }); @@ -1384,6 +1412,8 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { let remoteVersion = "2.0.0"; let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = incompatibleRegistryTarget; let resolveAttempts = 0; + let inspectCount = 0; + let onRefreshDone: Effect.Effect = Effect.void; const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, toolsDir: path.join(directory, "tools"), @@ -1409,6 +1439,12 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { ); const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCount += 1; + }).pipe(Effect.andThen(() => realCatalog.inspect(settings, environment))), + refreshIndex: (options) => + realCatalog.refreshIndex(options).pipe(Effect.tap(() => onRefreshDone)), resolve: (settings, cwd, environment) => Effect.sync(() => { resolveAttempts += 1; @@ -1439,7 +1475,23 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { const unsupported = Option.getOrThrow(yield* Fiber.join(becameUnsupported)); expect(unsupported.status).toBe("error"); - // 2. Live updates on the uninstalled snapshot cannot flip it back to ready; a post-TTL refresh to another incompatible version publishes it without probing. + // Same-revision refresh while uninstalled returns early without re-running inspect(). + const sameRevisionRefreshDone = yield* Deferred.make(); + onRefreshDone = Deferred.succeed(sameRevisionRefreshDone, undefined).pipe(Effect.asVoid); + const inspectsBeforeSameRevision = inspectCount; + yield* instance.snapshot.refresh; + yield* Deferred.await(sameRevisionRefreshDone); + // A follow-up refresh synchronizes past the previous enrichment fiber's synchronous early return. + const nextRefreshDone = yield* Deferred.make(); + onRefreshDone = Deferred.succeed(nextRefreshDone, undefined).pipe(Effect.asVoid); + yield* instance.snapshot.refresh; + yield* Deferred.await(nextRefreshDone); + onRefreshDone = Effect.void; + // 2 refreshes × (checkProvider + auth.refreshMethods), with 0 enrichment rechecks. + expect(inspectCount).toBe(inspectsBeforeSameRevision + 4); + + // 2. Live updates (config, commands, URL auth action) on the uninstalled snapshot cannot flip or leak into it; + // a post-TTL refresh to another incompatible version publishes it without probing. const attemptsWhileUnsupported = resolveAttempts; remoteVersion = "2.1.0"; const unsupportedSnapshots = yield* instance.snapshot.streamChanges.pipe( @@ -1450,19 +1502,40 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* coordinator.publishLiveConfiguration( identity.instanceId, normalizeAcpRegistryLiveConfiguration([], undefined, { - currentModelId: "model-a", - availableModels: [{ modelId: "model-a", name: "model-a" }], + currentModelId: "stale-model", + availableModels: [ + { modelId: "stale-model", name: "stale-model" }, + { modelId: "stale-other", name: "stale-other" }, + ], }), ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "stale-cmd" }], + skills: [], + }); + const authRequestWhileUnsupported = yield* coordinator + .requestUrlAuthentication(identity.instanceId, { + elicitationId: "uninstalled-auth", + url: "https://example.test/uninstalled-auth", + message: "Continue in your browser", + }) + .pipe(Effect.forkScoped({ startImmediately: true })); yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; const duringUnsupported = yield* Fiber.join(unsupportedSnapshots); expect( - duringUnsupported.every((snapshot) => !snapshot.installed && snapshot.status === "error"), + duringUnsupported.every( + (snapshot) => + !snapshot.installed && + snapshot.status === "error" && + snapshot.slashCommands.length === 0 && + snapshot.auth.action === undefined, + ), ).toBe(true); expect(resolveAttempts).toBe(attemptsWhileUnsupported); + yield* Fiber.interrupt(authRequestWhileUnsupported); - // 3. Upstream restores compatible 3.0.0; one post-TTL refresh clears the error before probing and installs 3.0.0. + // 3. Upstream restores compatible 3.0.0; one post-TTL refresh clears the error and stale live state before probing and installs 3.0.0. remoteVersion = "3.0.0"; remoteTarget = compatibleRegistryTarget; const recoverySnapshots = yield* instance.snapshot.streamChanges.pipe( @@ -1490,6 +1563,8 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { expect(ready.status).toBe("ready"); expect(ready.version).toBe("3.0.0"); expect(ready.nativeSessions).toBeDefined(); + expect(ready.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(ready.slashCommands).toEqual([]); expect(resolveAttempts).toBeGreaterThan(attemptsWhileUnsupported); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); }), @@ -1638,24 +1713,42 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { ); it.effect( - "publishes same-version metadata changes with cached enrichment and retries skipped version probes after a session ends", + "publishes same-version metadata updates without re-probing, re-probes same-version launch swaps, clears stale live state on upgrade, and retries skipped probes", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( "acp-driver-meta-session-", { website: "https://example.test/v1" }, ); let remoteVersion = "1.0.0"; - let remoteWebsite: string | undefined = "https://example.test/v1-updated"; + let remoteWebsite: string | undefined = "https://example.test/v1"; + let remoteArchiveSuffix = ""; + let remoteExtraAgentVersion: string | undefined = undefined; let registryRequests = 0; let resolveAttempts = 0; let onInspect: | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) | null = null; + let onBackgroundProbeOutcome: ((skipped: boolean) => Effect.Effect) | null = null; + let onRefreshIndex: Effect.Effect = Effect.void; + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + runBackgroundProbe: (agentId, effect) => + baseCoordinator + .runBackgroundProbe(agentId, effect) + .pipe( + Effect.tap((outcome) => + onBackgroundProbeOutcome === null + ? Effect.void + : onBackgroundProbeOutcome(Option.isNone(outcome)), + ), + ), + }; const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, toolsDir: path.join(directory, "tools"), @@ -1672,11 +1765,13 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { HttpClientResponse.fromWeb( request, new Response( - makeBinaryRegistry( - remoteVersion, - compatibleRegistryTarget, - remoteWebsite ? { website: remoteWebsite } : undefined, - ), + makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + ...(remoteWebsite ? { website: remoteWebsite } : {}), + ...(remoteArchiveSuffix ? { archiveSuffix: remoteArchiveSuffix } : {}), + ...(remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : {}), + }), ), ), ); @@ -1700,6 +1795,8 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { onInspect === null ? Effect.void : onInspect(inspection), ), ), + refreshIndex: (options) => + realCatalog.refreshIndex(options).pipe(Effect.tap(() => onRefreshIndex)), resolve: (settings, cwd, environment) => Effect.sync(() => { resolveAttempts += 1; @@ -1718,9 +1815,30 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { enabled: true, environment: [], config: decodeSettings({ agentId: "test-agent" }), - }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + + // Prime the 1.0.0 probe cache first so subsequent metadata-only refreshes can assert zero re-probes. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v1" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + const resolvesAfterInitialProbe = resolveAttempts; - // 1. Same-version metadata update publishes the new documentationUrl while preserving cached models, commands, and auth actions. + // 1. Same-version metadata update publishes the new documentationUrl while preserving cached models, commands, and auth actions without re-probing. yield* coordinator.publishAvailableCommands(identity.instanceId, { slashCommands: [{ name: "status" }], skills: [], @@ -1742,6 +1860,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(authActionReady); yield* Fiber.interrupt(authWatcher); + remoteWebsite = "https://example.test/v1-updated"; const updatedDocs = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => @@ -1752,6 +1871,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + yield* catalog.invalidateIndex(); yield* instance.snapshot.refresh; const withUpdatedDocs = Option.getOrThrow(yield* Fiber.join(updatedDocs)); expect(withUpdatedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); @@ -1760,7 +1880,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { elicitationId: "auth-1", url: "https://example.test/auth", }); - const resolvesAfterDocsUpdate = resolveAttempts; + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); yield* Fiber.interrupt(authRequest); // Removing website clears setup.documentationUrl via the cached probe without re-probing. @@ -1775,16 +1895,70 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* TestClock.adjust("1 minute"); yield* catalog.invalidateIndex(); yield* instance.snapshot.refresh; const withClearedDocs = Option.getOrThrow(yield* Fiber.join(clearedDocs)); expect(withClearedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); - expect(resolveAttempts).toBe(resolvesAfterDocsUpdate); + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); - // 2. When a foreground session skips a version-change probe, lastSeenIndexRevision stays pending and the next refresh after the session ends runs it. + // 2. An unrelated registry change plus a live command update does not re-probe this agent. + remoteExtraAgentVersion = "9.9.9"; + const unrelatedRefreshDone = yield* Deferred.make(); + onRefreshIndex = Deferred.succeed(unrelatedRefreshDone, undefined).pipe(Effect.asVoid); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "live-updated" }], + skills: [], + }); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + yield* Deferred.await(unrelatedRefreshDone); + onRefreshIndex = Effect.void; + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); + + // 3. Same-version launch distribution swap invalidates the probe cache and re-probes. + remoteArchiveSuffix = "-repackaged"; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["model-swapped-a", "model-swapped-b"]), + ); + const swappedReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "model-swapped-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + const swapped = Option.getOrThrow(yield* Fiber.join(swappedReady)); + expect(swapped.models.map((model) => model.slug)).toEqual([ + "model-swapped-a", + "model-swapped-b", + ]); + const resolvesAfterSwap = resolveAttempts; + expect(resolvesAfterSwap).toBeGreaterThan(resolvesAfterInitialProbe); + + // 4. Retained v1 live configuration/commands do not overwrite v2 after an upgrade, + // and a probe skipped during a foreground session stays pending until the session ends. + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-stale-a", + availableModels: [ + { modelId: "v1-stale-a", name: "v1-stale-a" }, + { modelId: "v1-stale-b", name: "v1-stale-b" }, + ], + }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "v1-stale-cmd" }], + skills: [], + }); remoteVersion = "2.0.0"; remoteWebsite = "https://example.test/v2"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v2-model-a", "v2-model-b"])); const sessionStarted = yield* Deferred.make(); const releaseSession = yield* Deferred.make(); const sessionFiber = yield* coordinator @@ -1797,18 +1971,30 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(sessionStarted); - const firstV2Recheck = yield* Deferred.make(); + let sawV2InFirstRefresh = false; + const firstV2ProbeSkipped = yield* Deferred.make(); onInspect = (inspection) => inspection.status === "ready" && inspection.version === "2.0.0" - ? Deferred.succeed(firstV2Recheck, undefined).pipe(Effect.asVoid) + ? Effect.sync(() => { + sawV2InFirstRefresh = true; + }) + : Effect.void; + onBackgroundProbeOutcome = (skipped) => + skipped && sawV2InFirstRefresh + ? Deferred.succeed(firstV2ProbeSkipped, undefined).pipe(Effect.asVoid) : Effect.void; yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; - yield* Deferred.await(firstV2Recheck); + yield* Deferred.await(firstV2ProbeSkipped); - // A second refresh while the session is still active rechecks v2 again because the skipped probe kept the revision pending. + // A second refresh while the session is still active skips the probe AND rechecks v2 because the revision stayed pending. let v2InspectsDuringSecondRefresh = 0; + const secondRefreshSkipped = yield* Deferred.make(); const secondRefreshRechecked = yield* Deferred.make(); + onBackgroundProbeOutcome = (skipped) => + skipped + ? Deferred.succeed(secondRefreshSkipped, undefined).pipe(Effect.asVoid) + : Effect.void; onInspect = (inspection) => inspection.status === "ready" && inspection.version === "2.0.0" ? Effect.sync(() => { @@ -1823,12 +2009,14 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { ) : Effect.void; yield* instance.snapshot.refresh; + yield* Deferred.await(secondRefreshSkipped); yield* Deferred.await(secondRefreshRechecked); - expect(resolveAttempts).toBe(resolvesAfterDocsUpdate); + expect(resolveAttempts).toBe(resolvesAfterSwap); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(false); - // Once the session ends, the next refresh runs the pending v2 probe without needing another registry fetch. + // Once the session ends, the next refresh installs v2 without another registry fetch and discards v1's stale live state. onInspect = null; + onBackgroundProbeOutcome = null; yield* Deferred.succeed(releaseSession, undefined); yield* Fiber.join(sessionFiber); const requestsBeforeRecovery = registryRequests; @@ -1845,6 +2033,8 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* instance.snapshot.refresh; const recovered = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); expect(recovered.version).toBe("2.0.0"); + expect(recovered.models.map((model) => model.slug)).toEqual(["v2-model-a", "v2-model-b"]); + expect(recovered.slashCommands).toEqual([]); expect(registryRequests).toBe(requestsBeforeRecovery); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); }), diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 856d1949d5709..2b1b8affa10a6 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -84,6 +84,7 @@ interface AcpRegistryEnrichmentCache { readonly entry: { readonly provider: ServerProvider; readonly expiresAt: number; + readonly launchIdentity?: string | null; } | null; } @@ -92,11 +93,18 @@ export function isAcpRegistryCacheValid( inspectedVersion: string | null, local: boolean, now: number, + inspectedLaunchIdentity?: string | null, ): boolean { - return ( - entry.expiresAt > now && - ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion) - ); + if (entry.expiresAt <= now) return false; + if (local && inspectedVersion === null) return true; + if ( + entry.launchIdentity !== undefined && + inspectedLaunchIdentity !== undefined && + entry.launchIdentity !== inspectedLaunchIdentity + ) { + return false; + } + return entry.provider.version === inspectedVersion; } export function updateAcpRegistryEnrichmentCache(input: { @@ -529,47 +537,83 @@ export function buildCheckedAcpRegistrySnapshot( }); } -export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")( - function* ( - input: SnapshotIdentity & { - readonly settings: AcpRegistrySettings; - readonly cwd: string; - readonly environment: NodeJS.ProcessEnv; - }, - probeConfiguration: AcpRegistryConfigurationProbe, - ): Effect.fn.Return { - const checkedAt = DateTime.formatIso(yield* DateTime.now); - if (!input.settings.enabled) { - return yield* buildInitialAcpRegistrySnapshot(input); - } - const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; - const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); - if (Result.isFailure(inspected)) { - return buildCheckedAcpRegistrySnapshot({ +interface CheckedAcpRegistryReadiness { + readonly snapshot: ServerProvider; + readonly launchIdentity: string | null; +} + +function runtimeIdentityFor( + provider: Pick, + launchIdentity: string | null, +): string | null { + return launchIdentity ?? provider.version; +} + +function readinessSignature(readiness: CheckedAcpRegistryReadiness) { + return { + installed: readiness.snapshot.installed, + version: readiness.snapshot.version, + status: readiness.snapshot.status, + message: readiness.snapshot.message, + documentationUrl: readiness.snapshot.setup?.documentationUrl, + launchIdentity: readiness.launchIdentity, + }; +} + +const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( + "AcpRegistryDriver.checkProviderStatus", +)(function* ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + }, + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.fn.Return< + { readonly provider: ServerProvider; readonly launchIdentity: string | null }, + never, + AcpRegistrySupport.AcpRegistryCatalog | Requirements +> { + const checkedAt = DateTime.formatIso(yield* DateTime.now); + if (!input.settings.enabled) { + return { provider: yield* buildInitialAcpRegistrySnapshot(input), launchIdentity: null }; + } + const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; + const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); + if (Result.isFailure(inspected)) { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: { status: "failed", message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`, }, - }); - } - if (inspected.success.status !== "ready") { - return buildCheckedAcpRegistrySnapshot({ + }), + launchIdentity: null, + }; + } + if (inspected.success.status !== "ready") { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: inspected.success, - }); - } - const probed = yield* Effect.result( - probeConfiguration({ - instanceId: input.instanceId, - settings: input.settings, - cwd: input.cwd, - environment: providerProbeEnvironment(input.environment), }), - ); - return Result.isFailure(probed) + launchIdentity: null, + }; + } + const launchIdentity = inspected.success.launchIdentity ?? null; + const probed = yield* Effect.result( + probeConfiguration({ + instanceId: input.instanceId, + settings: input.settings, + cwd: input.cwd, + environment: providerProbeEnvironment(input.environment), + }), + ); + return { + provider: Result.isFailure(probed) ? buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, @@ -581,21 +625,34 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check checkedAt, inspection: inspected.success, probe: probed.success, - }); + }), + launchIdentity, + }; +}); + +export const checkAcpRegistryProviderStatus = ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; }, -); + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.Effect => + checkAcpRegistryProviderStatusWithIdentity(input, probeConfiguration).pipe( + Effect.map(({ provider }) => provider), + ); -export const checkAcpRegistryProviderReadiness = Effect.fn( +const checkAcpRegistryProviderReadinessWithIdentity = Effect.fn( "AcpRegistryDriver.checkProviderReadiness", )(function* ( input: SnapshotIdentity & { readonly settings: AcpRegistrySettings; readonly environment: NodeJS.ProcessEnv; }, -): Effect.fn.Return { +): Effect.fn.Return { const checkedAt = DateTime.formatIso(yield* DateTime.now); if (!input.settings.enabled) { - return yield* buildInitialAcpRegistrySnapshot(input); + return { snapshot: yield* buildInitialAcpRegistrySnapshot(input), launchIdentity: null }; } const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); @@ -611,12 +668,23 @@ export const checkAcpRegistryProviderReadiness = Effect.fn( }); return inspected._tag === "Success" && inspected.success.status === "ready" ? { - ...snapshot, - message: "Checking ACP authentication, models, and commands in the background...", + snapshot: { + ...snapshot, + message: "Checking ACP authentication, models, and commands in the background...", + }, + launchIdentity: inspected.success.launchIdentity ?? null, } - : snapshot; + : { snapshot, launchIdentity: null }; }); +export const checkAcpRegistryProviderReadiness = ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly environment: NodeJS.ProcessEnv; + }, +): Effect.Effect => + checkAcpRegistryProviderReadinessWithIdentity(input).pipe(Effect.map(({ snapshot }) => snapshot)); + export type AcpRegistryDriverEnv = | AcpRegistryAdapterV2DriverEnv | Digest.Digest @@ -721,15 +789,20 @@ export const AcpRegistryDriver: ProviderDriver(null); const clearLiveState = ( Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value .clearLiveConfiguration(instanceId) .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId))) : Effect.void - ).pipe(Effect.andThen(clearLearnedModels)); + ).pipe( + Effect.andThen(clearLearnedModels), + Effect.andThen(Ref.set(activeRuntimeIdentity, null)), + ); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, + options?: { readonly applySessionLiveState?: boolean }, ) { if (!input.installed) return input; if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); @@ -740,43 +813,82 @@ export const AcpRegistryDriver: ProviderDriver { + const withCommands = applyAcpRegistryAvailableCommands(provider, commands); + return Option.match(configuration, { + onNone: () => Effect.succeed(withCommands), + onSome: (liveConfiguration) => applyLiveConfiguration(withCommands, liveConfiguration), }).pipe( - Effect.flatMap(({ commands, configuration, authAction }) => { - const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(configuration, { - onNone: () => Effect.succeed(withCommands), - onSome: (liveConfiguration) => - applyLiveConfiguration(withCommands, liveConfiguration), - }).pipe( - Effect.map((withConfiguration) => - applyAcpRegistryUrlAuthAction(withConfiguration, authAction), - ), - ); - }), + Effect.map((withConfiguration) => + 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); - const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.flatMap((provider) => - Ref.get(reportedLocalVersion).pipe( - Effect.map((version) => - provider.installed && provider.version === null && version !== null - ? { ...provider, version } - : provider, + const latestCheckedReadiness = yield* Ref.make(null); + const inspectReadiness = (options?: { + readonly applySessionLiveState?: boolean; + readonly seedActiveRuntimeIdentity?: boolean; + }) => + checkAcpRegistryProviderReadinessWithIdentity(readinessInput).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.flatMap(({ snapshot, launchIdentity }) => + Ref.get(reportedLocalVersion).pipe( + Effect.map((version) => ({ + snapshot: + snapshot.installed && snapshot.version === null && version !== null + ? { ...snapshot, version } + : snapshot, + launchIdentity, + })), ), ), - ), - Effect.flatMap(withLiveRuntimeState), + Effect.flatMap(({ snapshot, launchIdentity }) => + Ref.modify(activeRuntimeIdentity, (previousIdentity) => { + const nextIdentity = runtimeIdentityFor(snapshot, launchIdentity); + if ( + options?.seedActiveRuntimeIdentity === true && + snapshot.installed && + previousIdentity === null && + nextIdentity !== null + ) { + return [nextIdentity, nextIdentity] as const; + } + return [previousIdentity, previousIdentity] as const; + }).pipe( + Effect.flatMap((previousIdentity) => { + const nextIdentity = runtimeIdentityFor(snapshot, launchIdentity); + const applySessionLiveState = + (options?.applySessionLiveState ?? true) && + (previousIdentity === null || + nextIdentity === null || + previousIdentity === nextIdentity); + return withLiveRuntimeState(snapshot, { applySessionLiveState }).pipe( + Effect.map((withState) => ({ snapshot: withState, launchIdentity })), + ); + }), + ), + ), + ); + const checkProvider = inspectReadiness({ seedActiveRuntimeIdentity: true }).pipe( + Effect.tap((readiness) => Ref.set(latestCheckedReadiness, readiness)), + Effect.map(({ snapshot }) => snapshot), ); - const enrichProvider = checkAcpRegistryProviderStatus( + const enrichProvider = checkAcpRegistryProviderStatusWithIdentity( { ...readinessInput, cwd: host.paths.cwd, @@ -812,7 +924,7 @@ export const AcpRegistryDriver: ProviderDriver + const initialReadiness = yield* Ref.get(latestCheckedReadiness).pipe( + Effect.map((latest) => + latest !== null && + latest.snapshot.checkedAt === snapshot.checkedAt && + latest.snapshot.installed === snapshot.installed && + latest.snapshot.version === snapshot.version + ? { snapshot, launchIdentity: latest.launchIdentity } + : { snapshot, launchIdentity: null }, + ), + ); + const runProbeAndPublish = (target: CheckedAcpRegistryReadiness) => (Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( effectiveConfig.source === "local" ? `local:${instanceId}` : effectiveConfig.agentId, - enrichProviderCached(targetSnapshot), + enrichProviderCached(target), ) - : enrichProviderCached(targetSnapshot).pipe(Effect.asSome) + : enrichProviderCached(target).pipe(Effect.asSome) ).pipe( Effect.flatMap( Option.match({ onNone: () => Effect.succeed(false), - onSome: ({ provider, generation }) => + onSome: ({ provider, launchIdentity, generation }) => liveSnapshotSemaphore.withPermit( Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe( - Effect.flatMap(publishSnapshot), - Effect.as(true), - ) - : Effect.succeed(false), - ), + Effect.flatMap((current) => { + if (current.generation !== generation) return Effect.succeed(false); + const nextIdentity = runtimeIdentityFor(provider, launchIdentity); + return Ref.get(activeRuntimeIdentity).pipe( + Effect.flatMap((previousIdentity) => { + const runtimeChanged = + previousIdentity !== null && + nextIdentity !== null && + previousIdentity !== nextIdentity; + return withLiveRuntimeState(provider, { + applySessionLiveState: !runtimeChanged, + }).pipe( + Effect.flatMap(tryPublishSnapshot), + Effect.tap((published) => + !published + ? Effect.void + : (runtimeChanged ? clearLiveState : Effect.void).pipe( + Effect.andThen( + nextIdentity === null + ? Effect.void + : Ref.set(activeRuntimeIdentity, nextIdentity), + ), + ), + ), + ); + }), + ); + }), ), ), }), @@ -971,14 +1117,20 @@ export const AcpRegistryDriver: ProviderDriver + const publishUninstalled = ( + rechecked: CheckedAcpRegistryReadiness, + shouldClearLiveState: boolean, + ) => liveSnapshotSemaphore.withPermit( - clearLiveState.pipe( - Effect.andThen(invalidateEnrichmentCache), - Effect.andThen( - Equal.equals({ ...rechecked, checkedAt: snapshot.checkedAt }, snapshot) - ? Effect.void - : publishSnapshot(rechecked), + tryPublishSnapshot( + Equal.equals(readinessSignature(rechecked), readinessSignature(initialReadiness)) + ? snapshot + : rechecked.snapshot, + ).pipe( + Effect.tap((published) => + published && shouldClearLiveState + ? clearLiveState.pipe(Effect.andThen(invalidateEnrichmentCache)) + : Effect.void, ), ), ); @@ -986,14 +1138,20 @@ export const AcpRegistryDriver: ProviderDriver (published ? clearLiveState : Effect.void)), + ), + ); + if (!publishedRechecked) return; yield* runWithLiveWatchers( runProbeAndPublish(rechecked).pipe( Effect.tap((published) => @@ -1006,17 +1164,19 @@ export const AcpRegistryDriver: ProviderDriver { it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () => Effect.scoped( Effect.gen(function* () { - const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect> = []; + const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect> = []; const refreshCount = yield* Ref.make(0); const firstCallbackReady = yield* Deferred.make(); const secondCallbackReady = yield* Deferred.make(); @@ -686,9 +686,9 @@ describe("makeManagedServerProvider", () => { : Effect.succeed(refreshedSnapshotSecond), ), ), - enrichSnapshot: ({ publishSnapshot }) => + enrichSnapshot: ({ tryPublishSnapshot }) => Effect.gen(function* () { - publishCallbacks.push(publishSnapshot); + publishCallbacks.push(tryPublishSnapshot); if (publishCallbacks.length === 1) { yield* Deferred.succeed(firstCallbackReady, undefined).pipe(Effect.ignore); } else if (publishCallbacks.length === 2) { @@ -710,8 +710,9 @@ describe("makeManagedServerProvider", () => { yield* provider.refresh; yield* Deferred.await(secondCallbackReady); - yield* publishCallbacks[0]!(enrichedSnapshot); - yield* publishCallbacks[1]!(enrichedSnapshotSecond); + assert.strictEqual(yield* publishCallbacks[0]!(enrichedSnapshot), false); + assert.strictEqual(yield* publishCallbacks[1]!(enrichedSnapshotSecond), true); + assert.strictEqual(yield* publishCallbacks[1]!(enrichedSnapshotSecond), true); const updates = Array.from(yield* Fiber.join(updatesFiber)); const latest = yield* provider.getSnapshot; diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 2762930b5e1e9..416aae67a8142 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -69,6 +69,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly snapshot: ServerProvider; readonly getSnapshot: Effect.Effect; readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; + readonly tryPublishSnapshot: (snapshot: ServerProvider) => Effect.Effect; }) => Effect.Effect; readonly refreshInterval?: Duration.Input; readonly refreshOnInterval?: boolean | ((snapshot: ServerProvider) => boolean); @@ -101,30 +102,41 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* ( generation: number, nextSnapshot: ServerProvider, - ) { - const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => { - if (state.enrichmentGeneration !== generation) { - return [null, state] as const; - } - // Enrichment must not revert usage updates newer than its input snapshot. - const merged = withUsageLimits( - state.usageAuthLabel === undefined - ? nextSnapshot - : { - ...nextSnapshot, - auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, - }, - state.snapshot.usageLimits, - ); - if (Equal.equals(state.snapshot, merged)) { - return [null, state] as const; - } - return [merged, { ...state, snapshot: merged }] as const; - }); - if (snapshotToPublish === null) { - return; + ): Effect.fn.Return { + const outcome = yield* Ref.modify( + snapshotStateRef, + ( + state, + ): readonly [ + { readonly applied: boolean; readonly snapshot: ServerProvider | null }, + ProviderSnapshotState, + ] => { + if (state.enrichmentGeneration !== generation) { + return [{ applied: false, snapshot: null }, state]; + } + // Enrichment must not revert usage updates newer than its input snapshot. + const merged = withUsageLimits( + state.usageAuthLabel === undefined + ? nextSnapshot + : { + ...nextSnapshot, + auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, + }, + state.snapshot.usageLimits, + ); + if (Equal.equals(state.snapshot, merged)) { + return [{ applied: true, snapshot: null }, state]; + } + return [ + { applied: true, snapshot: merged }, + { ...state, snapshot: merged }, + ]; + }, + ); + if (outcome.snapshot !== null) { + yield* PubSub.publish(changesPubSub, outcome.snapshot); } - yield* PubSub.publish(changesPubSub, snapshotToPublish); + return outcome.applied; }); const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* ( @@ -146,7 +158,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( settings, snapshot, getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), - publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot), + publishSnapshot: (nextSnapshot) => + publishEnrichedSnapshot(generation, nextSnapshot).pipe(Effect.asVoid), + tryPublishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot), }) .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope)); From 6d8963a1cd6bec1d8657a3dd532aa1ec83a5a057 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 11:15:45 +0000 Subject: [PATCH 10/28] fix(acp-registry): harden runtime identity, binary receipts, and live state updates --- docs/user/providers-acp.md | 11 +- .../server/AcpRegistryRuntimeCoordinator.ts | 318 +++++++-- .../src/server/AcpRegistrySupport.test.ts | 350 ++++++++-- .../src/server/AcpRegistrySupport.ts | 204 ++++-- .../src/server/adapter.ts | 27 +- .../src/server/driver.test.ts | 657 ++++++++++++++++-- .../src/server/driver.ts | 649 ++++++++++++----- .../provider-acp-registry/src/server/probe.ts | 18 + packages/provider-acp/src/server/adapter.ts | 9 +- .../src/server/managedProvider.ts | 32 +- 10 files changed, 1883 insertions(+), 392 deletions(-) diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index b00e5585745c5..c3b2765cecac1 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -52,10 +52,13 @@ sign-in and direct use. Removing an agent's last provider instance removes T3-ma but keeps package installs. To use an existing local binary, set **Executable override** explicitly. T3 Code refreshes the Registry index in the background and automatically installs new versions of -enabled Registry agents alongside earlier versions, deferring background updates while that agent is -starting a session. Refreshing providers (in **Settings → Providers** on web and desktop, or -**Refresh providers** in environment settings on mobile) requests a fresh Registry check once the -installed agent finishes its status check. +prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while +that agent is starting a session. Agents using **Executable override** keep running the configured +executable—update those overrides directly on the server—while Registry refreshes can still pick up +updated Registry metadata, arguments, and environment variables. Refreshing providers (in +**Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on +mobile) requests a fresh Registry check right away for unprepared or unavailable agents, and after +the agent's status check finishes for installed agents. ## Signing in diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index bec80c06ddd39..a460782fc35a3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -17,14 +17,44 @@ import * as Stream from "effect/Stream"; import type { AcpRegistryAvailableCommands, AcpRegistryLiveConfiguration } from "./probe.ts"; +export interface AcpRegistryLiveUpdateMeta { + readonly runtimeIdentity: string | undefined; + readonly isCurrent: Effect.Effect; +} + +export interface AcpRegistryClearLiveStateOptions { + readonly preserveRuntimeIdentity?: string; +} + +export interface AcpRegistryReadLiveStateOptions { + readonly runtimeIdentity?: string; + readonly requireMatchingRuntimeIdentity?: boolean; +} + +interface AvailableCommandsEntry { + readonly commands: AcpRegistryAvailableCommands; + readonly runtimeIdentity: string | undefined; + readonly revision: number; +} + +interface LiveConfigurationEntry { + readonly configuration: AcpRegistryLiveConfiguration; + readonly runtimeIdentity: string | undefined; + readonly revision: number; +} + interface AvailableCommandsUpdate { readonly instanceId: ProviderInstanceId; readonly commands: AcpRegistryAvailableCommands; + readonly runtimeIdentity: string | undefined; + readonly revision: number; } interface LiveConfigurationUpdate { readonly instanceId: ProviderInstanceId; readonly configuration: AcpRegistryLiveConfiguration; + readonly runtimeIdentity: string | undefined; + readonly revision: number; } interface UrlAuthActionUpdate { @@ -54,29 +84,45 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly withSessionMutation: ( effect: Effect.Effect, ) => Effect.Effect; - readonly clearAvailableCommands: (instanceId: ProviderInstanceId) => Effect.Effect; + readonly clearAvailableCommands: ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, + ) => Effect.Effect; readonly publishAvailableCommands: ( instanceId: ProviderInstanceId, commands: AcpRegistryAvailableCommands, + runtimeIdentity?: string, ) => Effect.Effect; readonly getAvailableCommands: ( instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, ) => Effect.Effect>; readonly watchAvailableCommands: ( instanceId: ProviderInstanceId, - onUpdate: (commands: AcpRegistryAvailableCommands) => Effect.Effect, + onUpdate: ( + commands: AcpRegistryAvailableCommands, + meta: AcpRegistryLiveUpdateMeta, + ) => Effect.Effect, + ) => Effect.Effect; + readonly clearLiveConfiguration: ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, ) => Effect.Effect; - readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, + runtimeIdentity?: string, ) => Effect.Effect; readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, ) => Effect.Effect>; readonly watchLiveConfiguration: ( instanceId: ProviderInstanceId, - onUpdate: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + onUpdate: ( + configuration: AcpRegistryLiveConfiguration, + meta: AcpRegistryLiveUpdateMeta, + ) => Effect.Effect, ) => Effect.Effect; readonly requestUrlAuthentication: ( instanceId: ProviderInstanceId, @@ -95,17 +141,73 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< } >()("@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator") {} +interface LiveStateClearState { + readonly allBeforeRevision: number; + readonly nonMatchingBeforeRevision: number; + readonly preservedRuntimeIdentity: string | undefined; +} + +function recordLiveStateClear( + current: LiveStateClearState | undefined, + clearRevision: number, + options?: AcpRegistryClearLiveStateOptions, +): LiveStateClearState { + const preserveRuntimeIdentity = options?.preserveRuntimeIdentity; + if (preserveRuntimeIdentity === undefined) { + return { + allBeforeRevision: clearRevision, + nonMatchingBeforeRevision: clearRevision, + preservedRuntimeIdentity: undefined, + }; + } + const previousAllBefore = current?.allBeforeRevision ?? 0; + const previousPreservedExpired = + current !== undefined && current.preservedRuntimeIdentity !== preserveRuntimeIdentity + ? current.nonMatchingBeforeRevision + : 0; + return { + allBeforeRevision: Math.max(previousAllBefore, previousPreservedExpired), + nonMatchingBeforeRevision: clearRevision, + preservedRuntimeIdentity: preserveRuntimeIdentity, + }; +} + +function isLiveUpdateCurrent( + clearState: LiveStateClearState | undefined, + updateRevision: number, + runtimeIdentity: string | undefined, +): boolean { + if (clearState === undefined) return true; + if (updateRevision < clearState.allBeforeRevision) return false; + if ( + updateRevision < clearState.nonMatchingBeforeRevision && + (clearState.preservedRuntimeIdentity === undefined || + runtimeIdentity !== clearState.preservedRuntimeIdentity) + ) { + return false; + } + return true; +} + const make = Effect.gen(function* () { const foregroundStarts = yield* PubSub.unbounded(); const activeForegroundCounts = yield* Ref.make(new Map()); const availableCommandsUpdates = yield* PubSub.unbounded(); const availableCommandsByInstance = yield* Ref.make( - new Map(), + new Map(), ); + const availableCommandsClearsByInstance = yield* Ref.make( + new Map(), + ); + const availableCommandsRevision = yield* Ref.make(0); const liveConfigurationUpdates = yield* PubSub.unbounded(); const liveConfigurationByInstance = yield* Ref.make( - new Map(), + new Map(), + ); + const liveConfigurationClearsByInstance = yield* Ref.make( + new Map(), ); + const liveConfigurationRevision = yield* Ref.make(0); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -158,34 +260,79 @@ const make = Effect.gen(function* () { effect, ) => sessionMutationPermit.withPermit(effect); - const clearAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["clearAvailableCommands"] = - (instanceId) => - Ref.update(availableCommandsByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; - }); + const matchesReadRuntime = ( + entryRuntimeIdentity: string | undefined, + options?: AcpRegistryReadLiveStateOptions, + ): boolean => { + if (options?.runtimeIdentity === undefined) return true; + if (entryRuntimeIdentity === undefined) { + return options.requireMatchingRuntimeIdentity !== true; + } + return entryRuntimeIdentity === options.runtimeIdentity; + }; - const publishAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["publishAvailableCommands"] = - (instanceId, commands) => - Ref.update(availableCommandsByInstance, (current) => { - const next = new Map(current); - next.set(instanceId, commands); - return next; - }).pipe( + const clearAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["clearAvailableCommands"] = + (instanceId, options) => + Ref.updateAndGet(availableCommandsRevision, (revision) => revision + 1).pipe( + Effect.flatMap((clearRevision) => + Ref.update(availableCommandsClearsByInstance, (current) => { + const next = new Map(current); + next.set( + instanceId, + recordLiveStateClear(current.get(instanceId), clearRevision, options), + ); + return next; + }), + ), Effect.andThen( - PubSub.publish(availableCommandsUpdates, { - instanceId, - commands, + Ref.update(availableCommandsByInstance, (current) => { + const existing = current.get(instanceId); + if ( + existing === undefined || + (options?.preserveRuntimeIdentity !== undefined && + existing.runtimeIdentity === options.preserveRuntimeIdentity) + ) { + return current; + } + const next = new Map(current); + next.delete(instanceId); + return next; }), ), - Effect.asVoid, + ); + + const publishAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["publishAvailableCommands"] = + (instanceId, commands, runtimeIdentity) => + Ref.updateAndGet(availableCommandsRevision, (revision) => revision + 1).pipe( + Effect.flatMap((revision) => + Ref.update(availableCommandsByInstance, (current) => { + const next = new Map(current); + next.set(instanceId, { commands, runtimeIdentity, revision }); + return next; + }).pipe( + Effect.andThen( + PubSub.publish(availableCommandsUpdates, { + instanceId, + commands, + runtimeIdentity, + revision, + }), + ), + Effect.asVoid, + ), + ), ); const getAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["getAvailableCommands"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getAvailableCommands")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(availableCommandsByInstance)).get(instanceId)); - }); + Effect.fn("AcpRegistryRuntimeCoordinator.getAvailableCommands")( + function* (instanceId, options) { + const entry = (yield* Ref.get(availableCommandsByInstance)).get(instanceId); + if (entry === undefined || !matchesReadRuntime(entry.runtimeIdentity, options)) { + return Option.none(); + } + return Option.some(entry.commands); + }, + ); const watchAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["watchAvailableCommands"] = (instanceId, onUpdate) => @@ -193,56 +340,119 @@ const make = Effect.gen(function* () { Effect.gen(function* () { // Subscribe before reading to avoid missing publications. const subscription = yield* PubSub.subscribe(availableCommandsUpdates); - const current = yield* getAvailableCommands(instanceId); - if (Option.isSome(current)) { - yield* onUpdate(current.value); + const current = (yield* Ref.get(availableCommandsByInstance)).get(instanceId); + const metaFor = ( + runtimeIdentity: string | undefined, + revision: number, + ): AcpRegistryLiveUpdateMeta => ({ + runtimeIdentity, + isCurrent: Ref.get(availableCommandsClearsByInstance).pipe( + Effect.map((clears) => + isLiveUpdateCurrent(clears.get(instanceId), revision, runtimeIdentity), + ), + ), + }); + if (current !== undefined) { + yield* onUpdate(current.commands, metaFor(current.runtimeIdentity, current.revision)); } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.commands)), + Stream.runForEach((update) => + onUpdate(update.commands, metaFor(update.runtimeIdentity, update.revision)), + ), ); }), ); const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = - (instanceId) => - Ref.update(liveConfigurationByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; - }); - - const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = - (instanceId, configuration) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, configuration), - ).pipe( + (instanceId, options) => + Ref.updateAndGet(liveConfigurationRevision, (revision) => revision + 1).pipe( + Effect.flatMap((clearRevision) => + Ref.update(liveConfigurationClearsByInstance, (current) => { + const next = new Map(current); + next.set( + instanceId, + recordLiveStateClear(current.get(instanceId), clearRevision, options), + ); + return next; + }), + ), Effect.andThen( - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, + Ref.update(liveConfigurationByInstance, (current) => { + const existing = current.get(instanceId); + if ( + existing === undefined || + (options?.preserveRuntimeIdentity !== undefined && + existing.runtimeIdentity === options.preserveRuntimeIdentity) + ) { + return current; + } + const next = new Map(current); + next.delete(instanceId); + return next; }), ), - Effect.asVoid, + ); + + const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = + (instanceId, configuration, runtimeIdentity) => + Ref.updateAndGet(liveConfigurationRevision, (revision) => revision + 1).pipe( + Effect.flatMap((revision) => + Ref.update(liveConfigurationByInstance, (current) => + new Map(current).set(instanceId, { configuration, runtimeIdentity, revision }), + ).pipe( + Effect.andThen( + PubSub.publish(liveConfigurationUpdates, { + instanceId, + configuration, + runtimeIdentity, + revision, + }), + ), + Effect.asVoid, + ), + ), ); const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(liveConfigurationByInstance)).get(instanceId)); - }); + Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")( + function* (instanceId, options) { + const entry = (yield* Ref.get(liveConfigurationByInstance)).get(instanceId); + if (entry === undefined || !matchesReadRuntime(entry.runtimeIdentity, options)) { + return Option.none(); + } + return Option.some(entry.configuration); + }, + ); const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = (instanceId, onUpdate) => 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(liveConfigurationByInstance)).get(instanceId); + const metaFor = ( + runtimeIdentity: string | undefined, + revision: number, + ): AcpRegistryLiveUpdateMeta => ({ + runtimeIdentity, + isCurrent: Ref.get(liveConfigurationClearsByInstance).pipe( + Effect.map((clears) => + isLiveUpdateCurrent(clears.get(instanceId), revision, runtimeIdentity), + ), + ), + }); + if (current !== undefined) { + yield* onUpdate( + current.configuration, + metaFor(current.runtimeIdentity, current.revision), + ); } yield* Stream.fromSubscription(subscription).pipe( Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.configuration)), + Stream.runForEach((update) => + onUpdate(update.configuration, metaFor(update.runtimeIdentity, update.revision)), + ), ); }), ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index a6e1d3efbb6e1..c84ae2cc3cbb7 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1,4 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { sha256 } from "@noble/hashes/sha2.js"; +import * as Hex from "effect/encoding/Hex"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import { @@ -756,62 +758,111 @@ describe("AcpRegistrySupport", () => { ); }); - it.effect("installs and reuses a registry binary in the managed cache", () => { - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "./bin/example-agent", - args: ["acp"], - sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", + it.effect( + "installs, reuses, and replaces a registry binary in the managed cache when the artifact changes", + () => { + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + const replacementBytes = new TextEncoder().encode("#!/bin/sh\necho example-repackaged\n"); + const replacementArchiveUrl = "https://registry.test/example-agent-repackaged.bin"; + const replacementSha256 = Hex.encode(sha256(replacementBytes)); + let currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", + }, }, - }, - }); - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-install-", }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const first = yield* resolver.resolve(settings(), "/workspace"); - const second = yield* resolver.resolve(settings(), "/workspace"); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-install-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const first = yield* resolver.resolve(settings(), "/workspace"); + const second = yield* resolver.resolve(settings(), "/workspace"); - expect(first.spawn.command).toBe(second.spawn.command); - expect(first.spawn.command).toContain( - "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", - ); - expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( - "#!/bin/sh\necho example\n", + expect(first.spawn.command).toBe(second.spawn.command); + expect(first.spawn.command).toContain( + "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", + ); + expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( + "#!/bin/sh\necho example\n", + ); + expect(requests).toEqual([registryUrl, archiveUrl]); + + // Repackaging at the same version and cmd path downloads, verifies sha256, replaces the binary, and caches the new receipt. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: replacementSha256, + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const third = yield* resolver.resolve(settings(), "/workspace"); + const fourth = yield* resolver.resolve(settings(), "/workspace"); + expect(third.spawn.command).toBe(first.spawn.command); + expect(fourth.spawn.command).toBe(first.spawn.command); + expect(third.launchIdentity).not.toBe(first.launchIdentity); + expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( + "#!/bin/sh\necho example-repackaged\n", + ); + expect(requests).toEqual([registryUrl, archiveUrl, registryUrl, replacementArchiveUrl]); + + // A failed replacement (checksum mismatch) leaves the existing installed binary intact. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "0".repeat(64), + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const checksumError = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); + expect(checksumError.reason).toBe("checksum_mismatch"); + expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( + "#!/bin/sh\necho example-repackaged\n", + ); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + const payload = request.url === replacementArchiveUrl ? replacementBytes : binaryBytes; + const response = + request.url === registryUrl + ? new Response(makeRegistry(currentAgent)) + : new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(payload.slice(0, 8)); + controller.enqueue(payload.slice(8)); + controller.close(); + }, + }), + ); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), + ), ); - expect(requests).toEqual([registryUrl, archiveUrl]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests.push(request.url); - const response = - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(binaryBytes.slice(0, 8)); - controller.enqueue(binaryBytes.slice(8)); - controller.close(); - }, - }), - ); - return Effect.succeed(HttpClientResponse.fromWeb(request, response)); - }), - ), - ); - }); + }, + ); it.effect("gives Antigravity a T3-owned temp directory that is removed with the process", () => { const agent = { @@ -1111,7 +1162,9 @@ describe("AcpRegistrySupport", () => { .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); yield* Deferred.succeed(firstGate.release, undefined); - expect((yield* Fiber.join(firstRefresh)).reason).toBe("registry_unavailable"); + const firstRefreshError = yield* Fiber.join(firstRefresh); + expect(firstRefreshError.reason).toBe("registry_unavailable"); + expect(firstRefreshError.stage).toBe("http_request"); expect((yield* Fiber.join(queuedRefresh)).reason).toBe("registry_unavailable"); expect(registryRequests).toBe(1); @@ -1160,11 +1213,23 @@ describe("AcpRegistrySupport", () => { const coldInspectDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-inspect-coalesce-", }); + const coldCachePath = `${coldInspectDir}/acp-registry/registry.json`; + const missingColdCacheError = yield* fileSystem + .readFileString(coldCachePath) + .pipe(Effect.flip); + // Fail the missing cache read synchronously so the second inspect parks on the refresh semaphore before release. + const coldInspectFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === coldCachePath + ? Effect.fail(missingColdCacheError) + : fileSystem.readFileString(filePath, encoding), + }; const coldInspectResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: coldInspectDir, toolsDir: `${coldInspectDir}/tools`, registryUrl, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, coldInspectFs)); const coldInspectGate = { started: yield* Deferred.make(), release: yield* Deferred.make(), @@ -1179,6 +1244,7 @@ describe("AcpRegistrySupport", () => { const secondInspect = yield* coldInspectResolver .inspect(settings()) .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + expect(secondInspect.pollUnsafe()).toBeUndefined(); yield* Deferred.succeed(coldInspectGate.release, undefined); expect((yield* Fiber.join(firstInspect)).reason).toBe("registry_unavailable"); expect((yield* Fiber.join(secondInspect)).reason).toBe("registry_unavailable"); @@ -1369,7 +1435,52 @@ describe("AcpRegistrySupport", () => { expect(registryRequests).toBe(5); expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); - // 4. An uncached cold failure started before invalidation also does not record backoff. + // 4. A cold inspect() queued behind an invalidated in-flight fetch accepts the resulting index without refetching. + const coldAcceptedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-accept-", + }); + const coldAcceptedCachePath = `${coldAcceptedDir}/acp-registry/registry.json`; + const missingAcceptedCacheError = yield* fileSystem + .readFileString(coldAcceptedCachePath) + .pipe(Effect.flip); + const coldAcceptedFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === coldAcceptedCachePath + ? Effect.fail(missingAcceptedCacheError) + : fileSystem.readFileString(filePath, encoding), + }; + const coldAcceptedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldAcceptedDir, + toolsDir: `${coldAcceptedDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coldAcceptedFs)); + const coldFetchGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = coldFetchGate; + upstream = makeNpxAgent("1.2.8"); + const requestsBeforeColdAccept = registryRequests; + const inFlightRefresh = yield* coldAcceptedResolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldFetchGate.started); + yield* coldAcceptedResolver.invalidateIndex(); + const queuedColdInspect = yield* coldAcceptedResolver + .inspect(settings()) + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(queuedColdInspect.pollUnsafe()).toBeUndefined(); + fetchGate = null; + yield* Deferred.succeed(coldFetchGate.release, undefined); + expect(yield* Fiber.join(inFlightRefresh)).toBe(1); + expect(yield* Fiber.join(queuedColdInspect)).toMatchObject({ + version: "1.2.8", + indexRevision: 1, + }); + expect(registryRequests).toBe(requestsBeforeColdAccept + 1); + + // 5. An uncached cold failure started before invalidation also does not record backoff. const coldCacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-invalidate-race-", }); @@ -1395,9 +1506,9 @@ describe("AcpRegistrySupport", () => { online = true; fetchGate = null; expect(yield* coldResolver.refreshIndex(refreshOptions)).toBe(1); - expect(registryRequests).toBe(7); + expect(registryRequests).toBe(8); - // 5. Same-version package swaps change launchIdentity while documentation-only updates keep it identical. + // 6. launchIdentity tracks effective launch inputs for npx, commandOverride, and binary distributions. const packageSwapDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-launch-identity-", }); @@ -1453,6 +1564,131 @@ describe("AcpRegistrySupport", () => { docsOnlyInspection.status === "ready" && newPackageInspection.launchIdentity === docsOnlyInspection.launchIdentity, ).toBe(true); + + // commandOverride ignores version/package bumps it does not launch, while tracking args and env changes. + const overridePath = `${packageSwapDir}/override-agent`; + yield* fileSystem.writeFileString(overridePath, "#!/bin/sh\necho override\n"); + yield* fileSystem.chmod(overridePath, 0o755); + const overrideSettings = settings({ commandPath: overridePath }); + const overrideBase = yield* swapResolver.inspect(overrideSettings, toolchain.environment); + upstream = { + ...makeAgent({ npx: { package: "@example/other@2.0.0" } }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideBumped = yield* swapResolver.inspect(overrideSettings, toolchain.environment); + expect(overrideBase.status === "ready" && overrideBumped.status === "ready").toBe(true); + expect( + overrideBase.status === "ready" && overrideBumped.status === "ready" + ? overrideBase.launchIdentity === overrideBumped.launchIdentity + : false, + ).toBe(true); + + upstream = { + ...makeAgent({ + npx: { package: "@example/other@2.0.0", args: ["--flag"], env: { MODE: "acp" } }, + }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideArgsChanged = yield* swapResolver.inspect( + overrideSettings, + toolchain.environment, + ); + expect( + overrideBumped.status === "ready" && + overrideArgsChanged.status === "ready" && + overrideBumped.launchIdentity !== overrideArgsChanged.launchIdentity, + ).toBe(true); + + // Binary launchIdentity tracks archive, sha256, cmd, args, and env while ignoring website/icon changes. + const binaryExe = `${packageSwapDir}/tools/example-agent/1.0.0/linux-x86_64/bin/agent`; + yield* fileSystem.makeDirectory( + `${packageSwapDir}/tools/example-agent/1.0.0/linux-x86_64/bin`, + { + recursive: true, + }, + ); + yield* fileSystem.writeFileString(binaryExe, "#!/bin/sh\necho bin\n"); + yield* fileSystem.chmod(binaryExe, 0o755); + const inspectBinary = ( + target: { + readonly archive: string; + readonly cmd: string; + readonly sha256?: string; + readonly args?: ReadonlyArray; + readonly env?: Readonly>; + }, + meta?: { readonly website?: string; readonly icon?: string }, + ) => + Effect.gen(function* () { + upstream = { + ...makeAgent({ binary: { "linux-x86_64": target } }), + version: "1.0.0", + ...(meta?.website ? { website: meta.website } : {}), + ...(meta?.icon ? { icon: meta.icon } : {}), + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const inspected = yield* swapResolver.inspect(settings(), toolchain.environment); + expect(inspected.status).toBe("ready"); + return inspected.status === "ready" ? inspected.launchIdentity : undefined; + }); + const baseBinId = yield* inspectBinary( + { archive: archiveUrl, cmd: "./bin/agent", sha256: "a".repeat(64) }, + { + website: "https://example.test/a", + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/a.svg", + }, + ); + expect( + yield* inspectBinary( + { archive: archiveUrl, cmd: "./bin/agent", sha256: "a".repeat(64) }, + { + website: "https://example.test/b", + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/b.svg", + }, + ), + ).toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: "https://registry.test/other.bin", + cmd: "./bin/agent", + sha256: "a".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "b".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent-v2", + sha256: "a".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "a".repeat(64), + args: ["--extra"], + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "a".repeat(64), + env: { EXTRA: "1" }, + }), + ).not.toBe(baseBinId); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 0c36beca6c6bf..075c079edb46a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -208,9 +208,23 @@ const decodeBoundedAgentId = Schema.decodeUnknownEffect(BoundedAgentId); export const AcpRegistryErrorReason = AcpRegistryOperationErrorReason; export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type; +export const AcpRegistryFetchStage = Schema.Literals([ + "invalid_url", + "http_request", + "request_timeout", + "response_read", + "response_timeout", + "response_too_large", + "invalid_utf8", + "invalid_json", + "invalid_index", +]); +export type AcpRegistryFetchStage = typeof AcpRegistryFetchStage.Type; + export class AcpRegistryError extends Schema.TaggedError()("AcpRegistryError", { reason: AcpRegistryErrorReason, detail: Schema.String, + stage: Schema.optional(AcpRegistryFetchStage), cause: Schema.optional(Schema.Defect()), }) { override get message(): string { @@ -480,16 +494,19 @@ export function resolveAcpRegistryDistribution(input: { export interface ResolvedAcpRegistryAgent { readonly agent?: AcpRegistryAgent; readonly distribution: AcpRegistryDistributionKind | "local"; + readonly launchIdentity?: string; + readonly indexRevision?: number; readonly spawn: AcpSessionRuntime.AcpSpawnInput; } export type AcpRegistryInspection = | { readonly status: "unconfigured" } - | { readonly status: "not_found"; readonly agentId: string } + | { readonly status: "not_found"; readonly agentId: string; readonly indexRevision?: number } | { readonly status: "unsupported"; readonly agentId: string; readonly version: string; + readonly indexRevision?: number; } | { readonly status: "missing_runner"; @@ -497,6 +514,7 @@ export type AcpRegistryInspection = readonly version: string; readonly distribution: AcpRegistryDistributionKind; readonly runner: string; + readonly indexRevision?: number; } | { readonly status: "missing_runner"; @@ -508,6 +526,7 @@ export type AcpRegistryInspection = readonly agentId: string; readonly version: string; readonly distribution: "binary"; + readonly indexRevision?: number; } | { readonly status: "ready"; @@ -515,6 +534,8 @@ export type AcpRegistryInspection = readonly version: string | null; readonly distribution: AcpRegistryDistributionKind | "local"; readonly launchIdentity?: string; + readonly indexRevision?: number; + readonly icon?: string; readonly documentationUrl?: string; }; @@ -582,6 +603,16 @@ const INSTALL_LOCK_RETRY_DELAY = "100 millis"; const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; +const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; + +function binaryArtifactReceipt(target: typeof AcpRegistryBinaryTarget.Type): string { + return JSON.stringify({ + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + }); +} + function registryLaunchIdentity(input: { readonly version: string | null; readonly distribution: ResolvedAcpRegistryDistribution; @@ -590,10 +621,16 @@ function registryLaunchIdentity(input: { const envEntries = Object.entries(input.distribution.env).sort(([left], [right]) => compareText(left, right), ); + if (input.commandOverride) { + return JSON.stringify({ + commandOverride: input.commandOverride, + args: input.distribution.args, + env: envEntries, + }); + } 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 ? { @@ -607,37 +644,14 @@ function registryLaunchIdentity(input: { }); } -type RegistryFetchFailureStage = - | "invalid_url" - | "http_request" - | "request_timeout" - | "response_read" - | "response_timeout" - | "response_too_large" - | "invalid_utf8" - | "invalid_json" - | "invalid_index" - | "unknown"; - -function classifyRegistryFetchFailure(error: AcpRegistryError): RegistryFetchFailureStage { - if (error.detail.startsWith("ACP Registry index URL must use HTTPS.")) return "invalid_url"; - if (error.detail.startsWith("Timed out fetching ACP Registry index.")) return "request_timeout"; - if (error.detail.startsWith("Could not fetch ACP Registry index from ")) return "http_request"; - if (error.detail.startsWith("Timed out reading ACP Registry response body.")) { - return "response_timeout"; - } - if (error.detail.startsWith("Could not read ACP Registry response body.")) return "response_read"; - if (error.detail.startsWith("ACP Registry index exceeds ")) return "response_too_large"; - if (error.detail.startsWith("ACP Registry index is not valid UTF-8.")) return "invalid_utf8"; - if (error.detail.startsWith("ACP Registry returned invalid JSON.")) return "invalid_json"; - if (error.detail.startsWith("ACP Registry returned an invalid index.")) return "invalid_index"; - return "unknown"; -} - function isAlreadyExists(error: PlatformError.PlatformError): boolean { return error.reason._tag === "AlreadyExists"; } +function isNotFound(error: PlatformError.PlatformError): boolean { + return error.reason._tag === "NotFound"; +} + function normalizeRegistryCommandPath(command: string): ReadonlyArray | undefined { const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, ""); const segments = normalized.split("/").filter((segment) => segment.length > 0); @@ -903,10 +917,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const assertHttpsUrl = Effect.fn("AcpRegistryCatalog.assertHttpsUrl")(function* ( value: string, detail: string, + stage?: AcpRegistryFetchStage, ) { const valid = yield* decodeHttpsUrl(value).pipe(Effect.option); if (Option.isNone(valid)) { - return yield* new AcpRegistryError({ reason: "registry_unavailable", detail }); + return yield* new AcpRegistryError({ + reason: "registry_unavailable", + detail, + ...(stage === undefined ? {} : { stage }), + }); } return value; }); @@ -920,6 +939,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry returned invalid JSON.", + stage: "invalid_json", cause, }), ), @@ -930,6 +950,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry returned an invalid index.", + stage: "invalid_index", cause, }), ), @@ -965,7 +986,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); const fetchRegistry = Effect.fn("AcpRegistryCatalog.fetchRegistry")(function* () { - yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS."); + yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS.", "invalid_url"); const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError( @@ -973,6 +994,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: `Could not fetch ACP Registry index from ${registryUrl}.`, + stage: "http_request", cause, }), ), @@ -983,6 +1005,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Timed out fetching ACP Registry index.", + stage: "request_timeout", }), ), }), @@ -996,6 +1019,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Could not read ACP Registry response body.", + stage: "response_read", cause, }), ), @@ -1006,6 +1030,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Timed out reading ACP Registry response body.", + stage: "response_timeout", }), ), }), @@ -1014,12 +1039,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return yield* new AcpRegistryError({ reason: "registry_unavailable", detail: `ACP Registry index exceeds ${MAX_REGISTRY_BYTES} bytes.`, + stage: "response_too_large", }); } if (collected.invalidUtf8) { return yield* new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry index is not valid UTF-8.", + stage: "invalid_utf8", }); } const registry = yield* decodeRegistryText(collected.text); @@ -1032,6 +1059,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly observedAttemptRevision?: number; readonly failureBackoffMs?: number; readonly coalesceFailure?: boolean; + readonly acceptAnyIndex?: boolean; }) { const initialState = yield* Ref.get(registryState); const startFetchRevision = options?.observedFetchRevision ?? initialState.fetchRevision; @@ -1043,7 +1071,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const current = yield* Ref.get(registryState); if ( current.index !== undefined && - (current.fetchRevision !== startFetchRevision || + (options?.acceptAnyIndex === true || + current.fetchRevision !== startFetchRevision || (failureBackoffMs !== undefined && current.attemptRevision !== startAttemptRevision)) ) { return { index: current.index, indexRevision: current.indexRevision }; @@ -1076,7 +1105,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const now = yield* Clock.currentTimeMillis; yield* Effect.logDebug("ACP Registry index refresh failed", { reason: networkError.reason, - stage: classifyRegistryFetchFailure(networkError), + stage: networkError.stage ?? "unknown", }); // Prefer an already-loaded index over disk so a cache-write failure cannot regress it. const inMemory = (yield* Ref.get(registryState)).index; @@ -1184,16 +1213,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct })); }); - const loadRegistry = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { - const current = (yield* Ref.get(registryState)).index; - if (current !== undefined) return current; + const loadRegistrySnapshot = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { + const current = yield* Ref.get(registryState); + if (current.index !== undefined) { + return { index: current.index, indexRevision: current.indexRevision }; + } const cached = yield* readCachedRegistry; - if (Option.isNone(cached)) return (yield* refreshRegistry({ coalesceFailure: true })).index; + if (Option.isNone(cached)) { + return yield* refreshRegistry({ coalesceFailure: true, acceptAnyIndex: true }); + } // Publish without waiting on an in-flight refresh, while letting a completed refresh win. return yield* Ref.modify(registryState, (state) => { const index = state.index ?? cached.value; - return [index, state.index !== undefined ? state : { ...state, index }] as const; + return [ + { index, indexRevision: state.indexRevision }, + state.index !== undefined ? state : { ...state, index }, + ] as const; }); }); @@ -1702,6 +1738,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); + const isCachedBinaryMatching = Effect.fn("AcpRegistryCatalog.isCachedBinaryMatching")(function* ( + installRoot: string, + executablePath: string, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if (!(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false)))) { + return false; + } + const receiptPath = path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME); + const receipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); + return Option.isSome(receipt) && receipt.value === binaryArtifactReceipt(target); + }); + const installBinary = Effect.fn("AcpRegistryCatalog.installBinary")(function* ( agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type, @@ -1720,7 +1769,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const { commandSegments, installRoot, executablePath } = paths; - if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { + if (yield* isCachedBinaryMatching(installRoot, executablePath, target)) { return yield* assertExecutableInRoot(installRoot, executablePath).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) @@ -1758,7 +1807,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); return yield* Effect.gen(function* () { - if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { + if (yield* isCachedBinaryMatching(installRoot, executablePath, target)) { return yield* assertExecutableInRoot(installRoot, executablePath); } const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ @@ -1884,8 +1933,24 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); - yield* fileSystem.remove(installRoot, { recursive: true, force: true }); - yield* fileSystem.rename(extractionRoot, installRoot); + yield* fileSystem.writeFileString( + path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), + binaryArtifactReceipt(target), + ); + const backupRoot = path.join(temporaryRoot, "previous"); + const movedPrevious = yield* fileSystem.rename(installRoot, backupRoot).pipe( + Effect.as(true), + Effect.catchIf(isNotFound, () => Effect.succeed(false)), + ); + yield* fileSystem + .rename(extractionRoot, installRoot) + .pipe( + Effect.onError(() => + movedPrevious + ? fileSystem.rename(backupRoot, installRoot).pipe(Effect.ignore) + : Effect.void, + ), + ); return yield* assertExecutableInRoot(installRoot, executablePath); }).pipe( Effect.scoped, @@ -2035,17 +2100,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const agentId = settings.agentId.trim(); if (agentId.length === 0) return { status: "unconfigured" } as const; - const registry = yield* loadRegistry(); + const { index: registry, indexRevision } = yield* loadRegistrySnapshot(); const agent = registry.agents.find((candidate) => candidate.id === agentId); - if (agent === undefined) return { status: "not_found", agentId } as const; + if (agent === undefined) return { status: "not_found", agentId, indexRevision } as const; const documentationUrl = agent.website ?? agent.repository; + const icon = agent.icon; const distribution = resolveAcpRegistryDistribution({ agent, preference: settings.distribution, platformTarget, }); if (distribution === undefined) { - return { status: "unsupported", agentId, version: agent.version } as const; + return { status: "unsupported", agentId, version: agent.version, indexRevision } as const; } const commandOverride = settings.commandPath.trim(); @@ -2064,6 +2130,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct distribution, commandOverride, }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -2072,6 +2140,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: distribution.kind, runner: commandOverride, + indexRevision, } as const); } @@ -2080,7 +2149,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.gen(function* () { const paths = binaryPaths(agent, distribution.binaryTarget!); if (paths === undefined) { - return { status: "unsupported", agentId, version: agent.version } as const; + return { + status: "unsupported", + agentId, + version: agent.version, + indexRevision, + } as const; } yield* consumePreparedBinaryReservation(agent.id); const exists = yield* fileSystem @@ -2093,6 +2167,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: "binary", + indexRevision, } as const; } if (exists) { @@ -2114,6 +2189,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: "binary", launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const; }), @@ -2130,6 +2207,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: distribution.kind, launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -2138,6 +2217,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: distribution.kind, runner, + indexRevision, } as const); }, ); @@ -2147,6 +2227,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct cwd: string, environment: NodeJS.ProcessEnv | undefined, registry: AcpRegistryIndex, + indexRevision: number, ) { const agentId = settings.agentId.trim(); if (agentId.length === 0) { @@ -2211,6 +2292,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return { agent, distribution: distribution.kind, + launchIdentity: registryLaunchIdentity({ + version: commandOverride.length > 0 ? null : agent.version, + distribution, + ...(commandOverride.length > 0 ? { commandOverride } : {}), + }), + indexRevision, spawn: { command, args, @@ -2245,18 +2332,29 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct spawn: { command, args: settings.commandArgs, cwd, env, shell: false }, } satisfies ResolvedAcpRegistryAgent; } - const registry = yield* loadRegistry(); - return yield* resolveWithRegistry(settings, cwd, environment, registry).pipe( + const { index: registry, indexRevision } = yield* loadRegistrySnapshot(); + return yield* resolveWithRegistry(settings, cwd, environment, registry, indexRevision).pipe( Effect.catchIf( (error) => error.reason === "download_failed", (error) => Effect.gen(function* () { - const { index: latest } = yield* refreshRegistry().pipe(Effect.mapError(() => error)); + const { index: latest, indexRevision: latestRevision } = + 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; - return yield* resolveWithRegistry(settings, cwd, environment, latest); + const launchSignatureIn = (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 + ? agent.version + : registryLaunchIdentity({ version: agent.version, distribution }); + }; + if (launchSignatureIn(latest) === launchSignatureIn(registry)) return yield* error; + return yield* resolveWithRegistry(settings, cwd, environment, latest, latestRevision); }), ), ); diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..9196f62be03d2 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -139,6 +139,10 @@ export function acpRegistryPromptFailure(agentId: string, cause: unknown) { function makeAcpRegistryRuntime( options: AcpRegistryAdapterV2Options, catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"], + onResolvedRuntime?: ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent, + ) => void, ) { return ( input: AcpAdapterV2RuntimeInput, @@ -176,9 +180,11 @@ function makeAcpRegistryRuntime( ), }), ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( Effect.provide(context), ); + onResolvedRuntime?.(runtime, resolved); + return runtime; }); } @@ -262,6 +268,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu // the unquoted "T3 Code (Beta).exe" path). Both take T3's MCP endpoint over ACP HTTP. const useHttpMcpServers = copilotRouting !== undefined || prefersHttpMcpTransport(options.settings); + const runtimeIdentityByRuntime = new WeakMap< + AcpSessionRuntime.AcpSessionRuntime["Service"], + string + >(); const flavor: AcpAdapterV2Flavor = { driver: ACP_REGISTRY_PROVIDER, // Cancelling a Copilot prompt also kills the background agents it started. @@ -343,14 +353,22 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu alwaysSetModel: true, }), mcpOverHttp: useHttpMcpServers, - makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog), + makeRuntime: + options.makeRuntime ?? + makeAcpRegistryRuntime(runtimeOptions, catalog, (runtime, resolved) => { + const runtimeIdentity = resolved.launchIdentity ?? resolved.agent?.version; + if (runtimeIdentity !== undefined) { + runtimeIdentityByRuntime.set(runtime, runtimeIdentity); + } + }), ...(runtimeCoordinator === undefined ? {} : { - onAvailableCommandsUpdate: (commands) => + onAvailableCommandsUpdate: (commands, runtime) => runtimeCoordinator.publishAvailableCommands( options.instanceId, normalizeAcpRegistryCommands(commands), + runtime === undefined ? undefined : runtimeIdentityByRuntime.get(runtime), ), // A new Copilot session starts at its own effort, not the one the composer shows. ...(isCopilot @@ -374,10 +392,11 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), - onSessionConfigurationUpdate: (configOptions, modeState, modelState) => + onSessionConfigurationUpdate: (configOptions, modeState, modelState, runtime) => runtimeCoordinator.publishLiveConfiguration( options.instanceId, normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState), + runtime === undefined ? undefined : runtimeIdentityByRuntime.get(runtime), ), onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index b416a6d482bab..3290741f3d61c 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1039,6 +1039,14 @@ const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* const installedV1 = installedBinaryPath(path, directory, "1.0.0"); yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); + yield* fileSystem.writeFileString( + path.join(path.dirname(path.dirname(installedV1)), ".t3-artifact.json"), + JSON.stringify({ + archive: "https://registry.test/test-agent-1.0.0.bin", + cmd: "./bin/test-agent", + sha256: null, + }), + ); if (!isWindowsHost) { yield* fileSystem.chmod(installedV1, 0o755); } @@ -1398,7 +1406,7 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); }); -it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { +describe("AcpRegistryDriver registry recovery", () => { it.effect( "recovers when a refreshed index moves from compatible to incompatible and back without cache invalidation", () => @@ -1567,7 +1575,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { expect(ready.slashCommands).toEqual([]); expect(resolveAttempts).toBeGreaterThan(attemptsWhileUnsupported); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); - }), + }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); it.effect( @@ -1709,7 +1717,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* Deferred.succeed(secondGate.release, undefined); expect(Option.isSome(yield* Fiber.join(upgradedToV3))).toBe(true); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); - }), + }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); it.effect( @@ -1730,6 +1738,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { let remoteExtraAgentVersion: string | undefined = undefined; let registryRequests = 0; let resolveAttempts = 0; + let backgroundProbeCalls = 0; let onInspect: | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) | null = null; @@ -1739,15 +1748,16 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { { ...baseCoordinator, runBackgroundProbe: (agentId, effect) => - baseCoordinator - .runBackgroundProbe(agentId, effect) - .pipe( - Effect.tap((outcome) => - onBackgroundProbeOutcome === null - ? Effect.void - : onBackgroundProbeOutcome(Option.isNone(outcome)), - ), + Effect.sync(() => { + backgroundProbeCalls += 1; + }).pipe( + Effect.andThen(() => baseCoordinator.runBackgroundProbe(agentId, effect)), + Effect.tap((outcome) => + onBackgroundProbeOutcome === null + ? Effect.void + : onBackgroundProbeOutcome(Option.isNone(outcome)), ), + ), }; const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, @@ -1779,7 +1789,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { return Effect.succeed( HttpClientResponse.fromWeb( request, - new Response(`#!/bin/sh\necho ${remoteVersion}\n`), + new Response(`#!/bin/sh\necho ${remoteVersion}${remoteArchiveSuffix}\n`), ), ); }), @@ -1901,21 +1911,79 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { expect(withClearedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); expect(resolveAttempts).toBe(resolvesAfterInitialProbe); - // 2. An unrelated registry change plus a live command update does not re-probe this agent. + // 2. An unrelated registry change plus a live command update does not schedule a second probe. remoteExtraAgentVersion = "9.9.9"; - const unrelatedRefreshDone = yield* Deferred.make(); - onRefreshIndex = Deferred.succeed(unrelatedRefreshDone, undefined).pipe(Effect.asVoid); + let unrelatedRefreshed = false; + const unrelatedRechecked = yield* Deferred.make(); + onRefreshIndex = Effect.sync(() => { + unrelatedRefreshed = true; + }); + onInspect = () => + unrelatedRefreshed + ? Deferred.succeed(unrelatedRechecked, undefined).pipe(Effect.asVoid) + : Effect.void; + const liveCommandApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "live-updated"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const probesBeforeUnrelated = backgroundProbeCalls; yield* coordinator.publishAvailableCommands(identity.instanceId, { slashCommands: [{ name: "live-updated" }], skills: [], }); yield* catalog.invalidateIndex(); yield* instance.snapshot.refresh; - yield* Deferred.await(unrelatedRefreshDone); + yield* Deferred.await(unrelatedRechecked); + expect(Option.isSome(yield* Fiber.join(liveCommandApplied))).toBe(true); onRefreshIndex = Effect.void; + onInspect = null; + // 1 auth.refreshMethods + 1 initialProbe; 0 post-recheck probe calls. + expect(backgroundProbeCalls).toBe(probesBeforeUnrelated + 2); expect(resolveAttempts).toBe(resolvesAfterInitialProbe); + expect((yield* instance.snapshot.getSnapshot).slashCommands).toEqual([ + { name: "live-updated" }, + ]); + + // A freshly created instance on an already-refreshed catalog does not recheck the same revision. + const secondInstanceId = ProviderInstanceId.make("acpRegistry_second_fresh"); + let secondInstanceRefreshed = false; + let secondInstancePostRefreshInspects = 0; + const secondInstanceRefreshDone = yield* Deferred.make(); + onRefreshIndex = Effect.sync(() => { + secondInstanceRefreshed = true; + }).pipe( + Effect.andThen(Deferred.succeed(secondInstanceRefreshDone, undefined)), + Effect.asVoid, + ); + onInspect = () => + secondInstanceRefreshed + ? Effect.sync(() => { + secondInstancePostRefreshInspects += 1; + }) + : Effect.void; + const secondInstance = yield* AcpRegistryDriver.create({ + instanceId: secondInstanceId, + displayName: "Second ACP", + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + yield* secondInstance.snapshot.refresh; + yield* Deferred.await(secondInstanceRefreshDone); + onRefreshIndex = Effect.void; + onInspect = null; + expect(secondInstancePostRefreshInspects).toBe(0); - // 3. Same-version launch distribution swap invalidates the probe cache and re-probes. + // 3. Same-version launch distribution swap replaces the cached binary on disk, invalidates the probe cache, and re-probes. remoteArchiveSuffix = "-repackaged"; yield* fileSystem.writeFileString( modelsPath, @@ -1930,6 +1998,7 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const resolvesBeforeSwap = resolveAttempts; yield* catalog.invalidateIndex(); yield* instance.snapshot.refresh; const swapped = Option.getOrThrow(yield* Fiber.join(swappedReady)); @@ -1937,10 +2006,13 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { "model-swapped-a", "model-swapped-b", ]); + expect( + yield* fileSystem.readFileString(installedBinaryPath(path, directory, "1.0.0")), + ).toBe("#!/bin/sh\necho 1.0.0-repackaged\n"); const resolvesAfterSwap = resolveAttempts; - expect(resolvesAfterSwap).toBeGreaterThan(resolvesAfterInitialProbe); + expect(resolvesAfterSwap).toBeGreaterThan(resolvesBeforeSwap); - // 4. Retained v1 live configuration/commands do not overwrite v2 after an upgrade, + // 4. Retained v1 live configuration/commands do not leak onto v2 readiness or probe snapshots, // and a probe skipped during a foreground session stays pending until the session ends. yield* coordinator.publishLiveConfiguration( identity.instanceId, @@ -1987,56 +2059,561 @@ it.layer(driverLayer)("AcpRegistryDriver registry recovery", (it) => { yield* instance.snapshot.refresh; yield* Deferred.await(firstV2ProbeSkipped); - // A second refresh while the session is still active skips the probe AND rechecks v2 because the revision stayed pending. - let v2InspectsDuringSecondRefresh = 0; - const secondRefreshSkipped = yield* Deferred.make(); + // Collect every snapshot from Refresh #2 through v2 recovery to verify no v2 snapshot ever carries v1 live state. + const v2TransitionSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v2" && + snapshot.nativeSessions !== undefined, + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + + // A second refresh while the session is still active skips both probes (auth + enrichment) AND rechecks v2 after refreshIndex. + let secondRefreshSkips = 0; + let secondRefreshIndexChecked = false; + const secondRefreshAllSkips = yield* Deferred.make(); const secondRefreshRechecked = yield* Deferred.make(); onBackgroundProbeOutcome = (skipped) => skipped - ? Deferred.succeed(secondRefreshSkipped, undefined).pipe(Effect.asVoid) - : Effect.void; - onInspect = (inspection) => - inspection.status === "ready" && inspection.version === "2.0.0" ? Effect.sync(() => { - v2InspectsDuringSecondRefresh += 1; - return v2InspectsDuringSecondRefresh; + secondRefreshSkips += 1; + return secondRefreshSkips; }).pipe( Effect.flatMap((count) => count >= 2 - ? Deferred.succeed(secondRefreshRechecked, undefined).pipe(Effect.asVoid) + ? Deferred.succeed(secondRefreshAllSkips, undefined).pipe(Effect.asVoid) : Effect.void, ), ) : Effect.void; + onRefreshIndex = Effect.sync(() => { + secondRefreshIndexChecked = true; + }); + onInspect = (inspection) => + secondRefreshIndexChecked && + inspection.status === "ready" && + inspection.version === "2.0.0" + ? Deferred.succeed(secondRefreshRechecked, undefined).pipe(Effect.asVoid) + : Effect.void; yield* instance.snapshot.refresh; - yield* Deferred.await(secondRefreshSkipped); + yield* Deferred.await(secondRefreshAllSkips); yield* Deferred.await(secondRefreshRechecked); expect(resolveAttempts).toBe(resolvesAfterSwap); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(false); // Once the session ends, the next refresh installs v2 without another registry fetch and discards v1's stale live state. onInspect = null; + onRefreshIndex = Effect.void; onBackgroundProbeOutcome = null; yield* Deferred.succeed(releaseSession, undefined); yield* Fiber.join(sessionFiber); const requestsBeforeRecovery = registryRequests; - const upgradedToV2 = yield* instance.snapshot.streamChanges.pipe( + yield* instance.snapshot.refresh; + const transitionSnapshots = yield* Fiber.join(v2TransitionSnapshots); + const v2Snapshots = transitionSnapshots.filter((snapshot) => snapshot.version === "2.0.0"); + expect(v2Snapshots.length).toBeGreaterThanOrEqual(2); + expect( + v2Snapshots.every( + (snapshot) => + !snapshot.slashCommands.some((command) => command.name === "v1-stale-cmd") && + !snapshot.models.some((model) => model.slug === "v1-stale-a"), + ), + ).toBe(true); + const recovered = v2Snapshots[v2Snapshots.length - 1]!; + expect(recovered.version).toBe("2.0.0"); + expect(recovered.models.map((model) => model.slug)).toEqual(["v2-model-a", "v2-model-b"]); + expect(recovered.slashCommands).toEqual([]); + expect(registryRequests).toBe(requestsBeforeRecovery); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect("labels and caches probes using the runtime selected by catalog.resolve", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-resolved-identity-", + { website: "https://example.test/v1" }, + ); + + let remoteVersion = "2.0.0"; + let remoteWebsite = "https://example.test/v2"; + let switchedBeforeResolve = false; + let probeResolveAttempts = 0; + const inspectedVersionsBeforeSwitch: Array = []; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + website: remoteWebsite, + }) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + realCatalog.inspect(settings, environment).pipe( + Effect.tap((inspection) => + !switchedBeforeResolve && inspection.status === "ready" + ? Effect.sync(() => { + inspectedVersionsBeforeSwitch.push(inspection.version); + }) + : Effect.void, + ), + ), + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + const isProbeResolve = environment?.MISE_OFFLINE === "1"; + if (isProbeResolve) { + probeResolveAttempts += 1; + // Simulate a concurrent registry refresh advancing the index to 2.0.0 after inspect() saw 1.0.0. + if (!switchedBeforeResolve) { + switchedBeforeResolve = true; + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + } + } + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + return { + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }; + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v2-resolved-a", "v2-resolved-b"]), + ); + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // Let the initial startup check run once without triggering a concurrent refresh. + const firstProbed = Option.getOrThrow( + yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ), + ); + // Even though inspect() saw 1.0.0, the published probe carries 2.0.0's resolved version and metadata. + expect(inspectedVersionsBeforeSwitch.length).toBeGreaterThan(0); + expect(inspectedVersionsBeforeSwitch.every((version) => version === "1.0.0")).toBe(true); + expect(firstProbed.version).toBe("2.0.0"); + expect(firstProbed.setup?.documentationUrl).toBe("https://example.test/v2"); + expect(firstProbed.models.map((model) => model.slug)).toEqual([ + "v2-resolved-a", + "v2-resolved-b", + ]); + expect(probeResolveAttempts).toBe(1); + + // Refreshing on 2.0.0 reuses the cached probe keyed by 2.0.0's resolved launch identity. + const cachedV2 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(cachedV2))).toBe(true); + expect(probeResolveAttempts).toBe(1); + + // Reverting upstream to 1.0.0 must miss the cache (proving v2's probe was not cached under 1.0.0's identity). + remoteVersion = "1.0.0"; + remoteWebsite = "https://example.test/v1"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v1-fresh-a", "v1-fresh-b"])); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertedV1 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "v1-fresh-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const secondProbed = Option.getOrThrow(yield* Fiber.join(revertedV1)); + expect(secondProbed.models.map((model) => model.slug)).toEqual(["v1-fresh-a", "v1-fresh-b"]); + expect(probeResolveAttempts).toBe(2); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "retires cached probes and live state when base checkProvider observes an uninstalled transition", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-base-uninstall-", + ); + + let remoteVersion = "1.0.0"; + let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion, remoteTarget) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // Prime 1.0.0 cache and live state. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "stale-before-uninstall" }], + skills: [], + }); + + // Another caller refreshes the shared catalog to incompatible 2.0.0 so checkProvider directly sees !installed. + remoteVersion = "2.0.0"; + remoteTarget = incompatibleRegistryTarget; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const uninstalledSeen = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => !snapshot.installed && snapshot.version === "2.0.0"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(uninstalledSeen))).toBe(true); + + // Restoring 1.0.0 before the 15-minute probe TTL must re-probe fresh models and not restore stale commands. + remoteVersion = "1.0.0"; + remoteTarget = compatibleRegistryTarget; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["recovered-fresh-a", "recovered-fresh-b"]), + ); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const recovered = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => - snapshot.version === "2.0.0" && - snapshot.setup?.documentationUrl === "https://example.test/v2" && + snapshot.installed && + snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - const recovered = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); - expect(recovered.version).toBe("2.0.0"); - expect(recovered.models.map((model) => model.slug)).toEqual(["v2-model-a", "v2-model-b"]); - expect(recovered.slashCommands).toEqual([]); - expect(registryRequests).toBe(requestsBeforeRecovery); - expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); - }), + const freshSnapshot = Option.getOrThrow(yield* Fiber.join(recovered)); + expect(freshSnapshot.models.map((model) => model.slug)).toEqual([ + "recovered-fresh-a", + "recovered-fresh-b", + ]); + expect(freshSnapshot.slashCommands).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "preserves new-runtime live state across upgrades while rejecting older or queued stale watcher updates", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-runtime-tagged-live-", + ); + + let remoteVersion = "1.0.0"; + let v2ResolveGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let queuedStaleConfigGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly matchSlug: string; + } | null = null; + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + watchLiveConfiguration: (instanceId, onUpdate) => + baseCoordinator.watchLiveConfiguration(instanceId, (configuration, meta) => { + const activeGate = + queuedStaleConfigGate !== null && + configuration.models.some( + (model) => model.id === queuedStaleConfigGate!.matchSlug, + ) + ? queuedStaleConfigGate + : null; + if (activeGate === null) return onUpdate(configuration, meta); + queuedStaleConfigGate = null; + return Deferred.succeed(activeGate.entered, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(onUpdate(configuration, meta)), + ); + }), + }; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + if ( + environment?.MISE_OFFLINE === "1" && + resolved.agent?.version === "2.0.0" && + v2ResolveGate !== null + ) { + const gate = v2ResolveGate; + v2ResolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + return { + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + + // Prime 1.0.0 and capture its launch identity. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + const v1Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v1Inspection.status).toBe("ready"); + const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; + + // Start a refresh that upgrades 1.0.0 -> 2.0.0 mid-enrichment while the live watcher stays active. + remoteVersion = "2.0.0"; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v2-probed-a", "v2-probed-b"]), + ); + yield* realCatalog.invalidateIndex(); + const resolveGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + v2ResolveGate = resolveGate; + const v2ProbedReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(resolveGate.started); + const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v2Inspection.status).toBe("ready"); + const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; + expect(v2Identity).not.toBe(v1Identity); + + // Queue a v1 watcher update on this active enrichment fiber, then publish v2 live state before the v2 probe lands. + const staleGate = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + matchSlug: "v1-queued-a", + }; + queuedStaleConfigGate = staleGate; + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-queued-a", + availableModels: [ + { modelId: "v1-queued-a", name: "v1-queued-a" }, + { modelId: "v1-queued-b", name: "v1-queued-b" }, + ], + }), + v1Identity, + ); + yield* Deferred.await(staleGate.entered); + + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-live-cmd" }], skills: [] }, + v2Identity, + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v2-live-a", + availableModels: [ + { modelId: "v2-live-a", name: "v2-live-a" }, + { modelId: "v2-live-b", name: "v2-live-b" }, + ], + }), + v2Identity, + ); + yield* Deferred.succeed(resolveGate.release, undefined); + + const publishedV2 = Option.getOrThrow(yield* Fiber.join(v2ProbedReady)); + expect(publishedV2.models.map((model) => model.slug)).toEqual(["v2-live-a", "v2-live-b"]); + expect(publishedV2.slashCommands).toEqual([{ name: "v2-live-cmd" }]); + + // Releasing the queued v1 watcher callback and publishing late v1 updates must not overwrite v2. + const liveRaceSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( + (snapshot) => + snapshot.models.some((model) => model.slug === "v2-final-a") && + snapshot.slashCommands.some((command) => command.name === "v2-after-race"), + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.succeed(staleGate.release, undefined); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-late-a", + availableModels: [ + { modelId: "v1-late-a", name: "v1-late-a" }, + { modelId: "v1-late-b", name: "v1-late-b" }, + ], + }), + v1Identity, + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v1-late-cmd" }], skills: [] }, + v1Identity, + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v2-final-a", + availableModels: [ + { modelId: "v2-final-a", name: "v2-final-a" }, + { modelId: "v2-final-b", name: "v2-final-b" }, + ], + }), + v2Identity, + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-after-race" }], skills: [] }, + v2Identity, + ); + const observedAfterRace = yield* Fiber.join(liveRaceSnapshots); + expect( + observedAfterRace.every( + (snapshot) => + !snapshot.models.some( + (model) => model.slug === "v1-queued-a" || model.slug === "v1-late-a", + ) && !snapshot.slashCommands.some((command) => command.name === "v1-late-cmd"), + ), + ).toBe(true); + const afterRace = observedAfterRace[observedAfterRace.length - 1]!; + expect(afterRace.models.map((model) => model.slug)).toEqual(["v2-final-a", "v2-final-b"]); + expect(afterRace.slashCommands).toEqual([{ name: "v2-after-race" }]); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 2b1b8affa10a6..78b307c332776 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -112,14 +112,29 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly configuration: AcpRegistryLiveConfiguration; readonly customModels: ReadonlyArray; readonly now: number; + readonly runtimeIdentity?: string | null; }): AcpRegistryEnrichmentCache { - const { cache, configuration, customModels, now } = input; + const { cache, configuration, customModels, now, runtimeIdentity } = 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 }; } + const entryRuntimeIdentity = runtimeIdentityFor( + cache.entry.provider, + cache.entry.launchIdentity ?? null, + ); + if ( + runtimeIdentity !== undefined && + runtimeIdentity !== null && + entryRuntimeIdentity !== null && + entryRuntimeIdentity !== runtimeIdentity + ) { + // Live configuration belongs to a different runtime than the cached probe; + // leave the cache untouched so an in-flight probe for the new runtime can finish. + return cache; + } const provider = applyAcpRegistryLiveConfiguration( cache.entry.provider, configuration, @@ -295,6 +310,7 @@ function baseSnapshot( readonly version: string | null; readonly status: ServerProvider["status"]; readonly auth: ServerProvider["auth"]; + readonly icon?: string; readonly documentationUrl?: string; readonly message?: string; readonly probe?: AcpRegistryConfigurationProbeResult; @@ -304,7 +320,7 @@ function baseSnapshot( const iconUrl = input.settings.source === "local" ? null - : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon) ?? + : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon ?? input.icon) ?? officialAcpRegistryIconUrlForAgentId(input.settings.agentId)); return { instanceId: input.instanceId, @@ -445,15 +461,20 @@ function applyRegistryReadinessMetadata( provider: ServerProvider, baseSnapshot: ServerProvider, ): ServerProvider { + let next = provider; const documentationUrl = baseSnapshot.setup?.documentationUrl; - if (provider.setup === undefined || provider.setup.documentationUrl === documentationUrl) { - return provider; + if (next.setup !== undefined && next.setup.documentationUrl !== documentationUrl) { + const { documentationUrl: _previous, ...setup } = next.setup; + next = { + ...next, + setup: documentationUrl === undefined ? setup : { ...setup, documentationUrl }, + }; } - const { documentationUrl: _previous, ...setup } = provider.setup; - return { - ...provider, - setup: documentationUrl === undefined ? setup : { ...setup, documentationUrl }, - }; + if (next.iconUrl !== baseSnapshot.iconUrl) { + const { iconUrl: _previousIcon, ...rest } = next; + next = baseSnapshot.iconUrl === undefined ? rest : { ...rest, iconUrl: baseSnapshot.iconUrl }; + } + return next; } const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")( @@ -502,6 +523,9 @@ export function buildCheckedAcpRegistrySnapshot( : undefined; return baseSnapshot({ ...input, + ...(input.inspection.status === "ready" && input.inspection.icon + ? { icon: input.inspection.icon } + : {}), ...(input.inspection.status === "ready" && input.inspection.documentationUrl ? { documentationUrl: input.inspection.documentationUrl } : {}), @@ -540,6 +564,7 @@ export function buildCheckedAcpRegistrySnapshot( interface CheckedAcpRegistryReadiness { readonly snapshot: ServerProvider; readonly launchIdentity: string | null; + readonly indexRevision: number | null; } function runtimeIdentityFor( @@ -556,6 +581,17 @@ function readinessSignature(readiness: CheckedAcpRegistryReadiness) { status: readiness.snapshot.status, message: readiness.snapshot.message, documentationUrl: readiness.snapshot.setup?.documentationUrl, + iconUrl: readiness.snapshot.iconUrl, + launchIdentity: readiness.launchIdentity, + }; +} + +function installedRegistrySignature(readiness: CheckedAcpRegistryReadiness) { + return { + installed: readiness.snapshot.installed, + version: readiness.snapshot.version, + documentationUrl: readiness.snapshot.setup?.documentationUrl, + iconUrl: readiness.snapshot.iconUrl, launchIdentity: readiness.launchIdentity, }; } @@ -570,13 +606,23 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( }, probeConfiguration: AcpRegistryConfigurationProbe, ): Effect.fn.Return< - { readonly provider: ServerProvider; readonly launchIdentity: string | null }, + { + readonly provider: ServerProvider; + readonly launchIdentity: string | null; + readonly indexRevision: number | null; + readonly cacheable: boolean; + }, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements > { const checkedAt = DateTime.formatIso(yield* DateTime.now); if (!input.settings.enabled) { - return { provider: yield* buildInitialAcpRegistrySnapshot(input), launchIdentity: null }; + return { + provider: yield* buildInitialAcpRegistrySnapshot(input), + launchIdentity: null, + indexRevision: null, + cacheable: false, + }; } const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); @@ -591,8 +637,12 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( }, }), launchIdentity: null, + indexRevision: null, + cacheable: false, }; } + const inspectedIndexRevision = + "indexRevision" in inspected.success ? (inspected.success.indexRevision ?? null) : null; if (inspected.success.status !== "ready") { return { provider: buildCheckedAcpRegistrySnapshot({ @@ -601,9 +651,10 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( inspection: inspected.success, }), launchIdentity: null, + indexRevision: inspectedIndexRevision, + cacheable: false, }; } - const launchIdentity = inspected.success.launchIdentity ?? null; const probed = yield* Effect.result( probeConfiguration({ instanceId: input.instanceId, @@ -612,21 +663,76 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( environment: providerProbeEnvironment(input.environment), }), ); + if (Result.isFailure(probed)) { + return { + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: inspected.success, + probeError: probed.failure, + }), + launchIdentity: inspected.success.launchIdentity ?? null, + indexRevision: inspectedIndexRevision, + cacheable: false, + }; + } + if (input.settings.source === "local") { + return { + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: inspected.success, + probe: probed.success, + }), + launchIdentity: null, + indexRevision: null, + cacheable: true, + }; + } + const resolved = probed.success.resolved; + if (resolved === undefined) { + return { + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: inspected.success, + probe: probed.success, + }), + launchIdentity: null, + indexRevision: null, + cacheable: inspected.success.launchIdentity === undefined, + }; + } + const resolvedVersion = + input.settings.commandPath.trim().length > 0 + ? null + : (resolved.agent?.version ?? inspected.success.version); + const resolvedDocumentationUrl = + resolved.agent === undefined + ? inspected.success.documentationUrl + : (resolved.agent.website ?? resolved.agent.repository); + const resolvedIcon = resolved.agent === undefined ? inspected.success.icon : resolved.agent.icon; + const resolvedInspection: AcpRegistrySupport.AcpRegistryInspection = { + status: "ready", + agentId: inspected.success.agentId, + version: resolvedVersion, + distribution: resolved.distribution, + ...(resolved.launchIdentity === undefined ? {} : { launchIdentity: resolved.launchIdentity }), + ...(resolved.indexRevision === undefined ? {} : { indexRevision: resolved.indexRevision }), + ...(resolvedIcon ? { icon: resolvedIcon } : {}), + ...(resolvedDocumentationUrl ? { documentationUrl: resolvedDocumentationUrl } : {}), + }; return { - provider: Result.isFailure(probed) - ? buildCheckedAcpRegistrySnapshot({ - ...input, - checkedAt, - inspection: inspected.success, - probeError: probed.failure, - }) - : buildCheckedAcpRegistrySnapshot({ - ...input, - checkedAt, - inspection: inspected.success, - probe: probed.success, - }), - launchIdentity, + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: resolvedInspection, + probe: probed.success, + }), + launchIdentity: resolved.launchIdentity ?? null, + indexRevision: resolved.indexRevision ?? null, + cacheable: + resolved.launchIdentity !== undefined || inspected.success.launchIdentity === undefined, }; }); @@ -652,7 +758,11 @@ const checkAcpRegistryProviderReadinessWithIdentity = Effect.fn( ): Effect.fn.Return { const checkedAt = DateTime.formatIso(yield* DateTime.now); if (!input.settings.enabled) { - return { snapshot: yield* buildInitialAcpRegistrySnapshot(input), launchIdentity: null }; + return { + snapshot: yield* buildInitialAcpRegistrySnapshot(input), + launchIdentity: null, + indexRevision: null, + }; } const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); @@ -666,6 +776,10 @@ const checkAcpRegistryProviderReadinessWithIdentity = Effect.fn( } : inspected.success, }); + const indexRevision = + inspected._tag === "Success" && "indexRevision" in inspected.success + ? (inspected.success.indexRevision ?? null) + : null; return inspected._tag === "Success" && inspected.success.status === "ready" ? { snapshot: { @@ -673,8 +787,9 @@ const checkAcpRegistryProviderReadinessWithIdentity = Effect.fn( message: "Checking ACP authentication, models, and commands in the background...", }, launchIdentity: inspected.success.launchIdentity ?? null, + indexRevision, } - : { snapshot, launchIdentity: null }; + : { snapshot, launchIdentity: null, indexRevision }; }); export const checkAcpRegistryProviderReadiness = ( @@ -791,20 +906,30 @@ export const AcpRegistryDriver: ProviderDriver(null); const clearLiveState = ( - Option.isSome(runtimeCoordinator) + options?: AcpRegistryRuntimeCoordinator.AcpRegistryClearLiveStateOptions, + ) => + (Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value - .clearLiveConfiguration(instanceId) - .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId))) + .clearLiveConfiguration(instanceId, options) + .pipe( + Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId, options)), + ) : Effect.void - ).pipe( - Effect.andThen(clearLearnedModels), - Effect.andThen(Ref.set(activeRuntimeIdentity, null)), - ); + ).pipe( + Effect.andThen(clearLearnedModels), + Effect.andThen(Ref.set(activeRuntimeIdentity, options?.preserveRuntimeIdentity ?? null)), + ); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, - options?: { readonly applySessionLiveState?: boolean }, + options?: { + readonly applySessionLiveState?: boolean; + readonly sessionRuntimeIdentity?: string | null; + readonly requireMatchingRuntimeIdentity?: boolean; + readonly useLearnedModels?: boolean; + readonly persistLearnedModels?: boolean; + }, ) { - if (!input.installed) return input; + if (!input.installed) return { provider: input, appliedLiveConfiguration: false }; if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); const provider = input.enabled && @@ -813,29 +938,66 @@ export const AcpRegistryDriver: ProviderDriver { - const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(configuration, { - onNone: () => Effect.succeed(withCommands), - onSome: (liveConfiguration) => applyLiveConfiguration(withCommands, liveConfiguration), - }).pipe( - Effect.map((withConfiguration) => - applyAcpRegistryUrlAuthAction(withConfiguration, authAction), - ), - ); - }), - ); + }); + const withCommands = applyAcpRegistryAvailableCommands(provider, commands); + const withConfiguration = yield* Option.match(configuration, { + onNone: () => Effect.succeed(withCommands), + onSome: (liveConfiguration) => { + if (options?.persistLearnedModels === false) { + return ( + options.useLearnedModels === false + ? Effect.succeed>([]) + : Ref.get(learnedModels) + ).pipe( + Effect.map((learned) => + applyAcpRegistryLiveConfiguration( + withCommands, + liveConfiguration, + effectiveConfig.customModels, + learned.length > 0 ? learned : withCommands.models, + ), + ), + ); + } + return options?.useLearnedModels === false + ? Effect.succeed( + applyAcpRegistryLiveConfiguration( + withCommands, + liveConfiguration, + effectiveConfig.customModels, + withCommands.models, + ), + ) + : applyLiveConfiguration(withCommands, liveConfiguration); + }, + }); + return { + provider: applyAcpRegistryUrlAuthAction(withConfiguration, authAction), + appliedLiveConfiguration: Option.isSome(configuration), + }; }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. const reportedLocalVersion = yield* Ref.make(null); @@ -846,7 +1008,7 @@ export const AcpRegistryDriver: ProviderDriver checkAcpRegistryProviderReadinessWithIdentity(readinessInput).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.flatMap(({ snapshot, launchIdentity }) => + Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => Ref.get(reportedLocalVersion).pipe( Effect.map((version) => ({ snapshot: @@ -854,12 +1016,15 @@ export const AcpRegistryDriver: ProviderDriver + Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => Ref.modify(activeRuntimeIdentity, (previousIdentity) => { - const nextIdentity = runtimeIdentityFor(snapshot, launchIdentity); + const nextIdentity = snapshot.installed + ? runtimeIdentityFor(snapshot, launchIdentity) + : null; if ( options?.seedActiveRuntimeIdentity === true && snapshot.installed && @@ -871,14 +1036,25 @@ export const AcpRegistryDriver: ProviderDriver { - const nextIdentity = runtimeIdentityFor(snapshot, launchIdentity); - const applySessionLiveState = - (options?.applySessionLiveState ?? true) && - (previousIdentity === null || - nextIdentity === null || - previousIdentity === nextIdentity); - return withLiveRuntimeState(snapshot, { applySessionLiveState }).pipe( - Effect.map((withState) => ({ snapshot: withState, launchIdentity })), + const nextIdentity = snapshot.installed + ? runtimeIdentityFor(snapshot, launchIdentity) + : null; + const runtimeChanged = + previousIdentity !== null && + nextIdentity !== null && + previousIdentity !== nextIdentity; + return withLiveRuntimeState(snapshot, { + applySessionLiveState: options?.applySessionLiveState ?? true, + sessionRuntimeIdentity: nextIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: !runtimeChanged, + }).pipe( + Effect.map(({ provider }) => ({ + snapshot: provider, + launchIdentity, + indexRevision, + })), ); }), ), @@ -906,6 +1082,8 @@ export const AcpRegistryDriver: ProviderDriver 0; const lastSeenIndexRevision = yield* Ref.make(0); + const acknowledgeRevision = (revision: number) => + Ref.update(lastSeenIndexRevision, (seen) => Math.max(seen, revision)); const refreshRegistryIndex = Effect.fn("AcpRegistryDriver.refreshRegistryIndex")(function* () { return yield* catalog .refreshIndex({ @@ -945,14 +1123,20 @@ export const AcpRegistryDriver: ProviderDriver current.generation === cacheState.generation @@ -967,7 +1151,12 @@ export const AcpRegistryDriver: ProviderDriver( + snapshot.installed + ? runtimeIdentityFor(initialReadiness.snapshot, initialReadiness.launchIdentity) + : null, + ); + const checkLiveUpdate = (meta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta) => + Effect.all({ + isCurrent: meta.isCurrent, + expected: Ref.get(expectedRuntimeIdentity), + active: Ref.get(activeRuntimeIdentity), + }).pipe( + Effect.map(({ isCurrent, expected, active }) => { + const runtimeTransitioning = + active !== null && expected !== null && active !== expected; + if (!isCurrent) { + return { accepted: false, expected, runtimeTransitioning } as const; + } + if (meta.runtimeIdentity !== undefined) { + return { + accepted: expected === null || meta.runtimeIdentity === expected, + expected, + runtimeTransitioning, + } as const; + } + return { + accepted: !runtimeTransitioning, + expected, + runtimeTransitioning, + } as const; + }), + ); const runProbeAndPublish = (target: CheckedAcpRegistryReadiness) => (Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( @@ -1008,39 +1231,64 @@ export const AcpRegistryDriver: ProviderDriver Effect.succeed(false), - onSome: ({ provider, launchIdentity, generation }) => + onNone: () => + Effect.succeed<{ + readonly published: boolean; + readonly readiness: CheckedAcpRegistryReadiness | null; + }>({ published: false, readiness: null }), + onSome: ({ provider, launchIdentity, indexRevision, generation }) => liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => { - if (current.generation !== generation) return Effect.succeed(false); - const nextIdentity = runtimeIdentityFor(provider, launchIdentity); - return Ref.get(activeRuntimeIdentity).pipe( - Effect.flatMap((previousIdentity) => { - const runtimeChanged = - previousIdentity !== null && - nextIdentity !== null && - previousIdentity !== nextIdentity; - return withLiveRuntimeState(provider, { - applySessionLiveState: !runtimeChanged, - }).pipe( - Effect.flatMap(tryPublishSnapshot), - Effect.tap((published) => - !published - ? Effect.void - : (runtimeChanged ? clearLiveState : Effect.void).pipe( - Effect.andThen( - nextIdentity === null - ? Effect.void - : Ref.set(activeRuntimeIdentity, nextIdentity), - ), - ), - ), - ); - }), - ); - }), - ), + Effect.gen(function* () { + const current = yield* Ref.get(enrichmentCache); + if (current.generation !== generation) { + return { published: false, readiness: null }; + } + const nextIdentity = provider.installed + ? runtimeIdentityFor(provider, launchIdentity) + : null; + const previousIdentity = yield* Ref.get(activeRuntimeIdentity); + const runtimeChanged = + previousIdentity !== null && + nextIdentity !== null && + previousIdentity !== nextIdentity; + const { provider: nextSnapshot, appliedLiveConfiguration } = + yield* withLiveRuntimeState(provider, { + sessionRuntimeIdentity: nextIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: false, + }); + const published = yield* tryPublishSnapshot(nextSnapshot); + if (published) { + if (!provider.installed) { + if (previousIdentity !== null || current.entry !== null) { + yield* clearLiveState(); + yield* invalidateEnrichmentCache; + } + yield* Ref.set(expectedRuntimeIdentity, null); + } else if (runtimeChanged) { + yield* clearLiveState({ preserveRuntimeIdentity: nextIdentity }); + if (appliedLiveConfiguration) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + yield* Ref.set(expectedRuntimeIdentity, nextIdentity); + } else { + if (appliedLiveConfiguration && nextSnapshot.models !== provider.models) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + if (nextIdentity !== null) { + yield* Ref.set(activeRuntimeIdentity, nextIdentity); + } + yield* Ref.set(expectedRuntimeIdentity, nextIdentity); + } + } + return { + published, + readiness: published + ? { snapshot: provider, launchIdentity, indexRevision } + : null, + }; + }), ), }), ), @@ -1050,48 +1298,53 @@ export const AcpRegistryDriver: ProviderDriver + ({ slashCommands, skills }, meta) => liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - current.installed - ? publishSnapshot({ - ...current, - slashCommands, - skills, - }) - : Effect.void, - ), - ), + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return; + const current = yield* getSnapshot; + if (!current.installed) return; + yield* tryPublishSnapshot({ + ...current, + slashCommands, + skills, + }); + }), ), ); const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( instanceId, - (configuration) => + (configuration, meta) => liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - current.installed - ? applyLiveConfiguration(current, configuration).pipe( - Effect.tap(() => - Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => - Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - }), - ), - ), - ), - ), - Effect.flatMap(publishSnapshot), - ) - : Effect.void, - ), - ), + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return; + const current = yield* getSnapshot; + if (!current.installed) return; + const learned = gate.runtimeTransitioning ? [] : yield* Ref.get(learnedModels); + const next = applyAcpRegistryLiveConfiguration( + current, + configuration, + effectiveConfig.customModels, + learned.length > 0 ? learned : current.models, + ); + const published = yield* tryPublishSnapshot(next); + if (!published) return; + if (!gate.runtimeTransitioning && next.models !== current.models) { + yield* Ref.set(learnedModels, next.models); + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + runtimeIdentity: meta.runtimeIdentity ?? gate.expected, + }), + ); + }), ), ); const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( @@ -1101,9 +1354,9 @@ export const AcpRegistryDriver: ProviderDriver current.installed - ? publishSnapshot( + ? tryPublishSnapshot( applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)), - ) + ).pipe(Effect.asVoid) : Effect.void, ), ), @@ -1117,6 +1370,29 @@ export const AcpRegistryDriver: ProviderDriver + liveSnapshotSemaphore.withPermit( + Effect.all({ + active: Ref.get(activeRuntimeIdentity), + cache: Ref.get(enrichmentCache), + }).pipe( + Effect.flatMap(({ active, cache }) => + active === null && cache.entry === null + ? Effect.void + : tryPublishSnapshot(snapshot).pipe( + Effect.tap((published) => + published + ? clearLiveState().pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen(Ref.set(expectedRuntimeIdentity, null)), + ) + : Effect.void, + ), + Effect.asVoid, + ), + ), + ), + ); const publishUninstalled = ( rechecked: CheckedAcpRegistryReadiness, shouldClearLiveState: boolean, @@ -1129,33 +1405,58 @@ export const AcpRegistryDriver: ProviderDriver published && shouldClearLiveState - ? clearLiveState.pipe(Effect.andThen(invalidateEnrichmentCache)) + ? clearLiveState().pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen(Ref.set(expectedRuntimeIdentity, null)), + ) : Effect.void, ), ), ); if (!snapshot.installed) { + yield* retireActiveRuntimeIfNeeded(); if (!tracksRegistryIndex) return; const revision = yield* refreshRegistryIndex(); - if (revision === (yield* Ref.get(lastSeenIndexRevision))) return; + if (revision <= (yield* Ref.get(lastSeenIndexRevision))) return; + if ( + initialReadiness.indexRevision !== null && + revision <= initialReadiness.indexRevision + ) { + yield* acknowledgeRevision(revision); + return; + } const rechecked = yield* inspectReadiness({ applySessionLiveState: false }); if (!rechecked.snapshot.installed) { const published = yield* publishUninstalled(rechecked, false); - if (published) { - yield* Ref.set(lastSeenIndexRevision, revision); + if ( + published && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); } return; } + const nextIdentity = runtimeIdentityFor(rechecked.snapshot, rechecked.launchIdentity); const publishedRechecked = yield* liveSnapshotSemaphore.withPermit( tryPublishSnapshot(rechecked.snapshot).pipe( - Effect.tap((published) => (published ? clearLiveState : Effect.void)), + Effect.tap((published) => + published + ? clearLiveState( + nextIdentity === null ? undefined : { preserveRuntimeIdentity: nextIdentity }, + ).pipe(Effect.andThen(Ref.set(expectedRuntimeIdentity, nextIdentity))) + : Effect.void, + ), ), ); if (!publishedRechecked) return; yield* runWithLiveWatchers( runProbeAndPublish(rechecked).pipe( - Effect.tap((published) => - published ? Ref.set(lastSeenIndexRevision, revision) : Effect.void, + Effect.tap(({ published, readiness }) => + published && + readiness !== null && + (readiness.indexRevision === null || readiness.indexRevision >= revision) + ? acknowledgeRevision(readiness.indexRevision ?? revision) + : Effect.void, ), Effect.asVoid, ), @@ -1164,27 +1465,55 @@ export const AcpRegistryDriver: ProviderDriver= revision + ) { + yield* acknowledgeRevision(publishedReadiness.indexRevision); + return; + } const rechecked = yield* inspectReadiness(); if (!rechecked.snapshot.installed) { const published = yield* publishUninstalled(rechecked, true); - if (published) { - yield* Ref.set(lastSeenIndexRevision, revision); + if ( + published && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); } return; } - if (!Equal.equals(readinessSignature(rechecked), readinessSignature(initialReadiness))) { - const published = yield* runProbeAndPublish(rechecked); - if (published) { - yield* Ref.set(lastSeenIndexRevision, revision); + if ( + !Equal.equals( + installedRegistrySignature(rechecked), + installedRegistrySignature(publishedReadiness), + ) + ) { + const recheckedProbe = yield* runProbeAndPublish(rechecked); + if ( + recheckedProbe.published && + recheckedProbe.readiness !== null && + (recheckedProbe.readiness.indexRevision === null || + recheckedProbe.readiness.indexRevision >= revision) + ) { + yield* acknowledgeRevision(recheckedProbe.readiness.indexRevision ?? revision); } return; } - if (initialPublished) { - yield* Ref.set(lastSeenIndexRevision, revision); + if ( + initialProbe.published && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); } }); yield* runWithLiveWatchers(publishEnrichment); @@ -1234,7 +1563,7 @@ export const AcpRegistryDriver: ProviderDriver; readonly skills: ReadonlyArray; + readonly resolved?: AcpRegistryConfigurationProbeResolved; } export type AcpRegistryConfigurationProbe = ( @@ -635,6 +643,16 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: result.commands.slashCommands, skills: result.commands.skills, + resolved: { + ...(result.resolved.agent === undefined ? {} : { agent: result.resolved.agent }), + distribution: result.resolved.distribution, + ...(result.resolved.launchIdentity === undefined + ? {} + : { launchIdentity: result.resolved.launchIdentity }), + ...(result.resolved.indexRevision === undefined + ? {} + : { indexRevision: result.resolved.indexRevision }), + }, }; }, ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..6e776751f3add 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -428,11 +428,13 @@ export interface AcpAdapterV2Flavor { readonly ignoreSessionUpdate?: (notification: EffectAcpSchema.SessionNotification) => boolean; readonly onAvailableCommandsUpdate?: ( commands: ReadonlyArray, + runtime?: AcpSessionRuntime.AcpSessionRuntime["Service"], ) => Effect.Effect; readonly onSessionConfigurationUpdate?: ( configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, modelState: EffectAcpSchema.SessionModelState | null | undefined, + runtime?: AcpSessionRuntime.AcpSessionRuntime["Service"], ) => Effect.Effect; readonly onUrlElicitation?: (input: { readonly elicitationId: string; @@ -7077,7 +7079,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); return updated; }); - yield* flavor.onAvailableCommandsUpdate?.(advertisedCommands) ?? Effect.void; + yield* ( + flavor.onAvailableCommandsUpdate?.(advertisedCommands, runtime) ?? Effect.void + ); } if ( notification.update.sessionUpdate === "config_option_update" || @@ -7088,6 +7092,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* runtime.getConfigOptions, yield* runtime.getModeState, (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, + runtime, ) ?? Effect.void ); } @@ -7224,6 +7229,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* targetRuntime.getConfigOptions, yield* targetRuntime.getModeState, result.sessionSetupResult.models, + targetRuntime, ) ?? Effect.void ); }); @@ -8363,6 +8369,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* runtime.getConfigOptions, yield* runtime.getModeState, (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, + runtime, ) ?? Effect.void ); }); diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 416aae67a8142..02f7fb1fa1649 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -103,17 +103,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( generation: number, nextSnapshot: ServerProvider, ): Effect.fn.Return { - const outcome = yield* Ref.modify( - snapshotStateRef, - ( - state, - ): readonly [ - { readonly applied: boolean; readonly snapshot: ServerProvider | null }, - ProviderSnapshotState, - ] => { - if (state.enrichmentGeneration !== generation) { - return [{ applied: false, snapshot: null }, state]; - } + const outcome = yield* Ref.modify(snapshotStateRef, (state) => { + let applied = true; + let snapshot: ServerProvider | null = null; + let nextState = state; + if (state.enrichmentGeneration !== generation) { + applied = false; + } else { // Enrichment must not revert usage updates newer than its input snapshot. const merged = withUsageLimits( state.usageAuthLabel === undefined @@ -124,15 +120,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( }, state.snapshot.usageLimits, ); - if (Equal.equals(state.snapshot, merged)) { - return [{ applied: true, snapshot: null }, state]; + if (!Equal.equals(state.snapshot, merged)) { + snapshot = merged; + nextState = { ...state, snapshot: merged }; } - return [ - { applied: true, snapshot: merged }, - { ...state, snapshot: merged }, - ]; - }, - ); + } + return [{ applied, snapshot }, nextState] as const; + }); if (outcome.snapshot !== null) { yield* PubSub.publish(changesPubSub, outcome.snapshot); } From c7c0ea18e02af6848c9ea342a014734978779ffe Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 12:05:10 +0000 Subject: [PATCH 11/28] fix(acp-registry): harden binary slots, offline fallback, and coordinator isolation --- .../AcpRegistryRuntimeCoordinator.test.ts | 101 ++++ .../server/AcpRegistryRuntimeCoordinator.ts | 464 +++++++-------- .../src/server/AcpRegistrySupport.test.ts | 265 ++++++++- .../src/server/AcpRegistrySupport.ts | 533 ++++++++++++++---- .../src/server/driver.test.ts | 279 ++++++++- .../src/server/driver.ts | 286 +++++++--- .../provider-acp-registry/src/server/probe.ts | 2 + 7 files changed, 1445 insertions(+), 485 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index a6662853ae028..5efe9b82e0315 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -257,4 +257,105 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); + + it.effect( + "isolates per-runtime state, evaluates chained clear watermarks, and drops disposed instances", + () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_runtime_scoped"); + const metas: Array<{ + readonly label: string; + readonly meta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta; + }> = []; + const expectedCount = { target: 0, gate: yield* Deferred.make() }; + const watcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands, meta) => + Effect.gen(function* () { + metas.push({ label: commands.slashCommands[0]?.name ?? "empty", meta }); + if (metas.length >= expectedCount.target) { + yield* Deferred.succeed(expectedCount.gate, undefined); + } + }), + ) + .pipe(Effect.forkChild); + + const publishAndWait = (name: string, runtimeIdentity?: string) => + Effect.gen(function* () { + expectedCount.target = metas.length + 1; + expectedCount.gate = yield* Deferred.make(); + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name }], skills: [] }, + runtimeIdentity, + ); + yield* Deferred.await(expectedCount.gate); + return metas[metas.length - 1]!.meta; + }); + + // 1. Late update from A must not evict B's stored entry. + const metaA = yield* publishAndWait("cmd-a", "runtime-a"); + const metaB = yield* publishAndWait("cmd-b", "runtime-b"); + const metaUntagged = yield* publishAndWait("cmd-untagged"); + const metaLateA = yield* publishAndWait("cmd-a-late", "runtime-a"); + expect( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-b", + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] })); + expect(yield* metaA.isCurrent).toBe(true); + expect(yield* metaB.isCurrent).toBe(true); + expect(yield* metaUntagged.isCurrent).toBe(true); + expect(yield* metaLateA.isCurrent).toBe(true); + + // 2. Chained preserve clears (preserve B -> preserve C -> preserve B) keep only matching entries current. + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-b", + }); + expect(yield* metaA.isCurrent).toBe(false); + expect(yield* metaLateA.isCurrent).toBe(false); + expect(yield* metaUntagged.isCurrent).toBe(false); + expect(yield* metaB.isCurrent).toBe(true); + expect( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-a", + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.none()); + expect(yield* coordinator.getAvailableCommands(instanceId)).toEqual( + Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] }), + ); + + const metaC = yield* publishAndWait("cmd-c", "runtime-c"); + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-c", + }); + expect(yield* metaB.isCurrent).toBe(false); + expect(yield* metaC.isCurrent).toBe(true); + + // Returning to preserve B after preserve C must NOT resurrect the older pre-C metaB. + const metaB2 = yield* publishAndWait("cmd-b-2", "runtime-b"); + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-b", + }); + expect(yield* metaB.isCurrent).toBe(false); + expect(yield* metaC.isCurrent).toBe(false); + expect(yield* metaB2.isCurrent).toBe(true); + + // 3. Full clear invalidates everything published before it; subsequent publications stay current. + yield* coordinator.clearAvailableCommands(instanceId); + expect(yield* metaB2.isCurrent).toBe(false); + expect(Option.isNone(yield* coordinator.getAvailableCommands(instanceId))).toBe(true); + + const metaAfterFullClear = yield* publishAndWait("cmd-fresh", "runtime-b"); + expect(yield* metaAfterFullClear.isCurrent).toBe(true); + + // 4. Disposing an instance drops its state and marks earlier updates stale. + yield* coordinator.clearAvailableCommands(instanceId, { dispose: true }); + expect(yield* metaAfterFullClear.isCurrent).toBe(false); + expect(Option.isNone(yield* coordinator.getAvailableCommands(instanceId))).toBe(true); + yield* Fiber.interrupt(watcher); + }).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 a460782fc35a3..8335257cf50b3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -24,6 +24,7 @@ export interface AcpRegistryLiveUpdateMeta { export interface AcpRegistryClearLiveStateOptions { readonly preserveRuntimeIdentity?: string; + readonly dispose?: boolean; } export interface AcpRegistryReadLiveStateOptions { @@ -31,32 +32,6 @@ export interface AcpRegistryReadLiveStateOptions { readonly requireMatchingRuntimeIdentity?: boolean; } -interface AvailableCommandsEntry { - readonly commands: AcpRegistryAvailableCommands; - readonly runtimeIdentity: string | undefined; - readonly revision: number; -} - -interface LiveConfigurationEntry { - readonly configuration: AcpRegistryLiveConfiguration; - readonly runtimeIdentity: string | undefined; - readonly revision: number; -} - -interface AvailableCommandsUpdate { - readonly instanceId: ProviderInstanceId; - readonly commands: AcpRegistryAvailableCommands; - readonly runtimeIdentity: string | undefined; - readonly revision: number; -} - -interface LiveConfigurationUpdate { - readonly instanceId: ProviderInstanceId; - readonly configuration: AcpRegistryLiveConfiguration; - readonly runtimeIdentity: string | undefined; - readonly revision: number; -} - interface UrlAuthActionUpdate { readonly instanceId: ProviderInstanceId; readonly action: AcpRegistryUrlAuthAction | null; @@ -189,25 +164,180 @@ function isLiveUpdateCurrent( return true; } +interface ChannelEntry { + readonly value: T; + readonly runtimeIdentity: string | undefined; + readonly revision: number; +} + +interface InstanceChannelState { + readonly entries: ReadonlyMap>; + readonly latestKey: string | undefined; + readonly hasLatest: boolean; + readonly clear: LiveStateClearState | undefined; +} + +interface ChannelState { + readonly revision: number; + readonly instances: ReadonlyMap>; +} + +interface ChannelUpdate { + readonly instanceId: ProviderInstanceId; + readonly value: T; + readonly runtimeIdentity: string | undefined; + readonly revision: number; +} + +const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveStateChannel")( + function* (name: string) { + const updates = yield* PubSub.unbounded>(); + const stateRef = yield* Ref.make>({ + revision: 0, + instances: new Map(), + }); + + const clear = (instanceId: ProviderInstanceId, options?: AcpRegistryClearLiveStateOptions) => + Ref.update(stateRef, (state) => { + const revision = state.revision + 1; + const nextInstances = new Map(state.instances); + if (options?.dispose === true) { + nextInstances.delete(instanceId); + return { revision, instances: nextInstances }; + } + const existing = state.instances.get(instanceId); + const nextClear = recordLiveStateClear(existing?.clear, revision, options); + const nextEntries = new Map>(); + if (existing !== undefined) { + for (const [key, entry] of existing.entries) { + if (isLiveUpdateCurrent(nextClear, entry.revision, entry.runtimeIdentity)) { + nextEntries.set(key, entry); + } + } + } + const latestEntry = + existing !== undefined && existing.hasLatest + ? nextEntries.get(existing.latestKey) + : undefined; + const fallbackLatest = + latestEntry ?? + Array.from(nextEntries.values()).reduce | undefined>( + (best, entry) => (best === undefined || entry.revision > best.revision ? entry : best), + undefined, + ); + nextInstances.set(instanceId, { + entries: nextEntries, + latestKey: fallbackLatest?.runtimeIdentity, + hasLatest: fallbackLatest !== undefined, + clear: nextClear, + }); + return { revision, instances: nextInstances }; + }); + + const publish = (instanceId: ProviderInstanceId, value: T, runtimeIdentity?: string) => + Ref.modify(stateRef, (state) => { + const revision = state.revision + 1; + const existing = state.instances.get(instanceId); + const nextEntries = new Map(existing?.entries); + nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision }); + const nextInstances = new Map(state.instances); + nextInstances.set(instanceId, { + entries: nextEntries, + latestKey: runtimeIdentity, + hasLatest: true, + clear: existing?.clear, + }); + const event: ChannelUpdate = { instanceId, value, runtimeIdentity, revision }; + return [event, { revision, instances: nextInstances }] as const; + }).pipe( + Effect.flatMap((event) => PubSub.publish(updates, event)), + Effect.asVoid, + ); + + const get = Effect.fn(`AcpRegistryRuntimeCoordinator.${name}`)(function* ( + instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, + ) { + const inst = (yield* Ref.get(stateRef)).instances.get(instanceId); + if (inst === undefined) return Option.none(); + const validEntry = (entry: ChannelEntry | undefined): Option.Option => + entry !== undefined && + isLiveUpdateCurrent(inst.clear, entry.revision, entry.runtimeIdentity) + ? Option.some(entry.value) + : Option.none(); + if (options?.runtimeIdentity !== undefined) { + const exact = validEntry(inst.entries.get(options.runtimeIdentity)); + if (Option.isSome(exact)) return exact; + if (options.requireMatchingRuntimeIdentity === true) return Option.none(); + return validEntry(inst.entries.get(undefined)); + } + if (inst.clear?.preservedRuntimeIdentity !== undefined) { + const preserved = validEntry(inst.entries.get(inst.clear.preservedRuntimeIdentity)); + if (Option.isSome(preserved)) return preserved; + } + return inst.hasLatest ? validEntry(inst.entries.get(inst.latestKey)) : Option.none(); + }); + + const watch = ( + instanceId: ProviderInstanceId, + onUpdate: (value: T, meta: AcpRegistryLiveUpdateMeta) => Effect.Effect, + ) => + Effect.scoped( + Effect.gen(function* () { + // Subscribe before reading to avoid missing publications. + const subscription = yield* PubSub.subscribe(updates); + const inst = (yield* Ref.get(stateRef)).instances.get(instanceId); + const metaFor = ( + runtimeIdentity: string | undefined, + revision: number, + ): AcpRegistryLiveUpdateMeta => ({ + runtimeIdentity, + isCurrent: Ref.get(stateRef).pipe( + Effect.map((state) => { + const current = state.instances.get(instanceId); + return ( + current !== undefined && + isLiveUpdateCurrent(current.clear, revision, runtimeIdentity) + ); + }), + ), + }); + const replayed = + inst === undefined + ? [] + : Array.from(inst.entries.values()) + .filter((entry) => + isLiveUpdateCurrent(inst.clear, entry.revision, entry.runtimeIdentity), + ) + .toSorted((left, right) => left.revision - right.revision); + const replayedRevisions = new Set(replayed.map((entry) => entry.revision)); + for (const entry of replayed) { + yield* onUpdate(entry.value, metaFor(entry.runtimeIdentity, entry.revision)); + } + yield* Stream.fromSubscription(subscription).pipe( + Stream.filter((update) => { + if (update.instanceId !== instanceId) return false; + if (replayedRevisions.delete(update.revision)) return false; + return true; + }), + Stream.runForEach((update) => + onUpdate(update.value, metaFor(update.runtimeIdentity, update.revision)), + ), + ); + }), + ); + + return { clear, publish, get, watch } as const; + }, +); + const make = Effect.gen(function* () { const foregroundStarts = yield* PubSub.unbounded(); const activeForegroundCounts = yield* Ref.make(new Map()); - const availableCommandsUpdates = yield* PubSub.unbounded(); - const availableCommandsByInstance = yield* Ref.make( - new Map(), - ); - const availableCommandsClearsByInstance = yield* Ref.make( - new Map(), - ); - const availableCommandsRevision = yield* Ref.make(0); - const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurationByInstance = yield* Ref.make( - new Map(), - ); - const liveConfigurationClearsByInstance = yield* Ref.make( - new Map(), - ); - const liveConfigurationRevision = yield* Ref.make(0); + const availableCommandsChannel = + yield* makeLiveStateChannel("getAvailableCommands"); + const liveConfigurationChannel = + yield* makeLiveStateChannel("getLiveConfiguration"); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -260,203 +390,6 @@ const make = Effect.gen(function* () { effect, ) => sessionMutationPermit.withPermit(effect); - const matchesReadRuntime = ( - entryRuntimeIdentity: string | undefined, - options?: AcpRegistryReadLiveStateOptions, - ): boolean => { - if (options?.runtimeIdentity === undefined) return true; - if (entryRuntimeIdentity === undefined) { - return options.requireMatchingRuntimeIdentity !== true; - } - return entryRuntimeIdentity === options.runtimeIdentity; - }; - - const clearAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["clearAvailableCommands"] = - (instanceId, options) => - Ref.updateAndGet(availableCommandsRevision, (revision) => revision + 1).pipe( - Effect.flatMap((clearRevision) => - Ref.update(availableCommandsClearsByInstance, (current) => { - const next = new Map(current); - next.set( - instanceId, - recordLiveStateClear(current.get(instanceId), clearRevision, options), - ); - return next; - }), - ), - Effect.andThen( - Ref.update(availableCommandsByInstance, (current) => { - const existing = current.get(instanceId); - if ( - existing === undefined || - (options?.preserveRuntimeIdentity !== undefined && - existing.runtimeIdentity === options.preserveRuntimeIdentity) - ) { - return current; - } - const next = new Map(current); - next.delete(instanceId); - return next; - }), - ), - ); - - const publishAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["publishAvailableCommands"] = - (instanceId, commands, runtimeIdentity) => - Ref.updateAndGet(availableCommandsRevision, (revision) => revision + 1).pipe( - Effect.flatMap((revision) => - Ref.update(availableCommandsByInstance, (current) => { - const next = new Map(current); - next.set(instanceId, { commands, runtimeIdentity, revision }); - return next; - }).pipe( - Effect.andThen( - PubSub.publish(availableCommandsUpdates, { - instanceId, - commands, - runtimeIdentity, - revision, - }), - ), - Effect.asVoid, - ), - ), - ); - - const getAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["getAvailableCommands"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getAvailableCommands")( - function* (instanceId, options) { - const entry = (yield* Ref.get(availableCommandsByInstance)).get(instanceId); - if (entry === undefined || !matchesReadRuntime(entry.runtimeIdentity, options)) { - return Option.none(); - } - return Option.some(entry.commands); - }, - ); - - const watchAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["watchAvailableCommands"] = - (instanceId, onUpdate) => - Effect.scoped( - Effect.gen(function* () { - // Subscribe before reading to avoid missing publications. - const subscription = yield* PubSub.subscribe(availableCommandsUpdates); - const current = (yield* Ref.get(availableCommandsByInstance)).get(instanceId); - const metaFor = ( - runtimeIdentity: string | undefined, - revision: number, - ): AcpRegistryLiveUpdateMeta => ({ - runtimeIdentity, - isCurrent: Ref.get(availableCommandsClearsByInstance).pipe( - Effect.map((clears) => - isLiveUpdateCurrent(clears.get(instanceId), revision, runtimeIdentity), - ), - ), - }); - if (current !== undefined) { - yield* onUpdate(current.commands, metaFor(current.runtimeIdentity, current.revision)); - } - yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => - onUpdate(update.commands, metaFor(update.runtimeIdentity, update.revision)), - ), - ); - }), - ); - - const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = - (instanceId, options) => - Ref.updateAndGet(liveConfigurationRevision, (revision) => revision + 1).pipe( - Effect.flatMap((clearRevision) => - Ref.update(liveConfigurationClearsByInstance, (current) => { - const next = new Map(current); - next.set( - instanceId, - recordLiveStateClear(current.get(instanceId), clearRevision, options), - ); - return next; - }), - ), - Effect.andThen( - Ref.update(liveConfigurationByInstance, (current) => { - const existing = current.get(instanceId); - if ( - existing === undefined || - (options?.preserveRuntimeIdentity !== undefined && - existing.runtimeIdentity === options.preserveRuntimeIdentity) - ) { - return current; - } - const next = new Map(current); - next.delete(instanceId); - return next; - }), - ), - ); - - const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = - (instanceId, configuration, runtimeIdentity) => - Ref.updateAndGet(liveConfigurationRevision, (revision) => revision + 1).pipe( - Effect.flatMap((revision) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, { configuration, runtimeIdentity, revision }), - ).pipe( - Effect.andThen( - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, - runtimeIdentity, - revision, - }), - ), - Effect.asVoid, - ), - ), - ); - - const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")( - function* (instanceId, options) { - const entry = (yield* Ref.get(liveConfigurationByInstance)).get(instanceId); - if (entry === undefined || !matchesReadRuntime(entry.runtimeIdentity, options)) { - return Option.none(); - } - return Option.some(entry.configuration); - }, - ); - - const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = - (instanceId, onUpdate) => - Effect.scoped( - Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); - const current = (yield* Ref.get(liveConfigurationByInstance)).get(instanceId); - const metaFor = ( - runtimeIdentity: string | undefined, - revision: number, - ): AcpRegistryLiveUpdateMeta => ({ - runtimeIdentity, - isCurrent: Ref.get(liveConfigurationClearsByInstance).pipe( - Effect.map((clears) => - isLiveUpdateCurrent(clears.get(instanceId), revision, runtimeIdentity), - ), - ), - }); - if (current !== undefined) { - yield* onUpdate( - current.configuration, - metaFor(current.runtimeIdentity, current.revision), - ); - } - yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => - onUpdate(update.configuration, metaFor(update.runtimeIdentity, update.revision)), - ), - ); - }), - ); - const publishUrlAuthAction = ( instanceId: ProviderInstanceId, action: AcpRegistryUrlAuthAction | null, @@ -494,15 +427,18 @@ const make = Effect.gen(function* () { next.set(instanceId, { action: publishedAction, consent, expiresAt }); return [existing, next] as const; }); + yield* publishUrlAuthAction(instanceId, publishedAction); if (previous !== undefined) { - yield* Deferred.succeed(previous.consent, false).pipe(Effect.ignore); + yield* Deferred.succeed(previous.consent, false); } - yield* publishUrlAuthAction(instanceId, publishedAction); }), ); + const remaining = Duration.millis( + Math.max(0, DateTime.toEpochMillis(expiresAt) - DateTime.toEpochMillis(createdAt)), + ); return yield* Deferred.await(consent).pipe( Effect.timeoutOrElse({ - duration: URL_AUTH_ACTION_TTL, + duration: remaining, orElse: () => Effect.succeed(false), }), ); @@ -512,10 +448,20 @@ const make = Effect.gen(function* () { const acceptUrlAuthentication: AcpRegistryRuntimeCoordinator["Service"]["acceptUrlAuthentication"] = Effect.fn("AcpRegistryRuntimeCoordinator.acceptUrlAuthentication")(function* (input) { - const pending = (yield* Ref.get(pendingUrlAuthActions)).get(input.instanceId); - if (pending?.action.elicitationId !== input.elicitationId) return false; - if (DateTime.isGreaterThanOrEqualTo(yield* DateTime.now, pending.expiresAt)) { - yield* Deferred.succeed(pending.consent, false).pipe(Effect.ignore); + const now = yield* DateTime.now; + const pending = yield* Ref.modify(pendingUrlAuthActions, (current) => { + const existing = current.get(input.instanceId); + if (existing === undefined || existing.action.elicitationId !== input.elicitationId) { + return [undefined, current] as const; + } + const next = new Map(current); + next.delete(input.instanceId); + return [existing, next] as const; + }); + if (pending === undefined) return false; + yield* publishUrlAuthAction(input.instanceId, null); + if (DateTime.toEpochMillis(now) > DateTime.toEpochMillis(pending.expiresAt)) { + yield* Deferred.succeed(pending.consent, false); return false; } return yield* Deferred.succeed(pending.consent, true); @@ -524,7 +470,15 @@ const make = Effect.gen(function* () { const getUrlAuthAction: AcpRegistryRuntimeCoordinator["Service"]["getUrlAuthAction"] = Effect.fn( "AcpRegistryRuntimeCoordinator.getUrlAuthAction", )(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(pendingUrlAuthActions)).get(instanceId)?.action); + const now = yield* DateTime.now; + const pending = (yield* Ref.get(pendingUrlAuthActions)).get(instanceId); + if ( + pending === undefined || + DateTime.toEpochMillis(now) > DateTime.toEpochMillis(pending.expiresAt) + ) { + return Option.none(); + } + return Option.some(pending.action); }); const watchUrlAuthAction: AcpRegistryRuntimeCoordinator["Service"]["watchUrlAuthAction"] = ( @@ -549,14 +503,14 @@ const make = Effect.gen(function* () { withForegroundStartup, runBackgroundProbe, withSessionMutation, - clearAvailableCommands, - publishAvailableCommands, - getAvailableCommands, - watchAvailableCommands, - clearLiveConfiguration, - publishLiveConfiguration, - getLiveConfiguration, - watchLiveConfiguration, + clearAvailableCommands: availableCommandsChannel.clear, + publishAvailableCommands: availableCommandsChannel.publish, + getAvailableCommands: availableCommandsChannel.get, + watchAvailableCommands: availableCommandsChannel.watch, + clearLiveConfiguration: liveConfigurationChannel.clear, + publishLiveConfiguration: liveConfigurationChannel.publish, + getLiveConfiguration: liveConfigurationChannel.get, + watchLiveConfiguration: liveConfigurationChannel.watch, requestUrlAuthentication, acceptUrlAuthentication, getUrlAuthAction, diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index c84ae2cc3cbb7..daf26413f6b2a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -798,7 +798,8 @@ describe("AcpRegistrySupport", () => { ); expect(requests).toEqual([registryUrl, archiveUrl]); - // Repackaging at the same version and cmd path downloads, verifies sha256, replaces the binary, and caches the new receipt. + // Repackaging at the same version installs into an immutable artifact-scoped sibling slot, + // keeping the primary install intact for active sessions while preferring the new slot. currentAgent = makeAgent({ binary: { "linux-x86_64": { @@ -813,15 +814,33 @@ describe("AcpRegistrySupport", () => { yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const third = yield* resolver.resolve(settings(), "/workspace"); const fourth = yield* resolver.resolve(settings(), "/workspace"); - expect(third.spawn.command).toBe(first.spawn.command); - expect(fourth.spawn.command).toBe(first.spawn.command); + expect(third.spawn.command).not.toBe(first.spawn.command); + expect(third.spawn.command).toMatch( + /\/tools\/example-agent\/1\.2\.3\/linux-x86_64-[0-9a-f]{12}\/bin\/example-agent$/u, + ); + expect(fourth.spawn.command).toBe(third.spawn.command); expect(third.launchIdentity).not.toBe(first.launchIdentity); + expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( + "#!/bin/sh\necho example\n", + ); expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( "#!/bin/sh\necho example-repackaged\n", ); expect(requests).toEqual([registryUrl, archiveUrl, registryUrl, replacementArchiveUrl]); - // A failed replacement (checksum mismatch) leaves the existing installed binary intact. + const path = yield* Path.Path; + const managedDirs = yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + platform: "linux", + architecture: "x64", + }); + expect(managedDirs.slice(0, 2)).toEqual([ + path.dirname(third.spawn.command), + path.dirname(first.spawn.command), + ]); + + // A failed replacement (checksum mismatch) leaves existing installed binaries intact. currentAgent = makeAgent({ binary: { "linux-x86_64": { @@ -839,6 +858,13 @@ describe("AcpRegistrySupport", () => { expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( "#!/bin/sh\necho example-repackaged\n", ); + + // Uninstalling removes both the primary slot and the artifact-scoped sibling slot. + expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ + agentId: "example-agent", + removed: true, + }); + expect(yield* fileSystem.exists(`${cacheDir}/tools/example-agent`)).toBe(false); }).pipe( Effect.scoped, Effect.provide( @@ -864,6 +890,177 @@ describe("AcpRegistrySupport", () => { }, ); + it.effect( + "preserves offline legacy binaries without fabricating a receipt, retries same-version archive swaps on download failure, and falls back to prior receipted versions", + () => { + const legacyArchiveUrl = "https://example.test/example-agent-1.0.0.bin"; + const swappedArchiveUrl = "https://example.test/example-agent-1.0.0-fixed.bin"; + const v2ArchiveUrl = "https://example.test/example-agent-2.0.0.bin"; + const v1Bytes = new TextEncoder().encode("#!/bin/sh\necho v1-fixed\n"); + let offline = true; + let failSwappedDownload = false; + let failV2Download = true; + let currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + env: { AGENT_CHANNEL: "v1" }, + }, + }, + }), + version: "1.0.0", + }; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-offline-fallback-", + }); + const toolsDir = path.join(cacheDir, "tools"); + const legacyRoot = path.join(toolsDir, "example-agent", "1.0.0", "linux-x86_64"); + const legacyBinary = path.join(legacyRoot, "bin", "example-agent"); + const legacyReceipt = path.join(legacyRoot, ".t3-artifact.json"); + yield* fileSystem.makeDirectory(path.dirname(legacyBinary), { recursive: true }); + yield* fileSystem.writeFileString(legacyBinary, "#!/bin/sh\necho legacy-v1\n"); + yield* fileSystem.chmod(legacyBinary, 0o755); + yield* fileSystem.makeDirectory(path.join(cacheDir, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(cacheDir, "acp-registry", "registry.json"), + makeRegistry(currentAgent), + ); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir, + registryUrl, + }); + + // 1. Pre-existing receipt-less binary works offline without fabricating a receipt. + const offlineLegacy = yield* resolver.resolve(settings(), "/workspace"); + expect(offlineLegacy.agent?.version).toBe("1.0.0"); + expect(offlineLegacy.spawn.command).toBe(legacyBinary); + expect(offlineLegacy.fallback).toBeUndefined(); + expect(yield* fileSystem.exists(legacyReceipt)).toBe(false); + + // 2. If the registry updates the same-version archive URL and the new download fails, + // the receipt-less legacy install is NOT treated as matching the changed artifact. + offline = false; + failSwappedDownload = true; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: swappedArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-fixed"], + env: { AGENT_CHANNEL: "v1-fixed" }, + }, + }, + }), + version: "1.0.0", + }; + const changedArtifactFailure = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactFailure.reason).toBe("download_failed"); + + // 3. Once the updated same-version archive URL succeeds, download_failed on the stale + // cached URL refreshes the index, retries the new launch signature, and writes an immutable slot. + failSwappedDownload = false; + const swappedResolved = yield* resolver.resolve(settings(), "/workspace"); + expect(swappedResolved.agent?.version).toBe("1.0.0"); + expect(swappedResolved.spawn.command).not.toBe(legacyBinary); + expect(swappedResolved.spawn.command).toMatch( + /linux-x86_64-[0-9a-f]{12}[\\/]bin[\\/]example-agent$/, + ); + expect(yield* fileSystem.readFileString(swappedResolved.spawn.command)).toBe( + "#!/bin/sh\necho v1-fixed\n", + ); + expect(yield* fileSystem.readFileString(legacyBinary)).toBe("#!/bin/sh\necho legacy-v1\n"); + + // 4. A mismatched receipt at the same version is never reused when a repackaged download fails. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.0.0-broken.bin", + cmd: "./bin/example-agent", + args: ["--v1-broken"], + }, + }, + }), + version: "1.0.0", + }; + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const mismatchedSameVersionError = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(mismatchedSameVersionError.reason).toBe("download_failed"); + + // 5. When upstream publishes 2.0.0 whose download fails, resolve falls back to the + // receipted 1.0.0 install with its recorded version, args, env, and fallback=true. + failV2Download = true; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + env: { AGENT_CHANNEL: "v2" }, + }, + }, + }), + version: "2.0.0", + }; + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackToV1 = yield* resolver.resolve(settings(), "/workspace"); + expect(fallbackToV1.fallback).toBe(true); + expect(fallbackToV1.indexRevision).toBeUndefined(); + expect(fallbackToV1.agent?.version).toBe("1.0.0"); + expect(fallbackToV1.spawn.command).toBe(swappedResolved.spawn.command); + expect(fallbackToV1.spawn.args).toEqual(["--v1-fixed"]); + expect(fallbackToV1.spawn.env?.AGENT_CHANNEL).toBe("v1-fixed"); + expect(fallbackToV1.launchIdentity).toBe(swappedResolved.launchIdentity); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (offline) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("offline", { status: 503 })), + ); + } + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(currentAgent))), + ); + } + if (request.url === swappedArchiveUrl && !failSwappedDownload) { + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v1Bytes))); + } + if (request.url === v2ArchiveUrl && !failV2Download) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(new TextEncoder().encode("#!/bin/sh\necho v2\n")), + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ); + }), + ), + ); + }, + ); + it.effect("gives Antigravity a T3-owned temp directory that is removed with the process", () => { const agent = { ...makeAgent({ binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./agy" } } }), @@ -1565,10 +1762,14 @@ describe("AcpRegistrySupport", () => { newPackageInspection.launchIdentity === docsOnlyInspection.launchIdentity, ).toBe(true); - // commandOverride ignores version/package bumps it does not launch, while tracking args and env changes. + // commandOverride ignores version/package bumps it does not launch, while tracking args and env separately. + const hostPlatform = HostProcess.Platform.defaultValue(); + const isWindowsHost = hostPlatform === "win32"; const overridePath = `${packageSwapDir}/override-agent`; yield* fileSystem.writeFileString(overridePath, "#!/bin/sh\necho override\n"); - yield* fileSystem.chmod(overridePath, 0o755); + if (!isWindowsHost) { + yield* fileSystem.chmod(overridePath, 0o755); + } const overrideSettings = settings({ commandPath: overridePath }); const overrideBase = yield* swapResolver.inspect(overrideSettings, toolchain.environment); upstream = { @@ -1587,32 +1788,62 @@ describe("AcpRegistrySupport", () => { upstream = { ...makeAgent({ - npx: { package: "@example/other@2.0.0", args: ["--flag"], env: { MODE: "acp" } }, + npx: { package: "@example/other@2.0.0", args: ["--flag"] }, + }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideArgsOnly = yield* swapResolver.inspect( + overrideSettings, + toolchain.environment, + ); + expect( + overrideBumped.status === "ready" && + overrideArgsOnly.status === "ready" && + overrideBumped.launchIdentity !== overrideArgsOnly.launchIdentity, + ).toBe(true); + + upstream = { + ...makeAgent({ + npx: { package: "@example/other@2.0.0", env: { MODE: "acp" } }, }), version: "2.0.0", }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const overrideArgsChanged = yield* swapResolver.inspect( + const overrideEnvOnly = yield* swapResolver.inspect( overrideSettings, toolchain.environment, ); expect( overrideBumped.status === "ready" && - overrideArgsChanged.status === "ready" && - overrideBumped.launchIdentity !== overrideArgsChanged.launchIdentity, + overrideEnvOnly.status === "ready" && + overrideBumped.launchIdentity !== overrideEnvOnly.launchIdentity, ).toBe(true); // Binary launchIdentity tracks archive, sha256, cmd, args, and env while ignoring website/icon changes. - const binaryExe = `${packageSwapDir}/tools/example-agent/1.0.0/linux-x86_64/bin/agent`; + const binaryTargetKey = isWindowsHost ? "windows-x86_64" : "linux-x86_64"; + const binaryPlatform = isWindowsHost ? "win32" : "linux"; + const binarySwapResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: packageSwapDir, + toolsDir: `${packageSwapDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, binaryPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + ); + const binaryExe = `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin/agent`; yield* fileSystem.makeDirectory( - `${packageSwapDir}/tools/example-agent/1.0.0/linux-x86_64/bin`, + `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin`, { recursive: true, }, ); yield* fileSystem.writeFileString(binaryExe, "#!/bin/sh\necho bin\n"); - yield* fileSystem.chmod(binaryExe, 0o755); + if (!isWindowsHost) { + yield* fileSystem.chmod(binaryExe, 0o755); + } const inspectBinary = ( target: { readonly archive: string; @@ -1625,14 +1856,14 @@ describe("AcpRegistrySupport", () => { ) => Effect.gen(function* () { upstream = { - ...makeAgent({ binary: { "linux-x86_64": target } }), + ...makeAgent({ binary: { [binaryTargetKey]: target } }), version: "1.0.0", ...(meta?.website ? { website: meta.website } : {}), ...(meta?.icon ? { icon: meta.icon } : {}), }; - yield* swapResolver.invalidateIndex(); - yield* swapResolver.refreshIndex(refreshOptions); - const inspected = yield* swapResolver.inspect(settings(), toolchain.environment); + yield* binarySwapResolver.invalidateIndex(); + yield* binarySwapResolver.refreshIndex(refreshOptions); + const inspected = yield* binarySwapResolver.inspect(settings(), toolchain.environment); expect(inspected.status).toBe("ready"); return inspected.status === "ready" ? inspected.launchIdentity : undefined; }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 075c079edb46a..71fcd69735290 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -32,6 +32,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Result from "effect/Result"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; @@ -418,15 +419,25 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged (left, right) => right.localeCompare(left, undefined, { numeric: true }), ); for (const version of versions) { + const versionRoot = path.join(installsDirectory, agent, version); + const versionEntries = yield* listDirectories(versionRoot); for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(target)) { - const installRoot = path.join(installsDirectory, agent, version, candidateTarget); - if (yield* fileSystem.exists(installRoot).pipe(Effect.orElseSucceed(() => false))) { - const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution - .binary?.[candidateTarget]; - const commandSegments = - binaryTarget === undefined - ? undefined - : normalizeRegistryCommandPath(binaryTarget.cmd); + const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution + .binary?.[candidateTarget]; + const commandSegments = + binaryTarget === undefined ? undefined : normalizeRegistryCommandPath(binaryTarget.cmd); + const preferredArtifactDir = + binaryTarget === undefined + ? undefined + : binaryArtifactDirName(candidateTarget, binaryTarget); + const candidateEntries = [ + ...(preferredArtifactDir !== undefined && versionEntries.includes(preferredArtifactDir) + ? [preferredArtifactDir] + : []), + ...(versionEntries.includes(candidateTarget) ? [candidateTarget] : []), + ]; + for (const entry of candidateEntries) { + const installRoot = path.join(versionRoot, entry); const directory = commandSegments === undefined ? installRoot @@ -496,6 +507,7 @@ export interface ResolvedAcpRegistryAgent { readonly distribution: AcpRegistryDistributionKind | "local"; readonly launchIdentity?: string; readonly indexRevision?: number; + readonly fallback?: boolean; readonly spawn: AcpSessionRuntime.AcpSpawnInput; } @@ -604,12 +616,65 @@ const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; +const BINARY_ARTIFACT_SLOT_HASH_LENGTH = 12; + +const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ + version: Schema.optional(Schema.String), + archive: Schema.String, + cmd: Schema.String, + sha256: Schema.NullOr(Schema.String), + args: Schema.optional(Schema.Array(Schema.String)), + env: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); +type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt.Type; +const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryBinaryArtifactReceipt), +); + +function binaryArtifactIdentityKey(target: typeof AcpRegistryBinaryTarget.Type): string { + return JSON.stringify({ + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + }); +} + +function binaryArtifactDirName( + platformTarget: AcpRegistryPlatformTarget, + target: typeof AcpRegistryBinaryTarget.Type, +): string { + const digest = Hex.encode(sha256(new TextEncoder().encode(binaryArtifactIdentityKey(target)))); + return `${platformTarget}-${digest.slice(0, BINARY_ARTIFACT_SLOT_HASH_LENGTH)}`; +} + +function isBinaryPlatformEntry(entry: string, candidateTarget: AcpRegistryPlatformTarget): boolean { + if (entry === candidateTarget) return true; + if (!entry.startsWith(`${candidateTarget}-`)) return false; + return /^[0-9a-f]{12}$/u.test(entry.slice(candidateTarget.length + 1)); +} + +function binaryArtifactReceiptMatches( + receipt: AcpRegistryBinaryArtifactReceipt, + target: typeof AcpRegistryBinaryTarget.Type, +): boolean { + return ( + receipt.archive === target.archive && + receipt.cmd === target.cmd && + receipt.sha256 === (target.sha256 ?? null) + ); +} -function binaryArtifactReceipt(target: typeof AcpRegistryBinaryTarget.Type): string { +function encodeBinaryArtifactReceipt( + agent: AcpRegistryAgent, + target: typeof AcpRegistryBinaryTarget.Type, +): string { return JSON.stringify({ + version: agent.version, archive: target.archive, cmd: target.cmd, sha256: target.sha256 ?? null, + ...(target.args && target.args.length > 0 ? { args: target.args } : {}), + ...(target.env && Object.keys(target.env).length > 0 ? { env: target.env } : {}), }); } @@ -648,10 +713,6 @@ function isAlreadyExists(error: PlatformError.PlatformError): boolean { return error.reason._tag === "AlreadyExists"; } -function isNotFound(error: PlatformError.PlatformError): boolean { - return error.reason._tag === "NotFound"; -} - function normalizeRegistryCommandPath(command: string): ReadonlyArray | undefined { const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, ""); const segments = normalized.split("/").filter((segment) => segment.length > 0); @@ -1708,12 +1769,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (candidate) => agent.distribution.binary?.[candidate] === target, ) ?? platformTarget; if (matchedPlatformTarget === undefined || commandSegments === undefined) return undefined; - const installRoot = path.join(agentInstallRoot(agent), matchedPlatformTarget); + const versionRoot = agentInstallRoot(agent); + const installRoot = path.join(versionRoot, matchedPlatformTarget); + const artifactRoot = path.join( + versionRoot, + binaryArtifactDirName(matchedPlatformTarget, target), + ); return { commandSegments, installRoot, + artifactRoot, platformTarget: matchedPlatformTarget, executablePath: path.join(installRoot, ...commandSegments), + artifactExecutablePath: path.join(artifactRoot, ...commandSegments), }; }; @@ -1724,12 +1792,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .readDirectory(agentRoot) .pipe(Effect.orElseSucceed((): Array => [])); for (const version of versions) { + const entries = yield* fileSystem + .readDirectory(path.join(agentRoot, version)) + .pipe(Effect.orElseSucceed((): Array => [])); for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(platformTarget)) { - if ( - yield* fileSystem - .exists(path.join(agentRoot, version, candidateTarget)) - .pipe(Effect.orElseSucceed(() => false)) - ) { + if (entries.some((entry) => isBinaryPlatformEntry(entry, candidateTarget))) { return true; } } @@ -1738,17 +1805,37 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); - const isCachedBinaryMatching = Effect.fn("AcpRegistryCatalog.isCachedBinaryMatching")(function* ( - installRoot: string, - executablePath: string, + const isCachedBinarySlotMatching = Effect.fn("AcpRegistryCatalog.isCachedBinarySlotMatching")( + function* (root: string, executablePath: string, target: typeof AcpRegistryBinaryTarget.Type) { + if (!(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false)))) { + return false; + } + const receiptPath = path.join(root, BINARY_ARTIFACT_RECEIPT_FILENAME); + const rawReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); + const decoded = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + return Option.isSome(decoded) && binaryArtifactReceiptMatches(decoded.value, target); + }, + ); + + const findMatchingBinarySlot = Effect.fn("AcpRegistryCatalog.findMatchingBinarySlot")(function* ( + paths: NonNullable>, target: typeof AcpRegistryBinaryTarget.Type, ) { - if (!(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false)))) { - return false; + if ( + yield* isCachedBinarySlotMatching(paths.artifactRoot, paths.artifactExecutablePath, target) + ) { + return Option.some({ + root: paths.artifactRoot, + executablePath: paths.artifactExecutablePath, + }); + } + if (yield* isCachedBinarySlotMatching(paths.installRoot, paths.executablePath, target)) { + return Option.some({ + root: paths.installRoot, + executablePath: paths.executablePath, + }); } - const receiptPath = path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME); - const receipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); - return Option.isSome(receipt) && receipt.value === binaryArtifactReceipt(target); + return Option.none<{ readonly root: string; readonly executablePath: string }>(); }); const installBinary = Effect.fn("AcpRegistryCatalog.installBinary")(function* ( @@ -1768,9 +1855,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`, }); } - const { commandSegments, installRoot, executablePath } = paths; - if (yield* isCachedBinaryMatching(installRoot, executablePath, target)) { - return yield* assertExecutableInRoot(installRoot, executablePath).pipe( + const { commandSegments, installRoot, artifactRoot } = paths; + const validateSlot = (slot: { readonly root: string; readonly executablePath: string }) => + assertExecutableInRoot(slot.root, slot.executablePath).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -1781,6 +1868,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ), ); + const cachedSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(cachedSlot)) { + return yield* validateSlot(cachedSlot.value); } yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe( @@ -1807,9 +1897,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); return yield* Effect.gen(function* () { - if (yield* isCachedBinaryMatching(installRoot, executablePath, target)) { - return yield* assertExecutableInRoot(installRoot, executablePath); + const lockedSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(lockedSlot)) { + return yield* assertExecutableInRoot( + lockedSlot.value.root, + lockedSlot.value.executablePath, + ); } + const primaryExists = yield* fileSystem + .exists(installRoot) + .pipe(Effect.orElseSucceed(() => false)); + // Keep an existing primary directory intact for active sessions (and Windows file locks) + // by installing same-version replacements into an immutable artifact-scoped sibling slot. + const destinationRoot = primaryExists ? artifactRoot : installRoot; + const destinationExecutable = path.join(destinationRoot, ...commandSegments); const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ directory: path.dirname(installRoot), prefix: `.${agent.id}-install-`, @@ -1935,23 +2036,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); yield* fileSystem.writeFileString( path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), - binaryArtifactReceipt(target), - ); - const backupRoot = path.join(temporaryRoot, "previous"); - const movedPrevious = yield* fileSystem.rename(installRoot, backupRoot).pipe( - Effect.as(true), - Effect.catchIf(isNotFound, () => Effect.succeed(false)), + encodeBinaryArtifactReceipt(agent, target), ); - yield* fileSystem - .rename(extractionRoot, installRoot) - .pipe( - Effect.onError(() => - movedPrevious - ? fileSystem.rename(backupRoot, installRoot).pipe(Effect.ignore) - : Effect.void, - ), - ); - return yield* assertExecutableInRoot(installRoot, executablePath); + if (destinationRoot === artifactRoot) { + // An un-receipted leftover at this content-addressed slot cannot be a valid install. + yield* fileSystem.remove(destinationRoot, { recursive: true, force: true }); + } + yield* fileSystem.rename(extractionRoot, destinationRoot); + return yield* assertExecutableInRoot(destinationRoot, destinationExecutable); }).pipe( Effect.scoped, Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), @@ -2157,11 +2249,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } as const; } yield* consumePreparedBinaryReservation(agent.id); - const exists = yield* fileSystem - .exists(paths.executablePath) - .pipe(Effect.orElseSucceed(() => false)); + const activeSlot = yield* findMatchingBinarySlot(paths, distribution.binaryTarget!); + const primaryExists = + Option.isNone(activeSlot) && + (yield* fileSystem + .exists(paths.executablePath) + .pipe(Effect.orElseSucceed(() => false))); + const slotToValidate = Option.isSome(activeSlot) + ? activeSlot.value + : primaryExists + ? { root: paths.installRoot, executablePath: paths.executablePath } + : undefined; // Any prepared version keeps the agent ready; resolve installs the current one on demand. - if (!exists && !(yield* hasInstalledBinaryVersion(agent.id))) { + if (slotToValidate === undefined && !(yield* hasInstalledBinaryVersion(agent.id))) { return { status: "unprepared", agentId, @@ -2170,8 +2270,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct indexRevision, } as const; } - if (exists) { - yield* assertExecutableInRoot(paths.installRoot, paths.executablePath).pipe( + if (slotToValidate !== undefined) { + yield* assertExecutableInRoot( + slotToValidate.root, + slotToValidate.executablePath, + ).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -2222,6 +2325,223 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); + const buildResolvedRegistrySpawn = Effect.fn("AcpRegistryCatalog.buildResolvedRegistrySpawn")( + function* (input: { + readonly agent: AcpRegistryAgent; + readonly distribution: ResolvedAcpRegistryDistribution; + readonly command: string; + readonly commandBinDirectory?: string; + readonly commandOverride?: string; + readonly cwd: string; + readonly effectiveEnvironment: NodeJS.ProcessEnv; + readonly indexRevision?: number; + readonly fallback?: boolean; + }) { + const baseSpawnEnvironment = { + ...input.effectiveEnvironment, + ...input.distribution.env, + }; + const pathEnvironment = + input.commandBinDirectory === undefined + ? baseSpawnEnvironment + : withPreferredPath(baseSpawnEnvironment, input.commandBinDirectory, platform); + const spawnEnvironment = + runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(input.agent.id) + ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) + : pathEnvironment; + return { + agent: input.agent, + distribution: input.distribution.kind, + launchIdentity: registryLaunchIdentity({ + version: input.commandOverride ? null : input.agent.version, + distribution: input.distribution, + ...(input.commandOverride ? { commandOverride: input.commandOverride } : {}), + }), + ...(input.indexRevision === undefined ? {} : { indexRevision: input.indexRevision }), + ...(input.fallback ? { fallback: true } : {}), + spawn: { + command: input.command, + args: input.distribution.args, + cwd: input.cwd, + env: spawnEnvironment, + }, + } satisfies ResolvedAcpRegistryAgent; + }, + ); + + const safeDecodeVersionDir = (value: string): string => { + try { + return decodeURIComponent(value); + } catch { + return value; + } + }; + + const resolveFallbackInstalledBinary = Effect.fn( + "AcpRegistryCatalog.resolveFallbackInstalledBinary", + )(function* ( + settings: AcpRegistrySettings, + cwd: string, + environment: NodeJS.ProcessEnv | undefined, + registry: AcpRegistryIndex, + indexRevision: number, + options: { readonly allowLegacySameVersion: boolean }, + ) { + if (settings.commandPath.trim().length > 0 || platformTarget === undefined) { + return Option.none(); + } + const agent = registry.agents.find((candidate) => candidate.id === settings.agentId.trim()); + if (agent === undefined) return Option.none(); + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined || distribution.kind !== "binary") { + return Option.none(); + } + const effectiveEnvironment = environment ?? hostEnvironment; + return yield* withInstallPermit(agent.id)( + Effect.gen(function* () { + const target = distribution.binaryTarget!; + const paths = binaryPaths(agent, target); + // 1. Preserve a validated receipt-less legacy install at the same version without writing a receipt, + // only if no receipted slot has been installed for this version and target yet. + if (options.allowLegacySameVersion && paths !== undefined) { + const versionRoot = path.dirname(paths.installRoot); + const versionEntries = yield* fileSystem + .readDirectory(versionRoot) + .pipe(Effect.orElseSucceed((): Array => [])); + const targetSlots = versionEntries.filter((entry) => + isBinaryPlatformEntry(entry, paths.platformTarget), + ); + let hasAnyReceipt = false; + for (const slot of targetSlots) { + if ( + yield* fileSystem + .exists(path.join(versionRoot, slot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.orElseSucceed(() => false)) + ) { + hasAnyReceipt = true; + break; + } + } + const executableExists = + !hasAnyReceipt && + (yield* fileSystem + .exists(paths.executablePath) + .pipe(Effect.orElseSucceed(() => false))); + if (executableExists) { + const validated = yield* assertExecutableInRoot( + paths.installRoot, + paths.executablePath, + ).pipe(Effect.option); + if (Option.isSome(validated)) { + const resolved = yield* buildResolvedRegistrySpawn({ + agent, + distribution, + command: validated.value, + cwd, + effectiveEnvironment, + indexRevision, + }); + return Option.some(resolved); + } + } + } + // 2. Fall back to the newest receipted prior installed version so failed new-version downloads do not strand the agent. + const agentRoot = path.join(installsDirectory, agent.id); + const currentVersionDir = encodeURIComponent(agent.version); + const versions = (yield* fileSystem + .readDirectory(agentRoot) + .pipe(Effect.orElseSucceed((): Array => []))) + .filter((entry) => entry !== currentVersionDir) + .toSorted((left, right) => + safeDecodeVersionDir(right).localeCompare(safeDecodeVersionDir(left), undefined, { + numeric: true, + }), + ); + for (const versionDir of versions) { + const versionRoot = path.join(agentRoot, versionDir); + const entries = yield* fileSystem + .readDirectory(versionRoot) + .pipe(Effect.orElseSucceed((): Array => [])); + for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates( + platformTarget, + )) { + const matchedDirs = entries.filter((entry) => + isBinaryPlatformEntry(entry, candidateTarget), + ); + const candidatesWithMtime = yield* Effect.forEach(matchedDirs, (entry) => { + const dir = path.join(versionRoot, entry); + return fileSystem.stat(dir).pipe( + Effect.map((info) => ({ + dir, + entry, + mtimeMs: Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, + })), + Effect.orElseSucceed(() => ({ dir, entry, mtimeMs: 0 })), + ); + }); + candidatesWithMtime.sort((left, right) => { + // Prefer artifact-scoped slots over the older primary slot when both exist. + if (left.entry === candidateTarget && right.entry !== candidateTarget) return 1; + if (right.entry === candidateTarget && left.entry !== candidateTarget) return -1; + return right.mtimeMs - left.mtimeMs || left.entry.localeCompare(right.entry); + }); + for (const { dir } of candidatesWithMtime) { + const rawReceipt = yield* fileSystem + .readFileString(path.join(dir, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.option); + const decoded = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + if (Option.isNone(decoded)) continue; + const receipt = decoded.value; + const commandSegments = normalizeRegistryCommandPath(receipt.cmd); + if (commandSegments === undefined) continue; + const executablePath = path.join(dir, ...commandSegments); + if ( + !(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) + ) { + continue; + } + const validated = yield* assertExecutableInRoot(dir, executablePath).pipe( + Effect.option, + ); + if (Option.isNone(validated)) continue; + const fallbackVersion = receipt.version ?? safeDecodeVersionDir(versionDir); + const fallbackArgs = receipt.args ?? []; + const fallbackEnv = receipt.env ?? {}; + const fallbackTarget: typeof AcpRegistryBinaryTarget.Type = { + archive: receipt.archive, + cmd: receipt.cmd, + ...(receipt.sha256 ? { sha256: receipt.sha256 } : {}), + ...(fallbackArgs.length > 0 ? { args: fallbackArgs } : {}), + ...(Object.keys(fallbackEnv).length > 0 ? { env: fallbackEnv } : {}), + }; + const fallbackDistribution: ResolvedAcpRegistryDistribution = { + kind: "binary", + binaryTarget: fallbackTarget, + args: fallbackArgs, + env: fallbackEnv, + }; + const fallbackAgent: AcpRegistryAgent = { ...agent, version: fallbackVersion }; + const resolved = yield* buildResolvedRegistrySpawn({ + agent: fallbackAgent, + distribution: fallbackDistribution, + command: validated.value, + cwd, + effectiveEnvironment, + fallback: true, + }); + return Option.some(resolved); + } + } + } + return Option.none(); + }), + ); + }); + const resolveWithRegistry = Effect.fn("AcpRegistryCatalog.resolveWithRegistry")(function* ( settings: AcpRegistrySettings, cwd: string, @@ -2240,7 +2560,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const distribution = yield* compatibleDistribution(agent, settings.distribution); let command: string; - let args: ReadonlyArray; let commandBinDirectory: string | undefined; const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); @@ -2253,7 +2572,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } command = resolvedOverride; - args = distribution.args; } else if (distribution.kind === "npx" || distribution.kind === "uvx") { const installed = yield* withInstallPermit(agent.id)( ensureGlobalPackage( @@ -2264,7 +2582,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); command = installed.executablePath; - args = distribution.args; commandBinDirectory = installed.binDirectory; } else { const target = distribution.binaryTarget!; @@ -2273,38 +2590,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.tap(() => consumePreparedBinaryReservation(agent.id)), ), ); - args = distribution.args; } - const baseSpawnEnvironment = { - ...effectiveEnvironment, - ...distribution.env, - }; - const pathEnvironment = - commandBinDirectory === undefined - ? baseSpawnEnvironment - : withPreferredPath(baseSpawnEnvironment, commandBinDirectory, platform); - const spawnEnvironment = - runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(agent.id) - ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) - : pathEnvironment; - - return { + return yield* buildResolvedRegistrySpawn({ agent, - distribution: distribution.kind, - launchIdentity: registryLaunchIdentity({ - version: commandOverride.length > 0 ? null : agent.version, - distribution, - ...(commandOverride.length > 0 ? { commandOverride } : {}), - }), + distribution, + command, + ...(commandBinDirectory === undefined ? {} : { commandBinDirectory }), + ...(commandOverride.length > 0 ? { commandOverride } : {}), + cwd, + effectiveEnvironment, indexRevision, - spawn: { - command, - args, - cwd, - env: spawnEnvironment, - }, - } satisfies ResolvedAcpRegistryAgent; + }); }); // A cached index can pin a version whose archive was since removed upstream. @@ -2338,23 +2635,50 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (error) => error.reason === "download_failed", (error) => Effect.gen(function* () { - const { index: latest, indexRevision: latestRevision } = - yield* refreshRegistry().pipe(Effect.mapError(() => error)); - const agentId = settings.agentId.trim(); - const launchSignatureIn = (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 - ? agent.version - : registryLaunchIdentity({ version: agent.version, distribution }); - }; - if (launchSignatureIn(latest) === launchSignatureIn(registry)) return yield* error; - return yield* resolveWithRegistry(settings, cwd, environment, latest, latestRevision); + const refreshed = yield* Effect.result(refreshRegistry()); + let activeRegistry = registry; + let activeRevision = indexRevision; + let downloadError = error; + let artifactChanged = false; + if (Result.isSuccess(refreshed)) { + const { index: latest, indexRevision: latestRevision } = refreshed.success; + const agentId = settings.agentId.trim(); + const launchSignatureIn = (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 + ? agent.version + : registryLaunchIdentity({ version: agent.version, distribution }); + }; + if (launchSignatureIn(latest) !== launchSignatureIn(registry)) { + artifactChanged = true; + const retried = yield* Effect.result( + resolveWithRegistry(settings, cwd, environment, latest, latestRevision), + ); + if (Result.isSuccess(retried)) return retried.success; + if (retried.failure.reason !== "download_failed") { + return yield* retried.failure; + } + activeRegistry = latest; + activeRevision = latestRevision; + downloadError = retried.failure; + } + } + const fallback = yield* resolveFallbackInstalledBinary( + settings, + cwd, + environment, + activeRegistry, + activeRevision, + { allowLegacySameVersion: !artifactChanged }, + ); + if (Option.isSome(fallback)) return fallback.value; + return yield* downloadError; }), ), ); @@ -2415,7 +2739,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct for (const version of yield* fileSystem.readDirectory(agentRoot)) { const versionRoot = path.join(agentRoot, version); for (const entry of yield* fileSystem.readDirectory(versionRoot)) { - if (!/^(?:darwin|linux|windows)-(?:aarch64|x86_64)$/u.test(entry)) continue; + if ( + !/^(?:darwin|linux|windows)-(?:aarch64|x86_64)(?:-[0-9a-f]{12})?$/u.test(entry) + ) + continue; yield* fileSystem.remove(path.join(versionRoot, entry), { recursive: true, force: true, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 3290741f3d61c..73e11c9ff9839 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -875,6 +875,29 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.generation).toBe(5); expect(updated.entry).toBeNull(); }); + + it("ignores live updates tagged for a different runtime identity than the cached entry", () => { + const provider = providerWithModels( + [{ id: "smodel", name: "Default", description: null }], + "smodel", + ); + const cache = { + generation: 3, + entry: { provider, expiresAt: 1_000, launchIdentity: "runtime-v1" }, + }; + + const ignored = updateAcpRegistryEnrichmentCache({ + cache, + configuration: settledConfiguration, + customModels: [], + now: 5_000, + runtimeIdentity: "runtime-v2", + }); + + expect(ignored).toBe(cache); + expect(ignored.generation).toBe(3); + expect(ignored.entry?.provider.models.map((m) => m.slug)).toEqual(["smodel"]); + }); }); describe("acpRegistryAdvertisesModelCatalog", () => { @@ -1590,6 +1613,9 @@ describe("AcpRegistryDriver registry recovery", () => { const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; let remoteVersion = "2.0.0"; + let remoteWebsite: string | undefined = undefined; + let failArchiveDownload = false; + let onFallbackResolved: (() => Effect.Effect) | null = null; const initialGate = { started: yield* Deferred.make(), release: yield* Deferred.make(), @@ -1611,11 +1637,17 @@ describe("AcpRegistryDriver registry recovery", () => { const respond = Effect.sync(() => HttpClientResponse.fromWeb( request, - new Response( - request.url === registryUrl - ? makeBinaryRegistry(remoteVersion) - : `#!/bin/sh\necho ${remoteVersion}\n`, - ), + request.url === registryUrl + ? new Response( + makeBinaryRegistry( + remoteVersion, + compatibleRegistryTarget, + remoteWebsite ? { website: remoteWebsite } : undefined, + ), + ) + : failArchiveDownload + ? new Response("archive unavailable", { status: 503 }) + : new Response(`#!/bin/sh\necho ${remoteVersion}\n`), ), ); const activeGate = request.url === registryUrl ? gate : null; @@ -1632,6 +1664,11 @@ describe("AcpRegistryDriver registry recovery", () => { ...realCatalog, resolve: (settings, cwd, environment) => realCatalog.resolve(settings, cwd, environment).pipe( + Effect.tap((resolved) => + resolved.fallback && onFallbackResolved !== null + ? onFallbackResolved() + : Effect.void, + ), Effect.map((resolved) => ({ ...resolved, spawn: { command: process.execPath, args: [agentPath, modelsPath] }, @@ -1717,6 +1754,46 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Deferred.succeed(secondGate.release, undefined); expect(Option.isSome(yield* Fiber.join(upgradedToV3))).toBe(true); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); + + // If 4.0.0 fails to download, the driver falls back to the installed 3.0.0 without + // acknowledging the 4.0.0 revision, then upgrades to 4.0.0 once the archive recovers. + gate = null; + remoteVersion = "4.0.0"; + remoteWebsite = "https://example.test/v4"; + failArchiveDownload = true; + const fallbackObserved = yield* Deferred.make(); + onFallbackResolved = () => + Deferred.succeed(fallbackObserved, undefined).pipe(Effect.asVoid); + const fallbackPublished = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.status === "ready" && + snapshot.setup?.documentationUrl === "https://example.test/v4" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(fallbackObserved); + expect(Option.isSome(yield* Fiber.join(fallbackPublished))).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(false); + onFallbackResolved = null; + + // Recovering without invalidating the cached 4.0.0 index still upgrades because fallback did not acknowledge it. + failArchiveDownload = false; + const upgradedToV4 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "4.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(upgradedToV4))).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(true); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); @@ -1738,15 +1815,30 @@ describe("AcpRegistryDriver registry recovery", () => { let remoteExtraAgentVersion: string | undefined = undefined; let registryRequests = 0; let resolveAttempts = 0; + let lastResolvedCommand = ""; let backgroundProbeCalls = 0; + let onInspectStart: (() => Effect.Effect) | null = null; let onInspect: | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) | null = null; + let onGetUrlAuthAction: + | ((targetInstanceId: ProviderInstanceId) => Effect.Effect) + | null = null; let onBackgroundProbeOutcome: ((skipped: boolean) => Effect.Effect) | null = null; let onRefreshIndex: Effect.Effect = Effect.void; const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = { ...baseCoordinator, + getUrlAuthAction: (targetInstanceId) => + baseCoordinator + .getUrlAuthAction(targetInstanceId) + .pipe( + Effect.tap(() => + onGetUrlAuthAction === null + ? Effect.void + : onGetUrlAuthAction(targetInstanceId), + ), + ), runBackgroundProbe: (agentId, effect) => Effect.sync(() => { backgroundProbeCalls += 1; @@ -1798,13 +1890,12 @@ describe("AcpRegistryDriver registry recovery", () => { const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, inspect: (settings, environment) => - realCatalog - .inspect(settings, environment) - .pipe( - Effect.tap((inspection) => - onInspect === null ? Effect.void : onInspect(inspection), - ), + (onInspectStart === null ? Effect.void : onInspectStart()).pipe( + Effect.andThen(() => realCatalog.inspect(settings, environment)), + Effect.tap((inspection) => + onInspect === null ? Effect.void : onInspect(inspection), ), + ), refreshIndex: (options) => realCatalog.refreshIndex(options).pipe(Effect.tap(() => onRefreshIndex)), resolve: (settings, cwd, environment) => @@ -1812,6 +1903,11 @@ describe("AcpRegistryDriver registry recovery", () => { resolveAttempts += 1; }).pipe( Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), + Effect.tap((resolved) => + Effect.sync(() => { + lastResolvedCommand = resolved.spawn.command; + }), + ), Effect.map((resolved) => ({ ...resolved, spawn: { command: process.execPath, args: [agentPath, modelsPath] }, @@ -1911,17 +2007,24 @@ describe("AcpRegistryDriver registry recovery", () => { expect(withClearedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); expect(resolveAttempts).toBe(resolvesAfterInitialProbe); - // 2. An unrelated registry change plus a live command update does not schedule a second probe. + // 2. An unrelated registry change plus a live command update does not schedule a second probe + // and acknowledges the revision so a follow-up refresh skips rechecking. remoteExtraAgentVersion = "9.9.9"; let unrelatedRefreshed = false; - const unrelatedRechecked = yield* Deferred.make(); + const unrelatedReadinessCompleted = yield* Deferred.make(); onRefreshIndex = Effect.sync(() => { unrelatedRefreshed = true; }); - onInspect = () => - unrelatedRefreshed - ? Deferred.succeed(unrelatedRechecked, undefined).pipe(Effect.asVoid) + onGetUrlAuthAction = (targetInstanceId) => + unrelatedRefreshed && targetInstanceId === identity.instanceId + ? Deferred.succeed(unrelatedReadinessCompleted, undefined).pipe(Effect.asVoid) : Effect.void; + const probesBeforeUnrelated = backgroundProbeCalls; + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + // Wait until the post-refresh inspectReadiness finishes its last async step (getUrlAuthAction), + // then observe a live command update to guarantee the no-reprobe/acknowledge branch has settled. + yield* Deferred.await(unrelatedReadinessCompleted); const liveCommandApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.slashCommands.some((command) => command.name === "live-updated"), @@ -1929,17 +2032,13 @@ describe("AcpRegistryDriver registry recovery", () => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - const probesBeforeUnrelated = backgroundProbeCalls; yield* coordinator.publishAvailableCommands(identity.instanceId, { slashCommands: [{ name: "live-updated" }], skills: [], }); - yield* catalog.invalidateIndex(); - yield* instance.snapshot.refresh; - yield* Deferred.await(unrelatedRechecked); expect(Option.isSome(yield* Fiber.join(liveCommandApplied))).toBe(true); onRefreshIndex = Effect.void; - onInspect = null; + onGetUrlAuthAction = null; // 1 auth.refreshMethods + 1 initialProbe; 0 post-recheck probe calls. expect(backgroundProbeCalls).toBe(probesBeforeUnrelated + 2); expect(resolveAttempts).toBe(resolvesAfterInitialProbe); @@ -1958,7 +2057,7 @@ describe("AcpRegistryDriver registry recovery", () => { Effect.andThen(Deferred.succeed(secondInstanceRefreshDone, undefined)), Effect.asVoid, ); - onInspect = () => + onInspectStart = () => secondInstanceRefreshed ? Effect.sync(() => { secondInstancePostRefreshInspects += 1; @@ -1977,13 +2076,26 @@ describe("AcpRegistryDriver registry recovery", () => { coordinator, ), ); - yield* secondInstance.snapshot.refresh; + const secondSettled = yield* secondInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "second-settled"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); yield* Deferred.await(secondInstanceRefreshDone); + // Keep the inspect hook active until a live update on secondInstance settles past the skip decision. + yield* coordinator.publishAvailableCommands(secondInstanceId, { + slashCommands: [{ name: "second-settled" }], + skills: [], + }); + expect(Option.isSome(yield* Fiber.join(secondSettled))).toBe(true); onRefreshIndex = Effect.void; - onInspect = null; + onInspectStart = null; expect(secondInstancePostRefreshInspects).toBe(0); - // 3. Same-version launch distribution swap replaces the cached binary on disk, invalidates the probe cache, and re-probes. + // 3. Same-version launch distribution swap installs into an immutable artifact slot without + // mutating the existing binary, invalidates the probe cache, and re-probes. remoteArchiveSuffix = "-repackaged"; yield* fileSystem.writeFileString( modelsPath, @@ -2006,9 +2118,15 @@ describe("AcpRegistryDriver registry recovery", () => { "model-swapped-a", "model-swapped-b", ]); + expect(lastResolvedCommand).toMatch( + new RegExp(`${compatibleRegistryTarget}-[0-9a-f]{12}[\\\\/]bin[\\\\/]test-agent$`), + ); + expect(yield* fileSystem.readFileString(lastResolvedCommand)).toBe( + "#!/bin/sh\necho 1.0.0-repackaged\n", + ); expect( yield* fileSystem.readFileString(installedBinaryPath(path, directory, "1.0.0")), - ).toBe("#!/bin/sh\necho 1.0.0-repackaged\n"); + ).toBe("#!/bin/sh\necho 1.0.0\n"); const resolvesAfterSwap = resolveAttempts; expect(resolvesAfterSwap).toBeGreaterThan(resolvesBeforeSwap); @@ -2517,7 +2635,48 @@ describe("AcpRegistryDriver registry recovery", () => { const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; expect(v2Identity).not.toBe(v1Identity); - // Queue a v1 watcher update on this active enrichment fiber, then publish v2 live state before the v2 probe lands. + // 1. A live config update from displayed runtime v1 (which also learns an effort option on shared-model) + // updates v1's displayed snapshot without discarding the in-flight v2 upgrade probe. + const v1LiveUpdated = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "v1-during-probe-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + undefined, + { + currentModelId: "shared-model", + availableModels: [ + { modelId: "v1-during-probe-a", name: "v1-during-probe-a" }, + { modelId: "shared-model", name: "shared-model" }, + ], + }, + ), + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(v1LiveUpdated))).toBe(true); + + // 2. Queue an UNTAGGED stale update on this active enrichment fiber before v2 commits + // so rejecting it later proves the clear watermark (!isCurrent) independently of runtimeIdentity. const staleGate = { entered: yield* Deferred.make(), release: yield* Deferred.make(), @@ -2533,10 +2692,10 @@ describe("AcpRegistryDriver registry recovery", () => { { modelId: "v1-queued-b", name: "v1-queued-b" }, ], }), - v1Identity, ); yield* Deferred.await(staleGate.entered); + // 3. Publish v2 live state before the v2 probe lands; v2 must preserve it without inheriting v1 learnedModels. yield* coordinator.publishAvailableCommands( identity.instanceId, { slashCommands: [{ name: "v2-live-cmd" }], skills: [] }, @@ -2548,7 +2707,7 @@ describe("AcpRegistryDriver registry recovery", () => { currentModelId: "v2-live-a", availableModels: [ { modelId: "v2-live-a", name: "v2-live-a" }, - { modelId: "v2-live-b", name: "v2-live-b" }, + { modelId: "shared-model", name: "shared-model" }, ], }), v2Identity, @@ -2556,10 +2715,33 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Deferred.succeed(resolveGate.release, undefined); const publishedV2 = Option.getOrThrow(yield* Fiber.join(v2ProbedReady)); - expect(publishedV2.models.map((model) => model.slug)).toEqual(["v2-live-a", "v2-live-b"]); + expect(publishedV2.models.map((model) => model.slug)).toEqual([ + "v2-live-a", + "shared-model", + ]); + expect( + publishedV2.models.find((model) => model.slug === "shared-model")?.capabilities + ?.optionDescriptors ?? [], + ).toEqual([]); expect(publishedV2.slashCommands).toEqual([{ name: "v2-live-cmd" }]); - // Releasing the queued v1 watcher callback and publishing late v1 updates must not overwrite v2. + // Synchronize past runProbeAndPublish releasing liveSnapshotSemaphore (so clearLiveState has completed). + const v2PostClear = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v2-post-clear"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-post-clear" }], skills: [] }, + v2Identity, + ); + expect(Option.isSome(yield* Fiber.join(v2PostClear))).toBe(true); + + // 4. Release the queued untagged update (rejected solely by !isCurrent), then publish post-clear v1-tagged + // updates (whose revision is AFTER clear, so rejected solely by runtimeIdentity) without evicting v2 state. const liveRaceSnapshots = yield* instance.snapshot.streamChanges.pipe( Stream.takeUntil( (snapshot) => @@ -2586,6 +2768,14 @@ describe("AcpRegistryDriver registry recovery", () => { { slashCommands: [{ name: "v1-late-cmd" }], skills: [] }, v1Identity, ); + // Late v1 publications must not evict v2's stored coordinator entry. + expect( + yield* coordinator.getAvailableCommands(identity.instanceId, { + runtimeIdentity: v2Identity, + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "v2-post-clear" }], skills: [] })); + yield* coordinator.publishLiveConfiguration( identity.instanceId, normalizeAcpRegistryLiveConfiguration([], undefined, { @@ -2614,6 +2804,33 @@ describe("AcpRegistryDriver registry recovery", () => { const afterRace = observedAfterRace[observedAfterRace.length - 1]!; expect(afterRace.models.map((model) => model.slug)).toEqual(["v2-final-a", "v2-final-b"]); expect(afterRace.slashCommands).toEqual([{ name: "v2-after-race" }]); + + // 5. When the shared catalog advances to 3.0.0 and a 3.0.0 session publishes live commands before this + // instance refreshes, the driver automatically reconciles to 3.0.0 instead of dropping the update. + remoteVersion = "3.0.0"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v3-model-a", "v3-model-b"])); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v3Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v3Inspection.status).toBe("ready"); + const v3Identity = v3Inspection.status === "ready" ? v3Inspection.launchIdentity! : ""; + const reconciledV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.slashCommands.some((command) => command.name === "v3-session-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-session-cmd" }], skills: [] }, + v3Identity, + ); + const v3Snapshot = Option.getOrThrow(yield* Fiber.join(reconciledV3)); + expect(v3Snapshot.version).toBe("3.0.0"); + expect(v3Snapshot.slashCommands).toEqual([{ name: "v3-session-cmd" }]); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 78b307c332776..4e5b1fdab9e2d 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -81,6 +81,8 @@ function acpRegistryProbeTtlMs(provider: ServerProvider): number { interface AcpRegistryEnrichmentCache { readonly generation: number; + readonly invalidationGeneration?: number; + readonly liveGenerationByRuntime?: ReadonlyMap; readonly entry: { readonly provider: ServerProvider; readonly expiresAt: number; @@ -88,6 +90,15 @@ interface AcpRegistryEnrichmentCache { } | null; } +function nextLiveGenerationByRuntime( + current: ReadonlyMap | undefined, + runtimeIdentity: string | null, +): ReadonlyMap { + const next = new Map(current); + next.set(runtimeIdentity, (next.get(runtimeIdentity) ?? 0) + 1); + return next; +} + export function isAcpRegistryCacheValid( entry: NonNullable, inspectedVersion: string | null, @@ -115,11 +126,20 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly runtimeIdentity?: string | null; }): AcpRegistryEnrichmentCache { const { cache, configuration, customModels, now, runtimeIdentity } = input; + const runtimeKey = runtimeIdentity ?? null; 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 }; + // configuration to the snapshot. Advance the epoch for this runtime so an + // in-flight probe for the same runtime cannot overwrite newer live state, + // without discarding an upgrade probe targeting a different runtime. + return { + ...cache, + generation: cache.generation + 1, + liveGenerationByRuntime: nextLiveGenerationByRuntime( + cache.liveGenerationByRuntime, + runtimeKey, + ), + }; } const entryRuntimeIdentity = runtimeIdentityFor( cache.entry.provider, @@ -143,10 +163,11 @@ export function updateAcpRegistryEnrichmentCache(input: { if (Equal.equals(provider, cache.entry.provider)) return cache; 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. + // Advance only this runtime's live epoch so an in-flight probe for the same + // runtime discards stale results without invalidating an upgrade probe for + // a newer runtime. generation: cache.generation + 1, + liveGenerationByRuntime: nextLiveGenerationByRuntime(cache.liveGenerationByRuntime, runtimeKey), entry: { ...cache.entry, provider, @@ -565,6 +586,7 @@ interface CheckedAcpRegistryReadiness { readonly snapshot: ServerProvider; readonly launchIdentity: string | null; readonly indexRevision: number | null; + readonly fallback?: boolean; } function runtimeIdentityFor( @@ -611,6 +633,7 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( readonly launchIdentity: string | null; readonly indexRevision: number | null; readonly cacheable: boolean; + readonly fallback?: boolean; }, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements @@ -733,6 +756,7 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( indexRevision: resolved.indexRevision ?? null, cacheable: resolved.launchIdentity !== undefined || inspected.success.launchIdentity === undefined, + ...(resolved.fallback ? { fallback: true } : {}), }; }); @@ -822,6 +846,7 @@ export const AcpRegistryDriver: ProviderDriver runtimeCoordinator.value - .clearAvailableCommands(instanceId) - .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))), + .clearAvailableCommands(instanceId, { dispose: true }) + .pipe( + Effect.andThen( + runtimeCoordinator.value.clearLiveConfiguration(instanceId, { dispose: true }), + ), + ), ); } const random = yield* SecureRandom.SecureRandom; @@ -950,9 +979,7 @@ export const AcpRegistryDriver: ProviderDriver - Ref.modify(activeRuntimeIdentity, (previousIdentity) => { - const nextIdentity = snapshot.installed - ? runtimeIdentityFor(snapshot, launchIdentity) - : null; + Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => { + const nextIdentity = snapshot.installed + ? runtimeIdentityFor(snapshot, launchIdentity) + : null; + return Ref.modify(activeRuntimeIdentity, (previousIdentity) => { if ( options?.seedActiveRuntimeIdentity === true && snapshot.installed && @@ -1036,9 +1063,6 @@ export const AcpRegistryDriver: ProviderDriver { - const nextIdentity = snapshot.installed - ? runtimeIdentityFor(snapshot, launchIdentity) - : null; const runtimeChanged = previousIdentity !== null && nextIdentity !== null && @@ -1057,8 +1081,8 @@ export const AcpRegistryDriver: ProviderDriver Ref.set(latestCheckedReadiness, readiness)), @@ -1094,18 +1118,38 @@ export const AcpRegistryDriver: ProviderDriver({ generation: 0, + invalidationGeneration: 0, + liveGenerationByRuntime: new Map(), entry: null, }); const liveSnapshotSemaphore = yield* Semaphore.make(1); const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({ generation: current.generation + 1, + invalidationGeneration: (current.invalidationGeneration ?? 0) + 1, + liveGenerationByRuntime: new Map(), entry: null, })); + const isProbeStillCurrent = ( + current: AcpRegistryEnrichmentCache, + captured: { + readonly invalidationGeneration: number; + readonly liveGenerationByRuntime: ReadonlyMap; + }, + probeIdentity: string | null, + ) => + (current.invalidationGeneration ?? 0) === captured.invalidationGeneration && + (current.liveGenerationByRuntime?.get(probeIdentity) ?? 0) === + (captured.liveGenerationByRuntime.get(probeIdentity) ?? 0); const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* ( target: CheckedAcpRegistryReadiness, ) { const now = yield* Clock.currentTimeMillis; const cacheState = yield* Ref.get(enrichmentCache); + const captured = { + invalidationGeneration: cacheState.invalidationGeneration ?? 0, + liveGenerationByRuntime: + cacheState.liveGenerationByRuntime ?? new Map(), + }; const cached = cacheState.entry; if ( cached !== null && @@ -1124,7 +1168,8 @@ export const AcpRegistryDriver: ProviderDriver - current.generation === cacheState.generation + isProbeStillCurrent(current, captured, probeIdentity) ? { ...current, entry: { @@ -1155,9 +1204,12 @@ export const AcpRegistryDriver: ProviderDriver(null); + let triggerSnapshotRefresh: Effect.Effect = Effect.void; const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< ProviderSnapshotSettings @@ -1174,7 +1226,9 @@ export const AcpRegistryDriver: ProviderDriver latest !== null && latest.snapshot.checkedAt === snapshot.checkedAt && @@ -1193,6 +1247,38 @@ export const AcpRegistryDriver: ProviderDriver(null); + const maybeReconcileUnmatchedRuntime = (incomingIdentity: string | undefined) => { + if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; + return Effect.gen(function* () { + if ((yield* Ref.get(inFlightProbeIdentity)) === incomingIdentity) return; + const claimed = yield* Ref.modify(reconcilingRuntimeIdentity, (current) => + current === incomingIdentity + ? ([false, current] as const) + : ([true, incomingIdentity] as const), + ); + if (!claimed) return; + yield* Effect.gen(function* () { + const inspected = yield* Effect.result( + catalog.inspect(readinessInput.settings, readinessInput.environment), + ); + if ( + Result.isSuccess(inspected) && + inspected.success.status === "ready" && + inspected.success.launchIdentity === incomingIdentity + ) { + yield* triggerSnapshotRefresh; + } + }).pipe( + Effect.ensuring( + Ref.update(reconcilingRuntimeIdentity, (current) => + current === incomingIdentity ? null : current, + ), + ), + Effect.forkIn(driverScope), + ); + }); + }; const checkLiveUpdate = (meta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta) => Effect.all({ isCurrent: meta.isCurrent, @@ -1203,32 +1289,44 @@ export const AcpRegistryDriver: ProviderDriver - (Option.isSome(runtimeCoordinator) + const runProbeAndPublish = (target: CheckedAcpRegistryReadiness) => { + const targetIdentity = target.snapshot.installed + ? runtimeIdentityFor(target.snapshot, target.launchIdentity) + : null; + const probeEffect = Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( effectiveConfig.source === "local" ? `local:${instanceId}` : effectiveConfig.agentId, enrichProviderCached(target), ) - : enrichProviderCached(target).pipe(Effect.asSome) - ).pipe( + : enrichProviderCached(target).pipe(Effect.asSome); + return Ref.set(inFlightProbeIdentity, targetIdentity).pipe( + Effect.andThen(probeEffect), Effect.flatMap( Option.match({ onNone: () => @@ -1236,16 +1334,16 @@ export const AcpRegistryDriver: ProviderDriver({ published: false, readiness: null }), - onSome: ({ provider, launchIdentity, indexRevision, generation }) => + onSome: ({ provider, launchIdentity, indexRevision, fallback, captured }) => liveSnapshotSemaphore.withPermit( Effect.gen(function* () { - const current = yield* Ref.get(enrichmentCache); - if (current.generation !== generation) { - return { published: false, readiness: null }; - } const nextIdentity = provider.installed ? runtimeIdentityFor(provider, launchIdentity) : null; + const current = yield* Ref.get(enrichmentCache); + if (!isProbeStillCurrent(current, captured, nextIdentity)) { + return { published: false, readiness: null }; + } const previousIdentity = yield* Ref.get(activeRuntimeIdentity); const runtimeChanged = previousIdentity !== null && @@ -1285,67 +1383,84 @@ export const AcpRegistryDriver: ProviderDriver + current === targetIdentity ? null : current, + ), + ), ); + }; const runWithLiveWatchers = (enrichment: Effect.Effect) => { if (Option.isNone(runtimeCoordinator)) return enrichment; const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( instanceId, ({ slashCommands, skills }, meta) => - liveSnapshotSemaphore.withPermit( - Effect.gen(function* () { - const gate = yield* checkLiveUpdate(meta); - if (!gate.accepted) return; - const current = yield* getSnapshot; - if (!current.installed) return; - yield* tryPublishSnapshot({ - ...current, - slashCommands, - skills, - }); - }), - ), + liveSnapshotSemaphore + .withPermit( + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return gate.reconcileIdentity; + const current = yield* getSnapshot; + if (!current.installed) return undefined; + yield* tryPublishSnapshot({ + ...current, + slashCommands, + skills, + }); + return undefined; + }), + ) + .pipe(Effect.flatMap(maybeReconcileUnmatchedRuntime)), ); const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( instanceId, (configuration, meta) => - liveSnapshotSemaphore.withPermit( - Effect.gen(function* () { - const gate = yield* checkLiveUpdate(meta); - if (!gate.accepted) return; - const current = yield* getSnapshot; - if (!current.installed) return; - const learned = gate.runtimeTransitioning ? [] : yield* Ref.get(learnedModels); - const next = applyAcpRegistryLiveConfiguration( - current, - configuration, - effectiveConfig.customModels, - learned.length > 0 ? learned : current.models, - ); - const published = yield* tryPublishSnapshot(next); - if (!published) return; - if (!gate.runtimeTransitioning && next.models !== current.models) { - yield* Ref.set(learnedModels, next.models); - } - const now = yield* Clock.currentTimeMillis; - yield* Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, + liveSnapshotSemaphore + .withPermit( + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return gate.reconcileIdentity; + const current = yield* getSnapshot; + if (!current.installed) return undefined; + const learned = gate.runtimeTransitioning ? [] : yield* Ref.get(learnedModels); + const next = applyAcpRegistryLiveConfiguration( + current, configuration, - customModels: effectiveConfig.customModels, - now, - runtimeIdentity: meta.runtimeIdentity ?? gate.expected, - }), - ); - }), - ), + effectiveConfig.customModels, + learned.length > 0 ? learned : current.models, + ); + const published = yield* tryPublishSnapshot(next); + if (!published) return undefined; + if (!gate.runtimeTransitioning && next.models !== current.models) { + yield* Ref.set(learnedModels, next.models); + } + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + runtimeIdentity: meta.runtimeIdentity ?? gate.expected, + }), + ); + return undefined; + }), + ) + .pipe(Effect.flatMap(maybeReconcileUnmatchedRuntime)), ); const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( instanceId, @@ -1454,6 +1569,7 @@ export const AcpRegistryDriver: ProviderDriver published && readiness !== null && + !readiness.fallback && (readiness.indexRevision === null || readiness.indexRevision >= revision) ? acknowledgeRevision(readiness.indexRevision ?? revision) : Effect.void, @@ -1475,6 +1591,15 @@ export const AcpRegistryDriver: ProviderDriver= revision + ) { + return; + } + if ( + initialProbe.published && + !publishedReadiness.fallback && publishedReadiness.indexRevision !== null && publishedReadiness.indexRevision >= revision ) { @@ -1502,6 +1627,7 @@ export const AcpRegistryDriver: ProviderDriver= revision) ) { @@ -1511,6 +1637,7 @@ export const AcpRegistryDriver: ProviderDriver= revision) ) { yield* acknowledgeRevision(rechecked.indexRevision ?? revision); @@ -1529,6 +1656,7 @@ export const AcpRegistryDriver: ProviderDriver( effect: Effect.Effect< diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index f40f9c77efcf9..daf7e3c5038c3 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -387,6 +387,7 @@ export interface AcpRegistryConfigurationProbeResolved { readonly distribution: AcpRegistrySupport.ResolvedAcpRegistryAgent["distribution"]; readonly launchIdentity?: string; readonly indexRevision?: number; + readonly fallback?: boolean; } export interface AcpRegistryConfigurationProbeResult { @@ -652,6 +653,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ...(result.resolved.indexRevision === undefined ? {} : { indexRevision: result.resolved.indexRevision }), + ...(result.resolved.fallback ? { fallback: true } : {}), }, }; }, From 839ef7bcf41562d78b5622900a7cfce649d578fb Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 13:02:00 +0000 Subject: [PATCH 12/28] fix(acp-registry): harden fallback recovery, legacy baselines, and coordinator lifetime tracking --- docs/user/providers-acp.md | 14 +- .../AcpRegistryRuntimeCoordinator.test.ts | 69 ++- .../server/AcpRegistryRuntimeCoordinator.ts | 99 ++-- .../src/server/AcpRegistrySupport.test.ts | 332 +++++++++--- .../src/server/AcpRegistrySupport.ts | 424 ++++++++++----- .../src/server/driver.test.ts | 484 +++++++++++++++--- .../src/server/driver.ts | 375 ++++++++++---- .../provider-acp-registry/src/server/probe.ts | 315 ++++++------ 8 files changed, 1573 insertions(+), 539 deletions(-) diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index c3b2765cecac1..5bbcc8f11e464 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -53,12 +53,14 @@ but keeps package installs. To use an existing local binary, set **Executable ov T3 Code refreshes the Registry index in the background and automatically installs new versions of prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while -that agent is starting a session. Agents using **Executable override** keep running the configured -executable—update those overrides directly on the server—while Registry refreshes can still pick up -updated Registry metadata, arguments, and environment variables. Refreshing providers (in -**Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on -mobile) requests a fresh Registry check right away for unprepared or unavailable agents, and after -the agent's status check finishes for installed agents. +that agent is starting a session. If a newly published version cannot be downloaded, T3 Code keeps +running the newest previously installed version until the update succeeds. Agents using +**Executable override** keep running the configured executable—update those overrides directly on +the server—while Registry refreshes can still pick up updated Registry metadata, arguments, and +environment variables. Refreshing providers (in **Settings → Providers** on web and desktop, or +**Refresh providers** in environment settings on mobile) requests a fresh Registry check right away +for unprepared or unavailable agents, and after the agent's status check finishes for installed +agents. ## Signing in diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 5efe9b82e0315..0ccac34e1c19f 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -4,6 +4,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; import type { AcpRegistryAvailableCommands } from "./probe.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -173,6 +174,30 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(yield* Fiber.join(request)).toBe(true); expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + + // Consent must be rejected at the exact expiry boundary as well as after it. + const expiringSeen = yield* Deferred.make(); + const expiringWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-expiring" + ? Deferred.succeed(expiringSeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const expiringRequest = yield* coordinator + .requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-expiring", + }) + .pipe(Effect.forkChild); + yield* Deferred.await(expiringSeen); + yield* TestClock.adjust("10 minutes"); + expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + expect( + yield* coordinator.acceptUrlAuthentication({ instanceId, elicitationId: "login-expiring" }), + ).toBe(false); + expect(yield* Fiber.join(expiringRequest)).toBe(false); + yield* Fiber.interrupt(expiringWatcher); yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); @@ -327,7 +352,11 @@ describe("AcpRegistryRuntimeCoordinator", () => { Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] }), ); + // Even after another runtime publishes later, untagged get prefers preservedRuntimeIdentity. const metaC = yield* publishAndWait("cmd-c", "runtime-c"); + expect(yield* coordinator.getAvailableCommands(instanceId)).toEqual( + Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] }), + ); yield* coordinator.clearAvailableCommands(instanceId, { preserveRuntimeIdentity: "runtime-c", }); @@ -351,10 +380,48 @@ describe("AcpRegistryRuntimeCoordinator", () => { const metaAfterFullClear = yield* publishAndWait("cmd-fresh", "runtime-b"); expect(yield* metaAfterFullClear.isCurrent).toBe(true); - // 4. Disposing an instance drops its state and marks earlier updates stale. + // 4. Disposing an instance drops its state and keeps pre-disposal updates permanently stale + // even after the same instance ID is reused for new publications. yield* coordinator.clearAvailableCommands(instanceId, { dispose: true }); expect(yield* metaAfterFullClear.isCurrent).toBe(false); expect(Option.isNone(yield* coordinator.getAvailableCommands(instanceId))).toBe(true); + + const metaAfterReuse = yield* publishAndWait("cmd-reused", "runtime-b"); + expect(yield* metaAfterReuse.isCurrent).toBe(true); + expect(yield* metaAfterFullClear.isCurrent).toBe(false); + + // 5. A newly subscribed watcher replays retained per-runtime entries in ascending revision + // order and delivers subsequent live publications without replaying older revisions. + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: "cmd-reused-c" }], skills: [] }, + "runtime-c", + ); + const replayedNames: Array = []; + const initialReplayDone = yield* Deferred.make(); + const replayDone = yield* Deferred.make(); + const secondWatcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands) => + Effect.gen(function* () { + replayedNames.push(commands.slashCommands[0]?.name ?? "empty"); + if (replayedNames.length === 2) { + yield* Deferred.succeed(initialReplayDone, undefined); + } + if (replayedNames.length >= 3) { + yield* Deferred.succeed(replayDone, undefined); + } + }), + ) + .pipe(Effect.forkChild); + yield* Deferred.await(initialReplayDone); + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: "cmd-after-watch" }], skills: [] }, + "runtime-b", + ); + yield* Deferred.await(replayDone); + expect(replayedNames).toEqual(["cmd-reused", "cmd-reused-c", "cmd-after-watch"]); + yield* Fiber.interrupt(secondWatcher); yield* Fiber.interrupt(watcher); }).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 8335257cf50b3..f662fb1707feb 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -168,9 +168,11 @@ interface ChannelEntry { readonly value: T; readonly runtimeIdentity: string | undefined; readonly revision: number; + readonly lifetime: number; } interface InstanceChannelState { + readonly lifetime: number; readonly entries: ReadonlyMap>; readonly latestKey: string | undefined; readonly hasLatest: boolean; @@ -187,18 +189,29 @@ interface ChannelUpdate { readonly value: T; readonly runtimeIdentity: string | undefined; readonly revision: number; + readonly lifetime: number; +} + +interface LiveStateChannelNames { + readonly clear: string; + readonly publish: string; + readonly get: string; + readonly watch: string; } const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveStateChannel")( - function* (name: string) { + function* (names: LiveStateChannelNames) { const updates = yield* PubSub.unbounded>(); const stateRef = yield* Ref.make>({ revision: 0, instances: new Map(), }); - const clear = (instanceId: ProviderInstanceId, options?: AcpRegistryClearLiveStateOptions) => - Ref.update(stateRef, (state) => { + const clear = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.clear}`)(function* ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, + ) { + yield* Ref.update(stateRef, (state) => { const revision = state.revision + 1; const nextInstances = new Map(state.instances); if (options?.dispose === true) { @@ -206,6 +219,7 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt return { revision, instances: nextInstances }; } const existing = state.instances.get(instanceId); + const lifetime = existing?.lifetime ?? revision; const nextClear = recordLiveStateClear(existing?.clear, revision, options); const nextEntries = new Map>(); if (existing !== undefined) { @@ -226,6 +240,7 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt undefined, ); nextInstances.set(instanceId, { + lifetime, entries: nextEntries, latestKey: fallbackLatest?.runtimeIdentity, hasLatest: fallbackLatest !== undefined, @@ -233,28 +248,34 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt }); return { revision, instances: nextInstances }; }); + }); - const publish = (instanceId: ProviderInstanceId, value: T, runtimeIdentity?: string) => - Ref.modify(stateRef, (state) => { + const publish = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.publish}`)(function* ( + instanceId: ProviderInstanceId, + value: T, + runtimeIdentity?: string, + ) { + const event = yield* Ref.modify(stateRef, (state) => { const revision = state.revision + 1; const existing = state.instances.get(instanceId); + const lifetime = existing?.lifetime ?? revision; const nextEntries = new Map(existing?.entries); - nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision }); + nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision, lifetime }); const nextInstances = new Map(state.instances); nextInstances.set(instanceId, { + lifetime, entries: nextEntries, latestKey: runtimeIdentity, hasLatest: true, clear: existing?.clear, }); - const event: ChannelUpdate = { instanceId, value, runtimeIdentity, revision }; - return [event, { revision, instances: nextInstances }] as const; - }).pipe( - Effect.flatMap((event) => PubSub.publish(updates, event)), - Effect.asVoid, - ); + const update: ChannelUpdate = { instanceId, value, runtimeIdentity, revision, lifetime }; + return [update, { revision, instances: nextInstances }] as const; + }); + yield* PubSub.publish(updates, event); + }); - const get = Effect.fn(`AcpRegistryRuntimeCoordinator.${name}`)(function* ( + const get = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.get}`)(function* ( instanceId: ProviderInstanceId, options?: AcpRegistryReadLiveStateOptions, ) { @@ -278,18 +299,21 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt return inst.hasLatest ? validEntry(inst.entries.get(inst.latestKey)) : Option.none(); }); - const watch = ( + const watch = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.watch}`)(function* ( instanceId: ProviderInstanceId, onUpdate: (value: T, meta: AcpRegistryLiveUpdateMeta) => Effect.Effect, - ) => - Effect.scoped( + ) { + yield* Effect.scoped( Effect.gen(function* () { // Subscribe before reading to avoid missing publications. const subscription = yield* PubSub.subscribe(updates); - const inst = (yield* Ref.get(stateRef)).instances.get(instanceId); + const snapshot = yield* Ref.get(stateRef); + const snapshotRevision = snapshot.revision; + const inst = snapshot.instances.get(instanceId); const metaFor = ( runtimeIdentity: string | undefined, revision: number, + lifetime: number, ): AcpRegistryLiveUpdateMeta => ({ runtimeIdentity, isCurrent: Ref.get(stateRef).pipe( @@ -297,6 +321,7 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt const current = state.instances.get(instanceId); return ( current !== undefined && + current.lifetime === lifetime && isLiveUpdateCurrent(current.clear, revision, runtimeIdentity) ); }), @@ -310,22 +335,26 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt isLiveUpdateCurrent(inst.clear, entry.revision, entry.runtimeIdentity), ) .toSorted((left, right) => left.revision - right.revision); - const replayedRevisions = new Set(replayed.map((entry) => entry.revision)); for (const entry of replayed) { - yield* onUpdate(entry.value, metaFor(entry.runtimeIdentity, entry.revision)); + yield* onUpdate( + entry.value, + metaFor(entry.runtimeIdentity, entry.revision, entry.lifetime), + ); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => { - if (update.instanceId !== instanceId) return false; - if (replayedRevisions.delete(update.revision)) return false; - return true; - }), + Stream.filter( + (update) => update.instanceId === instanceId && update.revision > snapshotRevision, + ), Stream.runForEach((update) => - onUpdate(update.value, metaFor(update.runtimeIdentity, update.revision)), + onUpdate( + update.value, + metaFor(update.runtimeIdentity, update.revision, update.lifetime), + ), ), ); }), ); + }); return { clear, publish, get, watch } as const; }, @@ -334,10 +363,18 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt const make = Effect.gen(function* () { const foregroundStarts = yield* PubSub.unbounded(); const activeForegroundCounts = yield* Ref.make(new Map()); - const availableCommandsChannel = - yield* makeLiveStateChannel("getAvailableCommands"); - const liveConfigurationChannel = - yield* makeLiveStateChannel("getLiveConfiguration"); + const availableCommandsChannel = yield* makeLiveStateChannel({ + clear: "clearAvailableCommands", + publish: "publishAvailableCommands", + get: "getAvailableCommands", + watch: "watchAvailableCommands", + }); + const liveConfigurationChannel = yield* makeLiveStateChannel({ + clear: "clearLiveConfiguration", + publish: "publishLiveConfiguration", + get: "getLiveConfiguration", + watch: "watchLiveConfiguration", + }); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -460,7 +497,7 @@ const make = Effect.gen(function* () { }); if (pending === undefined) return false; yield* publishUrlAuthAction(input.instanceId, null); - if (DateTime.toEpochMillis(now) > DateTime.toEpochMillis(pending.expiresAt)) { + if (DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pending.expiresAt)) { yield* Deferred.succeed(pending.consent, false); return false; } @@ -474,7 +511,7 @@ const make = Effect.gen(function* () { const pending = (yield* Ref.get(pendingUrlAuthActions)).get(instanceId); if ( pending === undefined || - DateTime.toEpochMillis(now) > DateTime.toEpochMillis(pending.expiresAt) + DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pending.expiresAt) ) { return Option.none(); } diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index daf26413f6b2a..460915ee56749 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -763,8 +763,11 @@ describe("AcpRegistrySupport", () => { () => { const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); const replacementBytes = new TextEncoder().encode("#!/bin/sh\necho example-repackaged\n"); + const rehashedBytes = new TextEncoder().encode("#!/bin/sh\necho example-rehashed\n"); const replacementArchiveUrl = "https://registry.test/example-agent-repackaged.bin"; const replacementSha256 = Hex.encode(sha256(replacementBytes)); + const rehashedSha256 = Hex.encode(sha256(rehashedBytes)); + let serveRehashedAtReplacement = false; let currentAgent = makeAgent({ binary: { "linux-x86_64": { @@ -840,6 +843,29 @@ describe("AcpRegistrySupport", () => { path.dirname(first.spawn.command), ]); + // Changing only sha256 at the same archive URL & cmd must install into a new artifact slot. + serveRehashedAtReplacement = true; + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: rehashedSha256, + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rehashed = yield* resolver.resolve(settings(), "/workspace"); + expect(rehashed.spawn.command).not.toBe(third.spawn.command); + expect(yield* fileSystem.readFileString(rehashed.spawn.command)).toBe( + "#!/bin/sh\necho example-rehashed\n", + ); + expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( + "#!/bin/sh\necho example-repackaged\n", + ); + // A failed replacement (checksum mismatch) leaves existing installed binaries intact. currentAgent = makeAgent({ binary: { @@ -855,11 +881,11 @@ describe("AcpRegistrySupport", () => { yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const checksumError = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); expect(checksumError.reason).toBe("checksum_mismatch"); - expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( - "#!/bin/sh\necho example-repackaged\n", + expect(yield* fileSystem.readFileString(rehashed.spawn.command)).toBe( + "#!/bin/sh\necho example-rehashed\n", ); - // Uninstalling removes both the primary slot and the artifact-scoped sibling slot. + // Uninstalling removes the primary slot and all artifact-scoped sibling slots. expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ agentId: "example-agent", removed: true, @@ -870,7 +896,12 @@ describe("AcpRegistrySupport", () => { Effect.provide( layerResolver((request) => { requests.push(request.url); - const payload = request.url === replacementArchiveUrl ? replacementBytes : binaryBytes; + const payload = + request.url === replacementArchiveUrl + ? serveRehashedAtReplacement + ? rehashedBytes + : replacementBytes + : binaryBytes; const response = request.url === registryUrl ? new Response(makeRegistry(currentAgent)) @@ -896,10 +927,13 @@ describe("AcpRegistrySupport", () => { const legacyArchiveUrl = "https://example.test/example-agent-1.0.0.bin"; const swappedArchiveUrl = "https://example.test/example-agent-1.0.0-fixed.bin"; const v2ArchiveUrl = "https://example.test/example-agent-2.0.0.bin"; + const v1PrimaryBytes = new TextEncoder().encode("#!/bin/sh\necho v1-primary\n"); const v1Bytes = new TextEncoder().encode("#!/bin/sh\necho v1-fixed\n"); + const v2Bytes = new TextEncoder().encode("#!/bin/sh\necho v2\n"); let offline = true; let failSwappedDownload = false; let failV2Download = true; + let requests: Array = []; let currentAgent = { ...makeAgent({ binary: { @@ -938,16 +972,38 @@ describe("AcpRegistrySupport", () => { registryUrl, }); - // 1. Pre-existing receipt-less binary works offline without fabricating a receipt. + // 1. Pre-existing receipt-less binary works offline without downloading or fabricating a receipt. const offlineLegacy = yield* resolver.resolve(settings(), "/workspace"); expect(offlineLegacy.agent?.version).toBe("1.0.0"); expect(offlineLegacy.spawn.command).toBe(legacyBinary); expect(offlineLegacy.fallback).toBeUndefined(); + expect(requests).toEqual([]); expect(yield* fileSystem.exists(legacyReceipt)).toBe(false); - // 2. If the registry updates the same-version archive URL and the new download fails, - // the receipt-less legacy install is NOT treated as matching the changed artifact. + // Changing only args/env while keeping archive/cmd/sha256 unchanged still reuses the legacy binary. offline = false; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-updated-args"], + env: { AGENT_CHANNEL: "v1-updated" }, + }, + }, + }), + version: "1.0.0", + }; + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const legacyWithUpdatedArgs = yield* resolver.resolve(settings(), "/workspace"); + expect(legacyWithUpdatedArgs.spawn.command).toBe(legacyBinary); + expect(legacyWithUpdatedArgs.spawn.args).toEqual(["--v1-updated-args"]); + expect(yield* fileSystem.exists(legacyReceipt)).toBe(false); + + // 2. If the registry updates the same-version archive URL and the new download fails, + // a durable baseline permanently rejects the receipt-less legacy binary for the new artifact + // across repeated calls and server restarts. failSwappedDownload = true; currentAgent = { ...makeAgent({ @@ -962,24 +1018,112 @@ describe("AcpRegistrySupport", () => { }), version: "1.0.0", }; - const changedArtifactFailure = yield* resolver + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const changedArtifactFailure1 = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactFailure1.reason).toBe("download_failed"); + const changedArtifactFailure2 = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactFailure2.reason).toBe("download_failed"); + const restartedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir, + registryUrl, + }); + const changedArtifactAfterRestart = yield* restartedResolver .resolve(settings(), "/workspace") .pipe(Effect.flip); - expect(changedArtifactFailure.reason).toBe("download_failed"); + expect(changedArtifactAfterRestart.reason).toBe("download_failed"); - // 3. Once the updated same-version archive URL succeeds, download_failed on the stale - // cached URL refreshes the index, retries the new launch signature, and writes an immutable slot. + // 3. A single resolve() starting from a stale failing archive URL refreshes the index, + // retries the updated same-version archive URL, and succeeds. + const retryCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-retry-", + }); + const staleRetryAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.0.0-removed.bin", + cmd: "./bin/example-agent", + args: ["--v1-old"], + }, + }, + }), + version: "1.0.0", + }; + yield* fileSystem.makeDirectory(path.join(retryCacheDir, "acp-registry"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(retryCacheDir, "acp-registry", "registry.json"), + makeRegistry(staleRetryAgent), + ); failSwappedDownload = false; - const swappedResolved = yield* resolver.resolve(settings(), "/workspace"); - expect(swappedResolved.agent?.version).toBe("1.0.0"); - expect(swappedResolved.spawn.command).not.toBe(legacyBinary); + requests = []; + const retryResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: retryCacheDir, + toolsDir: path.join(retryCacheDir, "tools"), + registryUrl, + }); + const retriedResolved = yield* retryResolver.resolve(settings(), "/workspace"); + expect(retriedResolved.agent?.version).toBe("1.0.0"); + expect(yield* fileSystem.readFileString(retriedResolved.spawn.command)).toBe( + "#!/bin/sh\necho v1-fixed\n", + ); + expect(requests).toEqual([ + "https://example.test/example-agent-1.0.0-removed.bin", + registryUrl, + swappedArchiveUrl, + ]); + + // Install a receipted primary slot AND a newer receipted artifact slot in 1.0.0 on a clean cache + // so prior-version fallback and terminal PATH ordering can be verified unambiguously. + const fallbackCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-prior-version-", + }); + const fallbackToolsDir = path.join(fallbackCacheDir, "tools"); + const fallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: fallbackCacheDir, + toolsDir: fallbackToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-primary"], + env: { AGENT_CHANNEL: "v1-primary" }, + }, + }, + }), + version: "1.0.0", + }; + const primaryV1 = yield* fallbackResolver.resolve(settings(), "/workspace"); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: swappedArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-fixed"], + env: { AGENT_CHANNEL: "v1-fixed" }, + }, + }, + }), + version: "1.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const swappedResolved = yield* fallbackResolver.resolve(settings(), "/workspace"); expect(swappedResolved.spawn.command).toMatch( /linux-x86_64-[0-9a-f]{12}[\\/]bin[\\/]example-agent$/, ); - expect(yield* fileSystem.readFileString(swappedResolved.spawn.command)).toBe( - "#!/bin/sh\necho v1-fixed\n", - ); - expect(yield* fileSystem.readFileString(legacyBinary)).toBe("#!/bin/sh\necho legacy-v1\n"); // 4. A mismatched receipt at the same version is never reused when a repackaged download fails. currentAgent = { @@ -994,15 +1138,15 @@ describe("AcpRegistrySupport", () => { }), version: "1.0.0", }; - yield* resolver.invalidateIndex(); - yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const mismatchedSameVersionError = yield* resolver + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const mismatchedSameVersionError = yield* fallbackResolver .resolve(settings(), "/workspace") .pipe(Effect.flip); expect(mismatchedSameVersionError.reason).toBe("download_failed"); - // 5. When upstream publishes 2.0.0 whose download fails, resolve falls back to the - // receipted 1.0.0 install with its recorded version, args, env, and fallback=true. + // 5. When upstream publishes 2.0.0 whose download fails (or checksum mismatches), resolve falls + // back to the newest receipted prior slot (1.0.0 replacement) and terminal PATH keeps it first. failV2Download = true; currentAgent = { ...makeAgent({ @@ -1017,9 +1161,9 @@ describe("AcpRegistrySupport", () => { }), version: "2.0.0", }; - yield* resolver.invalidateIndex(); - yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const fallbackToV1 = yield* resolver.resolve(settings(), "/workspace"); + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackToV1 = yield* fallbackResolver.resolve(settings(), "/workspace"); expect(fallbackToV1.fallback).toBe(true); expect(fallbackToV1.indexRevision).toBeUndefined(); expect(fallbackToV1.agent?.version).toBe("1.0.0"); @@ -1027,10 +1171,79 @@ describe("AcpRegistrySupport", () => { expect(fallbackToV1.spawn.args).toEqual(["--v1-fixed"]); expect(fallbackToV1.spawn.env?.AGENT_CHANNEL).toBe("v1-fixed"); expect(fallbackToV1.launchIdentity).toBe(swappedResolved.launchIdentity); + + const managedAfterV2Bump = yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir: fallbackCacheDir, + toolsDir: fallbackToolsDir, + platform: "linux", + architecture: "x64", + }); + expect(managedAfterV2Bump.slice(0, 2)).toEqual([ + path.dirname(swappedResolved.spawn.command), + path.dirname(primaryV1.spawn.command), + ]); + + // A broken 2.0.0 checksum also falls back to receipted 1.0.0 rather than stranding the user. + failV2Download = false; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + sha256: "0".repeat(64), + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const checksumFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(checksumFallback.fallback).toBe(true); + expect(checksumFallback.agent?.version).toBe("1.0.0"); + expect(checksumFallback.spawn.command).toBe(swappedResolved.spawn.command); + + // 6. Installing 2.0.0 and then rolling back upstream to 1.5.0 (which fails download) must fall + // back only to versions strictly below 1.5.0 (1.0.0), never silently running newer 2.0.0. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const installedV2 = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(installedV2.agent?.version).toBe("2.0.0"); + + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.5.0.bin", + cmd: "./bin/example-agent", + }, + }, + }), + version: "1.5.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rollbackFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(rollbackFallback.fallback).toBe(true); + expect(rollbackFallback.agent?.version).toBe("1.0.0"); }).pipe( Effect.scoped, Effect.provide( layerResolver((request) => { + requests.push(request.url); if (offline) { return Effect.succeed( HttpClientResponse.fromWeb(request, new Response("offline", { status: 503 })), @@ -1041,16 +1254,16 @@ describe("AcpRegistrySupport", () => { HttpClientResponse.fromWeb(request, new Response(makeRegistry(currentAgent))), ); } + if (request.url === legacyArchiveUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(v1PrimaryBytes)), + ); + } if (request.url === swappedArchiveUrl && !failSwappedDownload) { return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v1Bytes))); } if (request.url === v2ArchiveUrl && !failV2Download) { - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response(new TextEncoder().encode("#!/bin/sh\necho v2\n")), - ), - ); + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v2Bytes))); } return Effect.succeed( HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), @@ -1709,19 +1922,32 @@ describe("AcpRegistrySupport", () => { const packageSwapDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-launch-identity-", }); + const hostPlatform = HostProcess.Platform.defaultValue(); + const hostArchitecture = HostProcess.Architecture.defaultValue(); + const isWindowsHost = hostPlatform === "win32"; + const hostBinaryOs = + hostPlatform === "darwin" ? "darwin" : isWindowsHost ? "windows" : "linux"; + const hostBinaryArch = hostArchitecture === "arm64" ? "aarch64" : "x86_64"; + const binaryTargetKey = `${hostBinaryOs}-${hostBinaryArch}` as const; const swapResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: packageSwapDir, toolsDir: `${packageSwapDir}/tools`, registryUrl, - }); - const toolchain = yield* makeFakeNpmToolchain(packageSwapDir); + }).pipe( + Effect.provideService(HostProcess.Platform, hostPlatform), + Effect.provideService(HostProcess.Architecture, hostArchitecture), + Effect.provideService(SpawnExecutableResolution, (command) => + command === "npm" || command.endsWith("override-agent") ? command : undefined, + ), + ); + const swapEnvironment: NodeJS.ProcessEnv = {}; upstream = { ...makeAgent({ npx: { package: "@example/old@1.0.0" } }), version: "1.0.0", website: "https://example.test/docs-a", }; yield* swapResolver.refreshIndex(refreshOptions); - const oldPackageInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + const oldPackageInspection = yield* swapResolver.inspect(settings(), swapEnvironment); expect(oldPackageInspection).toMatchObject({ status: "ready", version: "1.0.0", @@ -1735,7 +1961,7 @@ describe("AcpRegistrySupport", () => { }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const newPackageInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + const newPackageInspection = yield* swapResolver.inspect(settings(), swapEnvironment); expect(newPackageInspection).toMatchObject({ status: "ready", version: "1.0.0" }); expect( oldPackageInspection.status === "ready" && @@ -1750,7 +1976,7 @@ describe("AcpRegistrySupport", () => { }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const docsOnlyInspection = yield* swapResolver.inspect(settings(), toolchain.environment); + const docsOnlyInspection = yield* swapResolver.inspect(settings(), swapEnvironment); expect(docsOnlyInspection).toMatchObject({ status: "ready", version: "1.0.0", @@ -1763,22 +1989,20 @@ describe("AcpRegistrySupport", () => { ).toBe(true); // commandOverride ignores version/package bumps it does not launch, while tracking args and env separately. - const hostPlatform = HostProcess.Platform.defaultValue(); - const isWindowsHost = hostPlatform === "win32"; const overridePath = `${packageSwapDir}/override-agent`; yield* fileSystem.writeFileString(overridePath, "#!/bin/sh\necho override\n"); if (!isWindowsHost) { yield* fileSystem.chmod(overridePath, 0o755); } const overrideSettings = settings({ commandPath: overridePath }); - const overrideBase = yield* swapResolver.inspect(overrideSettings, toolchain.environment); + const overrideBase = yield* swapResolver.inspect(overrideSettings, swapEnvironment); upstream = { ...makeAgent({ npx: { package: "@example/other@2.0.0" } }), version: "2.0.0", }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const overrideBumped = yield* swapResolver.inspect(overrideSettings, toolchain.environment); + const overrideBumped = yield* swapResolver.inspect(overrideSettings, swapEnvironment); expect(overrideBase.status === "ready" && overrideBumped.status === "ready").toBe(true); expect( overrideBase.status === "ready" && overrideBumped.status === "ready" @@ -1794,10 +2018,7 @@ describe("AcpRegistrySupport", () => { }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const overrideArgsOnly = yield* swapResolver.inspect( - overrideSettings, - toolchain.environment, - ); + const overrideArgsOnly = yield* swapResolver.inspect(overrideSettings, swapEnvironment); expect( overrideBumped.status === "ready" && overrideArgsOnly.status === "ready" && @@ -1812,10 +2033,7 @@ describe("AcpRegistrySupport", () => { }; yield* swapResolver.invalidateIndex(); yield* swapResolver.refreshIndex(refreshOptions); - const overrideEnvOnly = yield* swapResolver.inspect( - overrideSettings, - toolchain.environment, - ); + const overrideEnvOnly = yield* swapResolver.inspect(overrideSettings, swapEnvironment); expect( overrideBumped.status === "ready" && overrideEnvOnly.status === "ready" && @@ -1823,16 +2041,6 @@ describe("AcpRegistrySupport", () => { ).toBe(true); // Binary launchIdentity tracks archive, sha256, cmd, args, and env while ignoring website/icon changes. - const binaryTargetKey = isWindowsHost ? "windows-x86_64" : "linux-x86_64"; - const binaryPlatform = isWindowsHost ? "win32" : "linux"; - const binarySwapResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: packageSwapDir, - toolsDir: `${packageSwapDir}/tools`, - registryUrl, - }).pipe( - Effect.provideService(HostProcess.Platform, binaryPlatform), - Effect.provideService(HostProcess.Architecture, "x64"), - ); const binaryExe = `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin/agent`; yield* fileSystem.makeDirectory( `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin`, @@ -1861,9 +2069,9 @@ describe("AcpRegistrySupport", () => { ...(meta?.website ? { website: meta.website } : {}), ...(meta?.icon ? { icon: meta.icon } : {}), }; - yield* binarySwapResolver.invalidateIndex(); - yield* binarySwapResolver.refreshIndex(refreshOptions); - const inspected = yield* binarySwapResolver.inspect(settings(), toolchain.environment); + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const inspected = yield* swapResolver.inspect(settings(), swapEnvironment); expect(inspected.status).toBe("ready"); return inspected.status === "ready" ? inspected.launchIdentity : undefined; }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 71fcd69735290..f72a325e98da5 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -416,7 +416,8 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged ); for (const agent of (yield* listDirectories(installsDirectory)).toSorted()) { const versions = (yield* listDirectories(path.join(installsDirectory, agent))).toSorted( - (left, right) => right.localeCompare(left, undefined, { numeric: true }), + (left, right) => + compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), ); for (const version of versions) { const versionRoot = path.join(installsDirectory, agent, version); @@ -424,26 +425,65 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(target)) { const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution .binary?.[candidateTarget]; - const commandSegments = + const preferredCommandSegments = binaryTarget === undefined ? undefined : normalizeRegistryCommandPath(binaryTarget.cmd); const preferredArtifactDir = binaryTarget === undefined ? undefined : binaryArtifactDirName(candidateTarget, binaryTarget); - const candidateEntries = [ - ...(preferredArtifactDir !== undefined && versionEntries.includes(preferredArtifactDir) - ? [preferredArtifactDir] - : []), - ...(versionEntries.includes(candidateTarget) ? [candidateTarget] : []), - ]; - for (const entry of candidateEntries) { - const installRoot = path.join(versionRoot, entry); - const directory = - commandSegments === undefined - ? installRoot - : path.join(installRoot, ...commandSegments.slice(0, -1)); - if (yield* fileSystem.exists(directory).pipe(Effect.orElseSucceed(() => false))) { - directories.push(directory); + const matchingEntries = versionEntries.filter((entry) => + isBinaryPlatformEntry(entry, candidateTarget), + ); + const inspectedSlots = yield* Effect.forEach(matchingEntries, (entry) => + Effect.gen(function* () { + const installRoot = path.join(versionRoot, entry); + const rawReceipt = yield* fileSystem + .readFileString(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.option); + const receipt = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + const isPreferred = entry === preferredArtifactDir; + const isPrimary = entry === candidateTarget; + // Skip un-receipted artifact-scoped leftovers; they cannot be valid installs. + if (!isPreferred && Option.isNone(receipt) && !isPrimary) { + return Option.none<{ + readonly rank: number; + readonly mtimeMs: number; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + const receiptSegments = Option.isSome(receipt) + ? normalizeRegistryCommandPath(receipt.value.cmd) + : undefined; + const segments = isPreferred + ? (preferredCommandSegments ?? receiptSegments) + : (receiptSegments ?? (isPrimary ? preferredCommandSegments : undefined)); + const directory = + segments === undefined + ? installRoot + : path.join(installRoot, ...segments.slice(0, -1)); + const mtimeMs = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => (Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0)), + Effect.orElseSucceed(() => 0), + ); + const rank = isPreferred ? 0 : Option.isSome(receipt) ? 1 : 2; + return Option.some({ rank, mtimeMs, isPrimary, entry, directory }); + }), + ); + const orderedSlots = inspectedSlots + .filter(Option.isSome) + .map((slot) => slot.value) + .toSorted( + (left, right) => + left.rank - right.rank || + right.mtimeMs - left.mtimeMs || + Number(left.isPrimary) - Number(right.isPrimary) || + left.entry.localeCompare(right.entry), + ); + for (const slot of orderedSlots) { + if (yield* fileSystem.exists(slot.directory).pipe(Effect.orElseSucceed(() => false))) { + directories.push(slot.directory); } } } @@ -616,7 +656,9 @@ const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; +const BINARY_LEGACY_BASELINE_FILENAME = ".t3-legacy-baseline.json"; const BINARY_ARTIFACT_SLOT_HASH_LENGTH = 12; +const DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS = 60 * 1_000; const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ version: Schema.optional(Schema.String), @@ -631,6 +673,45 @@ const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( Schema.fromJsonString(AcpRegistryBinaryArtifactReceipt), ); +const AcpRegistryBinaryLegacyBaseline = Schema.Struct({ + artifactKey: Schema.String, +}); +const decodeBinaryLegacyBaseline = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryBinaryLegacyBaseline), +); +const encodeBinaryLegacyBaseline = (artifactKey: string): string => JSON.stringify({ artifactKey }); + +function safeDecodeVersionDir(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +function compareRegistryVersions(left: string, right: string): number { + const splitVersion = (raw: string) => { + const stripped = raw.replace(/^v(?=\d)/iu, "").split("+", 1)[0] ?? raw; + const hyphenIndex = stripped.indexOf("-"); + const core = hyphenIndex === -1 ? stripped : stripped.slice(0, hyphenIndex); + const prerelease = hyphenIndex === -1 ? undefined : stripped.slice(hyphenIndex + 1); + return { core: core.split("."), prerelease }; + }; + const a = splitVersion(left); + const b = splitVersion(right); + const maxLen = Math.max(a.core.length, b.core.length); + for (let index = 0; index < maxLen; index += 1) { + const diff = (a.core[index] ?? "0").localeCompare(b.core[index] ?? "0", undefined, { + numeric: true, + }); + if (diff !== 0) return diff; + } + if (a.prerelease === undefined && b.prerelease === undefined) return 0; + if (a.prerelease === undefined) return 1; + if (b.prerelease === undefined) return -1; + return a.prerelease.localeCompare(b.prerelease, undefined, { numeric: true }); +} + function binaryArtifactIdentityKey(target: typeof AcpRegistryBinaryTarget.Type): string { return JSON.stringify({ archive: target.archive, @@ -858,6 +939,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return permit.withPermits(1); }; const preparedBinaryReservations = yield* Ref.make>(new Map()); + // In-memory mirror of durable legacy baselines so disk write errors still keep a superseded + // pre-receipt binary from matching a newly published artifact at the same version. + const legacyBaselineByInstallRoot = new Map(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -1111,8 +1195,69 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const registry = yield* decodeRegistryText(collected.text); - yield* writeRegistryCache(collected.text); - return registry; + return { registry, text: collected.text }; + }); + + const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( + inMemoryPrevious: AcpRegistryIndex | undefined, + nextIndex: AcpRegistryIndex, + ) { + if (platformTarget === undefined) return; + const candidates = resolveAcpRegistryPlatformTargetCandidates(platformTarget); + const pendingLegacyInstalls: Array<{ + readonly agentId: string; + readonly version: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly nextTarget: typeof AcpRegistryBinaryTarget.Type; + readonly installRoot: string; + readonly baselinePath: string; + }> = []; + for (const nextAgent of nextIndex.agents) { + if (nextAgent.distribution.binary === undefined) continue; + for (const candidateTarget of candidates) { + const nextTarget = nextAgent.distribution.binary[candidateTarget]; + if (nextTarget === undefined) continue; + const installRoot = path.join(agentInstallRoot(nextAgent), candidateTarget); + const baselinePath = path.join(installRoot, BINARY_LEGACY_BASELINE_FILENAME); + if (legacyBaselineByInstallRoot.has(installRoot)) continue; + const installExists = yield* fileSystem + .exists(installRoot) + .pipe(Effect.orElseSucceed(() => false)); + if (!installExists) continue; + const hasReceipt = yield* fileSystem + .exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.orElseSucceed(() => false)); + if (hasReceipt) continue; + const hasBaseline = yield* fileSystem + .exists(baselinePath) + .pipe(Effect.orElseSucceed(() => false)); + if (hasBaseline) continue; + pendingLegacyInstalls.push({ + agentId: nextAgent.id, + version: nextAgent.version, + candidateTarget, + nextTarget, + installRoot, + baselinePath, + }); + } + } + if (pendingLegacyInstalls.length === 0) return; + const previousIndex = inMemoryPrevious ?? Option.getOrUndefined(yield* readCachedRegistry); + if (previousIndex === undefined) return; + const previousById = new Map(previousIndex.agents.map((agent) => [agent.id, agent] as const)); + for (const pending of pendingLegacyInstalls) { + const previousAgent = previousById.get(pending.agentId); + if (previousAgent === undefined || previousAgent.version !== pending.version) continue; + const previousTarget = previousAgent.distribution.binary?.[pending.candidateTarget]; + if (previousTarget === undefined) continue; + const previousKey = binaryArtifactIdentityKey(previousTarget); + if (binaryArtifactIdentityKey(pending.nextTarget) === previousKey) continue; + legacyBaselineByInstallRoot.set(pending.installRoot, previousKey); + yield* fileSystem + .writeFileString(pending.baselinePath, encodeBinaryLegacyBaseline(previousKey)) + .pipe(Effect.ignore); + } }); const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { @@ -1160,7 +1305,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const startInvalidationGeneration = current.invalidationGeneration; const result = yield* fetchRegistry().pipe( - Effect.map((index) => ({ index, refreshed: true as const })), + Effect.flatMap(({ registry, text }) => + recordLegacyBaselines(current.index, registry).pipe( + Effect.andThen(writeRegistryCache(text)), + Effect.as({ index: registry, refreshed: true as const }), + ), + ), Effect.catch((networkError) => Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; @@ -1817,6 +1967,45 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); + const isLegacyBinarySlotEligible = Effect.fn("AcpRegistryCatalog.isLegacyBinarySlotEligible")( + function* ( + paths: NonNullable>, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if ( + !(yield* fileSystem.exists(paths.executablePath).pipe(Effect.orElseSucceed(() => false))) + ) { + return false; + } + const versionRoot = path.dirname(paths.installRoot); + const versionEntries = yield* fileSystem + .readDirectory(versionRoot) + .pipe(Effect.orElseSucceed((): Array => [])); + for (const entry of versionEntries) { + if (!isBinaryPlatformEntry(entry, paths.platformTarget)) continue; + if ( + yield* fileSystem + .exists(path.join(versionRoot, entry, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.orElseSucceed(() => false)) + ) { + return false; + } + } + const currentKey = binaryArtifactIdentityKey(target); + const memoryBaseline = legacyBaselineByInstallRoot.get(paths.installRoot); + if (memoryBaseline !== undefined) { + return memoryBaseline === currentKey; + } + const baselinePath = path.join(paths.installRoot, BINARY_LEGACY_BASELINE_FILENAME); + if (!(yield* fileSystem.exists(baselinePath).pipe(Effect.orElseSucceed(() => false)))) { + return true; + } + const rawBaseline = yield* fileSystem.readFileString(baselinePath).pipe(Effect.option); + const decoded = Option.flatMap(rawBaseline, decodeBinaryLegacyBaseline); + return Option.isSome(decoded) && decoded.value.artifactKey === currentKey; + }, + ); + const findMatchingBinarySlot = Effect.fn("AcpRegistryCatalog.findMatchingBinarySlot")(function* ( paths: NonNullable>, target: typeof AcpRegistryBinaryTarget.Type, @@ -1835,6 +2024,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct executablePath: paths.executablePath, }); } + if (yield* isLegacyBinarySlotEligible(paths, target)) { + return Option.some({ + root: paths.installRoot, + executablePath: paths.executablePath, + }); + } return Option.none<{ readonly root: string; readonly executablePath: string }>(); }); @@ -2038,12 +2233,37 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), encodeBinaryArtifactReceipt(agent, target), ); + // Recheck right before promotion in case a stale-lock takeover let another installer publish + // a valid receipt-matching slot while this staging download was in flight. + const concurrentSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(concurrentSlot)) { + const validated = yield* assertExecutableInRoot( + concurrentSlot.value.root, + concurrentSlot.value.executablePath, + ).pipe(Effect.option); + if (Option.isSome(validated)) { + return validated.value; + } + } if (destinationRoot === artifactRoot) { - // An un-receipted leftover at this content-addressed slot cannot be a valid install. + // Only remove an un-receipted or invalid leftover at the content-addressed slot. yield* fileSystem.remove(destinationRoot, { recursive: true, force: true }); } - yield* fileSystem.rename(extractionRoot, destinationRoot); - return yield* assertExecutableInRoot(destinationRoot, destinationExecutable); + const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( + Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), + Effect.catch((renameError) => + findMatchingBinarySlot(paths, target).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(renameError), + onSome: (slot) => assertExecutableInRoot(slot.root, slot.executablePath), + }), + ), + Effect.mapError(() => renameError), + ), + ), + ); + return promotedPath; }).pipe( Effect.scoped, Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), @@ -2369,14 +2589,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); - const safeDecodeVersionDir = (value: string): string => { - try { - return decodeURIComponent(value); - } catch { - return value; - } - }; - const resolveFallbackInstalledBinary = Effect.fn( "AcpRegistryCatalog.resolveFallbackInstalledBinary", )(function* ( @@ -2384,8 +2596,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct cwd: string, environment: NodeJS.ProcessEnv | undefined, registry: AcpRegistryIndex, - indexRevision: number, - options: { readonly allowLegacySameVersion: boolean }, ) { if (settings.commandPath.trim().length > 0 || platformTarget === undefined) { return Option.none(); @@ -2403,63 +2613,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveEnvironment = environment ?? hostEnvironment; return yield* withInstallPermit(agent.id)( Effect.gen(function* () { - const target = distribution.binaryTarget!; - const paths = binaryPaths(agent, target); - // 1. Preserve a validated receipt-less legacy install at the same version without writing a receipt, - // only if no receipted slot has been installed for this version and target yet. - if (options.allowLegacySameVersion && paths !== undefined) { - const versionRoot = path.dirname(paths.installRoot); - const versionEntries = yield* fileSystem - .readDirectory(versionRoot) - .pipe(Effect.orElseSucceed((): Array => [])); - const targetSlots = versionEntries.filter((entry) => - isBinaryPlatformEntry(entry, paths.platformTarget), - ); - let hasAnyReceipt = false; - for (const slot of targetSlots) { - if ( - yield* fileSystem - .exists(path.join(versionRoot, slot, BINARY_ARTIFACT_RECEIPT_FILENAME)) - .pipe(Effect.orElseSucceed(() => false)) - ) { - hasAnyReceipt = true; - break; - } - } - const executableExists = - !hasAnyReceipt && - (yield* fileSystem - .exists(paths.executablePath) - .pipe(Effect.orElseSucceed(() => false))); - if (executableExists) { - const validated = yield* assertExecutableInRoot( - paths.installRoot, - paths.executablePath, - ).pipe(Effect.option); - if (Option.isSome(validated)) { - const resolved = yield* buildResolvedRegistrySpawn({ - agent, - distribution, - command: validated.value, - cwd, - effectiveEnvironment, - indexRevision, - }); - return Option.some(resolved); - } - } - } - // 2. Fall back to the newest receipted prior installed version so failed new-version downloads do not strand the agent. + // Fall back only to receipted versions strictly older than the registry's current version + // so failed upgrades do not strand the agent and upstream rollbacks never run a newer build. const agentRoot = path.join(installsDirectory, agent.id); - const currentVersionDir = encodeURIComponent(agent.version); const versions = (yield* fileSystem .readDirectory(agentRoot) .pipe(Effect.orElseSucceed((): Array => []))) - .filter((entry) => entry !== currentVersionDir) + .filter( + (entry) => compareRegistryVersions(safeDecodeVersionDir(entry), agent.version) < 0, + ) .toSorted((left, right) => - safeDecodeVersionDir(right).localeCompare(safeDecodeVersionDir(left), undefined, { - numeric: true, - }), + compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), ); for (const versionDir of versions) { const versionRoot = path.join(agentRoot, versionDir); @@ -2478,17 +2642,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.map((info) => ({ dir, entry, + isPrimary: entry === candidateTarget, mtimeMs: Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, })), - Effect.orElseSucceed(() => ({ dir, entry, mtimeMs: 0 })), + Effect.orElseSucceed(() => ({ + dir, + entry, + isPrimary: entry === candidateTarget, + mtimeMs: 0, + })), ); }); - candidatesWithMtime.sort((left, right) => { - // Prefer artifact-scoped slots over the older primary slot when both exist. - if (left.entry === candidateTarget && right.entry !== candidateTarget) return 1; - if (right.entry === candidateTarget && left.entry !== candidateTarget) return -1; - return right.mtimeMs - left.mtimeMs || left.entry.localeCompare(right.entry); - }); + candidatesWithMtime.sort( + (left, right) => + right.mtimeMs - left.mtimeMs || + Number(left.isPrimary) - Number(right.isPrimary) || + left.entry.localeCompare(right.entry), + ); for (const { dir } of candidatesWithMtime) { const rawReceipt = yield* fileSystem .readFileString(path.join(dir, BINARY_ARTIFACT_RECEIPT_FILENAME)) @@ -2630,43 +2800,49 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } satisfies ResolvedAcpRegistryAgent; } const { index: registry, indexRevision } = yield* loadRegistrySnapshot(); + const canFallbackOnError = (reason: AcpRegistryErrorReason) => + reason === "download_failed" || + reason === "checksum_mismatch" || + reason === "archive_invalid"; return yield* resolveWithRegistry(settings, cwd, environment, registry, indexRevision).pipe( Effect.catchIf( - (error) => error.reason === "download_failed", + (error) => canFallbackOnError(error.reason), (error) => Effect.gen(function* () { - const refreshed = yield* Effect.result(refreshRegistry()); let activeRegistry = registry; - let activeRevision = indexRevision; - let downloadError = error; - let artifactChanged = false; - if (Result.isSuccess(refreshed)) { - const { index: latest, indexRevision: latestRevision } = refreshed.success; - const agentId = settings.agentId.trim(); - const launchSignatureIn = (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 - ? agent.version - : registryLaunchIdentity({ version: agent.version, distribution }); - }; - if (launchSignatureIn(latest) !== launchSignatureIn(registry)) { - artifactChanged = true; - const retried = yield* Effect.result( - resolveWithRegistry(settings, cwd, environment, latest, latestRevision), - ); - if (Result.isSuccess(retried)) return retried.success; - if (retried.failure.reason !== "download_failed") { - return yield* retried.failure; + let activeError = error; + if (error.reason === "download_failed") { + const refreshed = yield* Effect.result( + refreshRegistry({ failureBackoffMs: DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS }), + ); + if (Result.isSuccess(refreshed)) { + const { index: latest, indexRevision: latestRevision } = refreshed.success; + const agentId = settings.agentId.trim(); + const artifactSignatureIn = (index: AcpRegistryIndex) => { + const agent = index.agents.find((candidate) => candidate.id === agentId); + if (agent === undefined) return undefined; + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined) return agent.version; + if (distribution.kind === "binary" && distribution.binaryTarget !== undefined) { + return `${agent.version}\0${binaryArtifactIdentityKey(distribution.binaryTarget)}`; + } + return registryLaunchIdentity({ version: agent.version, distribution }); + }; + if (artifactSignatureIn(latest) !== artifactSignatureIn(registry)) { + const retried = yield* Effect.result( + resolveWithRegistry(settings, cwd, environment, latest, latestRevision), + ); + if (Result.isSuccess(retried)) return retried.success; + if (!canFallbackOnError(retried.failure.reason)) { + return yield* retried.failure; + } + activeRegistry = latest; + activeError = retried.failure; } - activeRegistry = latest; - activeRevision = latestRevision; - downloadError = retried.failure; } } const fallback = yield* resolveFallbackInstalledBinary( @@ -2674,11 +2850,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct cwd, environment, activeRegistry, - activeRevision, - { allowLegacySameVersion: !artifactChanged }, ); if (Option.isSome(fallback)) return fallback.value; - return yield* downloadError; + return yield* activeError; }), ), ); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 73e11c9ff9839..f87cb31d99d82 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -15,6 +15,7 @@ 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 Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as HttpClient from "effect/http/HttpClient"; @@ -23,8 +24,10 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; @@ -830,7 +833,11 @@ describe("acpRegistryEnrichmentCache", () => { it("does not renew the cache deadline when live configuration is replayed unchanged", () => { const provider = providerWithModels(settledConfiguration.models, "auto"); - const cache = { generation: 1, entry: { provider, expiresAt: 1_000 } }; + const cache = { + invalidationGeneration: 1, + liveGenerationByRuntime: new Map(), + entry: { provider, expiresAt: 1_000 }, + }; const replayed = updateAcpRegistryEnrichmentCache({ cache, @@ -848,7 +855,11 @@ describe("acpRegistryEnrichmentCache", () => { [{ id: "smodel", name: "Default", description: null }], "smodel", ); - const cache = { generation: 1, entry: { provider, expiresAt: 1_000 } }; + const cache = { + invalidationGeneration: 1, + liveGenerationByRuntime: new Map(), + entry: { provider, expiresAt: 1_000 }, + }; const updated = updateAcpRegistryEnrichmentCache({ cache, @@ -859,11 +870,16 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.entry?.provider.models.map((m) => m.slug)).toEqual(["auto", "qmodel", "kmodel"]); expect((updated.entry?.expiresAt ?? 0) - 5_000).toBe(15 * 60 * 1_000); - expect(updated.generation).toBe(2); + expect(updated.invalidationGeneration).toBe(1); + expect(updated.liveGenerationByRuntime.get(null)).toBe(1); }); it("advances the cache epoch when a live update arrives before any probe lands", () => { - const cache = { generation: 4, entry: null }; + const cache = { + invalidationGeneration: 4, + liveGenerationByRuntime: new Map(), + entry: null, + }; const updated = updateAcpRegistryEnrichmentCache({ cache, @@ -872,7 +888,8 @@ describe("acpRegistryEnrichmentCache", () => { now: 5_000, }); - expect(updated.generation).toBe(5); + expect(updated.invalidationGeneration).toBe(4); + expect(updated.liveGenerationByRuntime.get(null)).toBe(1); expect(updated.entry).toBeNull(); }); @@ -882,7 +899,8 @@ describe("acpRegistryEnrichmentCache", () => { "smodel", ); const cache = { - generation: 3, + invalidationGeneration: 3, + liveGenerationByRuntime: new Map(), entry: { provider, expiresAt: 1_000, launchIdentity: "runtime-v1" }, }; @@ -895,7 +913,8 @@ describe("acpRegistryEnrichmentCache", () => { }); expect(ignored).toBe(cache); - expect(ignored.generation).toBe(3); + expect(ignored.invalidationGeneration).toBe(3); + expect(ignored.liveGenerationByRuntime.size).toBe(0); expect(ignored.entry?.provider.models.map((m) => m.slug)).toEqual(["smodel"]); }); }); @@ -1615,7 +1634,21 @@ describe("AcpRegistryDriver registry recovery", () => { let remoteVersion = "2.0.0"; let remoteWebsite: string | undefined = undefined; let failArchiveDownload = false; + let probeResolveAttempts = 0; let onFallbackResolved: (() => Effect.Effect) | null = null; + let onEnrichmentEnd: ((exit: Exit.Exit) => void) | null = null; + const testTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnrichmentEnd?.(exit); + }; + return inner; + }, + }; const initialGate = { started: yield* Deferred.make(), release: yield* Deferred.make(), @@ -1663,7 +1696,12 @@ describe("AcpRegistryDriver registry recovery", () => { const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, resolve: (settings, cwd, environment) => - realCatalog.resolve(settings, cwd, environment).pipe( + Effect.sync(() => { + if (environment?.MISE_OFFLINE === "1") { + probeResolveAttempts += 1; + } + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), Effect.tap((resolved) => resolved.fallback && onFallbackResolved !== null ? onFallbackResolved() @@ -1680,9 +1718,12 @@ describe("AcpRegistryDriver registry recovery", () => { instanceId: identity.instanceId, displayName: identity.displayName, enabled: true, - environment: [], + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], config: decodeSettings({ agentId: "test-agent" }), - }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); // On cold startup, the disk-cached 1.0.0 probe publishes before the slow 2.0.0 registry fetch finishes. const coldReady = yield* instance.snapshot.streamChanges.pipe( @@ -1755,8 +1796,22 @@ describe("AcpRegistryDriver registry recovery", () => { expect(Option.isSome(yield* Fiber.join(upgradedToV3))).toBe(true); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); - // If 4.0.0 fails to download, the driver falls back to the installed 3.0.0 without - // acknowledging the 4.0.0 revision, then upgrades to 4.0.0 once the archive recovers. + // If 4.0.0 fails to download, the driver falls back to the installed 3.0.0 with a user-visible + // status message, stays flicker-free during backoff, does not acknowledge the 4.0.0 revision, + // and upgrades to 4.0.0 once backoff expires and the archive recovers. + const v3LiveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-live-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "v3-live-cmd" }], + skills: [], + }); + expect(Option.isSome(yield* Fiber.join(v3LiveApplied))).toBe(true); + gate = null; remoteVersion = "4.0.0"; remoteWebsite = "https://example.test/v4"; @@ -1778,11 +1833,45 @@ describe("AcpRegistryDriver registry recovery", () => { yield* TestClock.adjust("16 minutes"); yield* instance.snapshot.refresh; yield* Deferred.await(fallbackObserved); - expect(Option.isSome(yield* Fiber.join(fallbackPublished))).toBe(true); + const fallbackSnapshot = Option.getOrThrow(yield* Fiber.join(fallbackPublished)); + expect(fallbackSnapshot.message).toContain("4.0.0"); + expect(fallbackSnapshot.slashCommands).toEqual([{ name: "v3-live-cmd" }]); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(false); onFallbackResolved = null; - // Recovering without invalidating the cached 4.0.0 index still upgrades because fallback did not acknowledge it. + // Refreshing inside the 60s fallback backoff window must not flicker to 4.0.0, drop v3 live + // commands, or re-run probe/download attempts. + const resolvesBeforeBackoffRefresh = probeResolveAttempts; + const backoffSnapshots: Array = []; + const backoffCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + backoffSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const backoffEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(backoffEnrichmentDone, Exit.void); + } + }; + yield* TestClock.adjust("30 seconds"); + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(backoffEnrichmentDone); + onEnrichmentEnd = null; + yield* Fiber.interrupt(backoffCollector); + expect(probeResolveAttempts).toBe(resolvesBeforeBackoffRefresh); + expect(backoffSnapshots.every((snapshot) => snapshot.version === "3.0.0")).toBe(true); + expect( + backoffSnapshots.every((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-live-cmd"), + ), + ).toBe(true); + + // Once backoff expires, recovering without invalidating the cached 4.0.0 index still upgrades + // because fallback did not acknowledge the 4.0.0 revision. failArchiveDownload = false; const upgradedToV4 = yield* instance.snapshot.streamChanges.pipe( Stream.filter( @@ -1791,9 +1880,39 @@ describe("AcpRegistryDriver registry recovery", () => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + yield* TestClock.adjust("31 seconds"); yield* instance.snapshot.refresh; - expect(Option.isSome(yield* Fiber.join(upgradedToV4))).toBe(true); + const v4Snapshot = Option.getOrThrow(yield* Fiber.join(upgradedToV4)); + expect(v4Snapshot.message).toBeUndefined(); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(true); + + // A freshly created instance on a cached failing 5.0.0 index falls back to 4.0.0 in a single + // probe without double-probing when refreshIndex does not advance the revision. + remoteVersion = "5.0.0"; + failArchiveDownload = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvesBeforeFreshFallback = probeResolveAttempts; + const freshFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(freshFallbackDone, Exit.void); + } + }; + const freshInstance = yield* AcpRegistryDriver.create({ + instanceId: ProviderInstanceId.make("acpRegistry_fallback_single_probe"), + displayName: "Fallback Single Probe", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(freshFallbackDone); + onEnrichmentEnd = null; + expect((yield* freshInstance.snapshot.getSnapshot).version).toBe("4.0.0"); + expect(probeResolveAttempts).toBe(resolvesBeforeFreshFallback + 1); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); @@ -1821,24 +1940,26 @@ describe("AcpRegistryDriver registry recovery", () => { let onInspect: | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) | null = null; - let onGetUrlAuthAction: - | ((targetInstanceId: ProviderInstanceId) => Effect.Effect) - | null = null; let onBackgroundProbeOutcome: ((skipped: boolean) => Effect.Effect) | null = null; let onRefreshIndex: Effect.Effect = Effect.void; + let onPublishEnrichmentEnd: ((exit: Exit.Exit) => void) | null = null; + const makeEnrichmentTracer = ( + onEnd: () => ((exit: Exit.Exit) => void) | null, + ): Tracer.Tracer => ({ + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnd()?.(exit); + }; + return inner; + }, + }); const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = { ...baseCoordinator, - getUrlAuthAction: (targetInstanceId) => - baseCoordinator - .getUrlAuthAction(targetInstanceId) - .pipe( - Effect.tap(() => - onGetUrlAuthAction === null - ? Effect.void - : onGetUrlAuthAction(targetInstanceId), - ), - ), runBackgroundProbe: (agentId, effect) => Effect.sync(() => { backgroundProbeCalls += 1; @@ -1927,6 +2048,10 @@ describe("AcpRegistryDriver registry recovery", () => { AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, coordinator, ), + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onPublishEnrichmentEnd), + ), ); // Prime the 1.0.0 probe cache first so subsequent metadata-only refreshes can assert zero re-probes. @@ -2011,20 +2136,15 @@ describe("AcpRegistryDriver registry recovery", () => { // and acknowledges the revision so a follow-up refresh skips rechecking. remoteExtraAgentVersion = "9.9.9"; let unrelatedRefreshed = false; - const unrelatedReadinessCompleted = yield* Deferred.make(); + const unrelatedEnrichmentDone = yield* Deferred.make(); onRefreshIndex = Effect.sync(() => { unrelatedRefreshed = true; }); - onGetUrlAuthAction = (targetInstanceId) => - unrelatedRefreshed && targetInstanceId === identity.instanceId - ? Deferred.succeed(unrelatedReadinessCompleted, undefined).pipe(Effect.asVoid) - : Effect.void; - const probesBeforeUnrelated = backgroundProbeCalls; - yield* catalog.invalidateIndex(); - yield* instance.snapshot.refresh; - // Wait until the post-refresh inspectReadiness finishes its last async step (getUrlAuthAction), - // then observe a live command update to guarantee the no-reprobe/acknowledge branch has settled. - yield* Deferred.await(unrelatedReadinessCompleted); + onPublishEnrichmentEnd = (exit) => { + if (unrelatedRefreshed && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(unrelatedEnrichmentDone, Exit.void); + } + }; const liveCommandApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.slashCommands.some((command) => command.name === "live-updated"), @@ -2032,13 +2152,23 @@ describe("AcpRegistryDriver registry recovery", () => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const probesBeforeUnrelated = backgroundProbeCalls; yield* coordinator.publishAvailableCommands(identity.instanceId, { slashCommands: [{ name: "live-updated" }], skills: [], }); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh.pipe( + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onPublishEnrichmentEnd), + ), + ); + // Wait for publishEnrichment itself to finish its post-refresh decision before asserting counts. + yield* Deferred.await(unrelatedEnrichmentDone); expect(Option.isSome(yield* Fiber.join(liveCommandApplied))).toBe(true); onRefreshIndex = Effect.void; - onGetUrlAuthAction = null; + onPublishEnrichmentEnd = null; // 1 auth.refreshMethods + 1 initialProbe; 0 post-recheck probe calls. expect(backgroundProbeCalls).toBe(probesBeforeUnrelated + 2); expect(resolveAttempts).toBe(resolvesAfterInitialProbe); @@ -2050,20 +2180,24 @@ describe("AcpRegistryDriver registry recovery", () => { const secondInstanceId = ProviderInstanceId.make("acpRegistry_second_fresh"); let secondInstanceRefreshed = false; let secondInstancePostRefreshInspects = 0; - const secondInstanceRefreshDone = yield* Deferred.make(); + const secondEnrichmentDone = yield* Deferred.make(); onRefreshIndex = Effect.sync(() => { secondInstanceRefreshed = true; - }).pipe( - Effect.andThen(Deferred.succeed(secondInstanceRefreshDone, undefined)), - Effect.asVoid, - ); + }); onInspectStart = () => secondInstanceRefreshed ? Effect.sync(() => { secondInstancePostRefreshInspects += 1; }) : Effect.void; - const secondInstance = yield* AcpRegistryDriver.create({ + let onSecondEnrichmentEnd: ((exit: Exit.Exit) => void) | null = ( + exit, + ) => { + if (secondInstanceRefreshed && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(secondEnrichmentDone, Exit.void); + } + }; + yield* AcpRegistryDriver.create({ instanceId: secondInstanceId, displayName: "Second ACP", enabled: true, @@ -2075,21 +2209,14 @@ describe("AcpRegistryDriver registry recovery", () => { AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, coordinator, ), - ); - const secondSettled = yield* secondInstance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => - snapshot.slashCommands.some((command) => command.name === "second-settled"), + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onSecondEnrichmentEnd), ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), ); - yield* Deferred.await(secondInstanceRefreshDone); - // Keep the inspect hook active until a live update on secondInstance settles past the skip decision. - yield* coordinator.publishAvailableCommands(secondInstanceId, { - slashCommands: [{ name: "second-settled" }], - skills: [], - }); - expect(Option.isSome(yield* Fiber.join(secondSettled))).toBe(true); + // Wait for secondInstance's publishEnrichment span to complete past the revision skip decision. + yield* Deferred.await(secondEnrichmentDone); + onSecondEnrichmentEnd = null; onRefreshIndex = Effect.void; onInspectStart = null; expect(secondInstancePostRefreshInspects).toBe(0); @@ -2507,10 +2634,14 @@ describe("AcpRegistryDriver registry recovery", () => { ); let remoteVersion = "1.0.0"; - let v2ResolveGate: { + let failProbeSpawn = false; + let inspectCalls = 0; + let resolveGate: { + readonly matchVersion: string; readonly started: Deferred.Deferred; readonly release: Deferred.Deferred; } | null = null; + let onInspectCallback: (() => Effect.Effect) | null = null; let queuedStaleConfigGate: { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; @@ -2561,19 +2692,32 @@ describe("AcpRegistryDriver registry recovery", () => { ); const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCalls += 1; + }).pipe( + Effect.andThen(() => realCatalog.inspect(settings, environment)), + Effect.tap(() => (onInspectCallback === null ? Effect.void : onInspectCallback())), + ), resolve: (settings, cwd, environment) => Effect.gen(function* () { const resolved = yield* realCatalog.resolve(settings, cwd, environment); if ( environment?.MISE_OFFLINE === "1" && - resolved.agent?.version === "2.0.0" && - v2ResolveGate !== null + resolveGate !== null && + resolved.agent?.version === resolveGate.matchVersion ) { - const gate = v2ResolveGate; - v2ResolveGate = null; + const gate = resolveGate; + resolveGate = null; yield* Deferred.succeed(gate.started, undefined); yield* Deferred.await(gate.release); } + if (environment?.MISE_OFFLINE === "1" && failProbeSpawn) { + return yield* new AcpRegistrySupport.AcpRegistryError({ + reason: "install_failed", + detail: `Simulated probe install failure for ${resolved.agent?.version ?? "unknown"}.`, + }); + } return { ...resolved, spawn: { command: process.execPath, args: [agentPath, modelsPath] }, @@ -2609,6 +2753,74 @@ describe("AcpRegistryDriver registry recovery", () => { expect(v1Inspection.status).toBe("ready"); const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; + // 0. Same-runtime live config update arriving while a v1 probe is in flight discards the + // older v1 probe so stale probe models cannot overwrite newer live configuration. + yield* instance.invalidateCaches ?? Effect.void; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v1-stale-probe-a", "v1-stale-probe-b"]), + ); + const v1ProbeGate = { + matchVersion: "1.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v1ProbeGate; + const v1ProbeSnapshots: Array = []; + const v1ProbeCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + v1ProbeSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(v1ProbeGate.started); + const v1NewerLiveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "v1-newer-live-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-newer-live-a", + availableModels: [ + { modelId: "v1-newer-live-a", name: "v1-newer-live-a" }, + { modelId: "v1-newer-live-b", name: "v1-newer-live-b" }, + ], + }), + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(v1NewerLiveApplied))).toBe(true); + yield* Deferred.succeed(v1ProbeGate.release, undefined); + const v1SettledAfterRelease = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v1-after-superseded-probe"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v1-after-superseded-probe" }], skills: [] }, + v1Identity, + ); + const v1AfterSuperseded = Option.getOrThrow(yield* Fiber.join(v1SettledAfterRelease)); + yield* Fiber.interrupt(v1ProbeCollector); + expect(v1AfterSuperseded.models.map((model) => model.slug)).toEqual([ + "v1-newer-live-a", + "v1-newer-live-b", + ]); + expect( + v1ProbeSnapshots.every( + (snapshot) => !snapshot.models.some((model) => model.slug === "v1-stale-probe-a"), + ), + ).toBe(true); + // Start a refresh that upgrades 1.0.0 -> 2.0.0 mid-enrichment while the live watcher stays active. remoteVersion = "2.0.0"; yield* fileSystem.writeFileString( @@ -2616,11 +2828,12 @@ describe("AcpRegistryDriver registry recovery", () => { JSON.stringify(["v2-probed-a", "v2-probed-b"]), ); yield* realCatalog.invalidateIndex(); - const resolveGate = { + const v2ProbeGate = { + matchVersion: "2.0.0", started: yield* Deferred.make(), release: yield* Deferred.make(), }; - v2ResolveGate = resolveGate; + resolveGate = v2ProbeGate; const v2ProbedReady = yield* instance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, @@ -2629,7 +2842,7 @@ describe("AcpRegistryDriver registry recovery", () => { Effect.forkScoped({ startImmediately: true }), ); yield* instance.snapshot.refresh; - yield* Deferred.await(resolveGate.started); + yield* Deferred.await(v2ProbeGate.started); const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); expect(v2Inspection.status).toBe("ready"); const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; @@ -2695,7 +2908,10 @@ describe("AcpRegistryDriver registry recovery", () => { ); yield* Deferred.await(staleGate.entered); - // 3. Publish v2 live state before the v2 probe lands; v2 must preserve it without inheriting v1 learnedModels. + // 3. Publish v2 live state while the v2 probe is already in flight; inFlightProbeIdentity must + // skip spawning a redundant reconcile inspect, and v2 must preserve its live state without + // inheriting v1 learnedModels. + const inspectsBeforeInFlightV2 = inspectCalls; yield* coordinator.publishAvailableCommands( identity.instanceId, { slashCommands: [{ name: "v2-live-cmd" }], skills: [] }, @@ -2712,9 +2928,10 @@ describe("AcpRegistryDriver registry recovery", () => { }), v2Identity, ); - yield* Deferred.succeed(resolveGate.release, undefined); + yield* Deferred.succeed(v2ProbeGate.release, undefined); const publishedV2 = Option.getOrThrow(yield* Fiber.join(v2ProbedReady)); + expect(inspectCalls).toBe(inspectsBeforeInFlightV2); expect(publishedV2.models.map((model) => model.slug)).toEqual([ "v2-live-a", "shared-model", @@ -2741,7 +2958,9 @@ describe("AcpRegistryDriver registry recovery", () => { expect(Option.isSome(yield* Fiber.join(v2PostClear))).toBe(true); // 4. Release the queued untagged update (rejected solely by !isCurrent), then publish post-clear v1-tagged - // updates (whose revision is AFTER clear, so rejected solely by runtimeIdentity) without evicting v2 state. + // updates (whose revision is AFTER clear, so rejected solely by runtimeIdentity) without evicting v2 state + // and without triggering reconcile catalog.inspect disk I/O for retired v1. + const inspectsBeforeRetiredV1 = inspectCalls; const liveRaceSnapshots = yield* instance.snapshot.streamChanges.pipe( Stream.takeUntil( (snapshot) => @@ -2793,6 +3012,7 @@ describe("AcpRegistryDriver registry recovery", () => { v2Identity, ); const observedAfterRace = yield* Fiber.join(liveRaceSnapshots); + expect(inspectCalls).toBe(inspectsBeforeRetiredV1); expect( observedAfterRace.every( (snapshot) => @@ -2818,11 +3038,28 @@ describe("AcpRegistryDriver registry recovery", () => { Stream.filter( (snapshot) => snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined && snapshot.slashCommands.some((command) => command.name === "v3-session-cmd"), ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const v3EnrichmentSettled = yield* Deferred.make(); + let sawV3Enrichment = false; + const v3Tracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + if (sawV3Enrichment && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(v3EnrichmentSettled, Exit.void); + } + }; + return inner; + }, + }; yield* coordinator.publishAvailableCommands( identity.instanceId, { slashCommands: [{ name: "v3-session-cmd" }], skills: [] }, @@ -2831,6 +3068,113 @@ describe("AcpRegistryDriver registry recovery", () => { const v3Snapshot = Option.getOrThrow(yield* Fiber.join(reconciledV3)); expect(v3Snapshot.version).toBe("3.0.0"); expect(v3Snapshot.slashCommands).toEqual([{ name: "v3-session-cmd" }]); + // Settle the 3.0.0 enrichment cycle before counting inspects for the unmatched-runtime check. + sawV3Enrichment = true; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, v3Tracer)); + yield* Deferred.await(v3EnrichmentSettled); + + // An unrecognized runtime identity that does NOT match catalog.inspect must not trigger a refresh. + const unmatchedChecked = yield* Deferred.make(); + onInspectCallback = () => Deferred.succeed(unmatchedChecked, undefined).pipe(Effect.asVoid); + const inspectsBeforeUnmatched = inspectCalls; + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "bogus-future-cmd" }], skills: [] }, + "unmatched-future-runtime", + ); + yield* Deferred.await(unmatchedChecked); + onInspectCallback = null; + const v3Check = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-still-active"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-still-active" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(v3Check))).toBe(true); + // Only the 1 reconcile inspect ran; no refresh (which would invoke another inspect) fired. + expect(inspectCalls).toBe(inspectsBeforeUnmatched + 1); + + // 6. A failed upgrade probe (4.0.0 fails before resolving/starting) must NOT report 4.0.0 as + // installed, wipe v3 coordinator state, or reject subsequent v3 live updates. + remoteVersion = "4.0.0"; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + const failedUpgradeWarning = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const warningSnapshot = Option.getOrThrow(yield* Fiber.join(failedUpgradeWarning)); + expect(warningSnapshot.version).toBe("3.0.0"); + expect(warningSnapshot.slashCommands).toEqual([{ name: "v3-still-active" }]); + expect( + yield* coordinator.getAvailableCommands(identity.instanceId, { + runtimeIdentity: v3Identity, + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "v3-still-active" }], skills: [] })); + const v3AfterFailedUpgrade = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-after-failed-v4"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-after-failed-v4" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(v3AfterFailedUpgrade))).toBe(true); + failProbeSpawn = false; + + // 7. Disposing a driver instance removes its coordinator state and marks earlier metadata stale. + const disposedInstanceId = ProviderInstanceId.make("acpRegistry_disposed_cleanup"); + const disposedScope = yield* Scope.make(); + let disposedMeta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta | null = null; + const disposedWatched = yield* Deferred.make(); + const disposedWatcher = yield* coordinator + .watchAvailableCommands(disposedInstanceId, (_commands, meta) => + Effect.sync(() => { + disposedMeta = meta; + }).pipe(Effect.andThen(Deferred.succeed(disposedWatched, undefined)), Effect.asVoid), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* AcpRegistryDriver.create({ + instanceId: disposedInstanceId, + displayName: "Disposed ACP", + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Scope.provide(disposedScope), + ); + yield* coordinator.publishAvailableCommands( + disposedInstanceId, + { slashCommands: [{ name: "before-dispose" }], skills: [] }, + v3Identity, + ); + yield* Deferred.await(disposedWatched); + expect(disposedMeta).not.toBeNull(); + expect(yield* disposedMeta!.isCurrent).toBe(true); + yield* Scope.close(disposedScope, Exit.void); + expect(Option.isNone(yield* coordinator.getAvailableCommands(disposedInstanceId))).toBe( + true, + ); + expect(yield* disposedMeta!.isCurrent).toBe(false); + yield* Fiber.interrupt(disposedWatcher); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 4e5b1fdab9e2d..f045a328ec368 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -80,9 +80,8 @@ function acpRegistryProbeTtlMs(provider: ServerProvider): number { } interface AcpRegistryEnrichmentCache { - readonly generation: number; - readonly invalidationGeneration?: number; - readonly liveGenerationByRuntime?: ReadonlyMap; + readonly invalidationGeneration: number; + readonly liveGenerationByRuntime: ReadonlyMap; readonly entry: { readonly provider: ServerProvider; readonly expiresAt: number; @@ -91,7 +90,7 @@ interface AcpRegistryEnrichmentCache { } function nextLiveGenerationByRuntime( - current: ReadonlyMap | undefined, + current: ReadonlyMap, runtimeIdentity: string | null, ): ReadonlyMap { const next = new Map(current); @@ -134,7 +133,6 @@ export function updateAcpRegistryEnrichmentCache(input: { // without discarding an upgrade probe targeting a different runtime. return { ...cache, - generation: cache.generation + 1, liveGenerationByRuntime: nextLiveGenerationByRuntime( cache.liveGenerationByRuntime, runtimeKey, @@ -166,7 +164,6 @@ export function updateAcpRegistryEnrichmentCache(input: { // Advance only this runtime's live epoch so an in-flight probe for the same // runtime discards stale results without invalidating an upgrade probe for // a newer runtime. - generation: cache.generation + 1, liveGenerationByRuntime: nextLiveGenerationByRuntime(cache.liveGenerationByRuntime, runtimeKey), entry: { ...cache.entry, @@ -587,6 +584,16 @@ interface CheckedAcpRegistryReadiness { readonly launchIdentity: string | null; readonly indexRevision: number | null; readonly fallback?: boolean; + readonly probeFailed?: boolean; +} + +interface ActiveFallbackState { + readonly targetLaunchIdentity: string | null; + readonly targetVersion: string | null; + readonly fallbackVersion: string | null; + readonly fallbackLaunchIdentity: string | null; + readonly failedAtMs: number; + readonly message: string; } function runtimeIdentityFor( @@ -634,6 +641,9 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( readonly indexRevision: number | null; readonly cacheable: boolean; readonly fallback?: boolean; + readonly fallbackTargetLaunchIdentity?: string | null; + readonly fallbackTargetVersion?: string | null; + readonly probeFailed?: boolean; }, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements @@ -694,9 +704,10 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( inspection: inspected.success, probeError: probed.failure, }), - launchIdentity: inspected.success.launchIdentity ?? null, + launchIdentity: null, indexRevision: inspectedIndexRevision, cacheable: false, + probeFailed: true, }; } if (input.settings.source === "local") { @@ -756,7 +767,13 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( indexRevision: resolved.indexRevision ?? null, cacheable: resolved.launchIdentity !== undefined || inspected.success.launchIdentity === undefined, - ...(resolved.fallback ? { fallback: true } : {}), + ...(resolved.fallback + ? { + fallback: true, + fallbackTargetLaunchIdentity: inspected.success.launchIdentity ?? null, + fallbackTargetVersion: inspected.success.version, + } + : {}), }; }); @@ -1029,25 +1046,53 @@ export const AcpRegistryDriver: ProviderDriver(null); const latestCheckedReadiness = yield* Ref.make(null); + const activeFallback = yield* Ref.make(null); + const retiredRuntimeIdentities = yield* Ref.make>(new Set()); const inspectReadiness = (options?: { readonly applySessionLiveState?: boolean; readonly seedActiveRuntimeIdentity?: boolean; + readonly preserveActiveFallback?: boolean; }) => checkAcpRegistryProviderReadinessWithIdentity(readinessInput).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => - Ref.get(reportedLocalVersion).pipe( - Effect.map((version) => ({ - snapshot: + Effect.all({ + version: Ref.get(reportedLocalVersion), + fallbackState: Ref.get(activeFallback), + }).pipe( + Effect.map(({ version, fallbackState }) => { + const withLocalVersion = snapshot.installed && snapshot.version === null && version !== null ? { ...snapshot, version } - : snapshot, - launchIdentity, - indexRevision, - })), + : snapshot; + if ( + options?.preserveActiveFallback === true && + fallbackState !== null && + withLocalVersion.installed && + launchIdentity !== null && + launchIdentity === fallbackState.targetLaunchIdentity + ) { + return { + snapshot: { + ...withLocalVersion, + version: fallbackState.fallbackVersion, + message: withLocalVersion.message ?? fallbackState.message, + }, + launchIdentity: fallbackState.fallbackLaunchIdentity, + indexRevision, + fallback: true as const, + }; + } + return { + snapshot: withLocalVersion, + launchIdentity, + indexRevision, + fallback: false as const, + }; + }), ), ), - Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => { + Effect.flatMap(({ snapshot, launchIdentity, indexRevision, fallback }) => { const nextIdentity = snapshot.installed ? runtimeIdentityFor(snapshot, launchIdentity) : null; @@ -1078,13 +1123,17 @@ export const AcpRegistryDriver: ProviderDriver Ref.set(latestCheckedReadiness, readiness)), Effect.map(({ snapshot }) => snapshot), ); @@ -1117,18 +1166,20 @@ export const AcpRegistryDriver: ProviderDriver Ref.get(lastSeenIndexRevision))); }); const enrichmentCache = yield* Ref.make({ - generation: 0, invalidationGeneration: 0, liveGenerationByRuntime: new Map(), entry: null, }); const liveSnapshotSemaphore = yield* Semaphore.make(1); - const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({ - generation: current.generation + 1, - invalidationGeneration: (current.invalidationGeneration ?? 0) + 1, - liveGenerationByRuntime: new Map(), - entry: null, - })); + const invalidateEnrichmentCache = Ref.set(activeFallback, null).pipe( + Effect.andThen( + Ref.update(enrichmentCache, (current) => ({ + invalidationGeneration: current.invalidationGeneration + 1, + liveGenerationByRuntime: new Map(), + entry: null, + })), + ), + ); const isProbeStillCurrent = ( current: AcpRegistryEnrichmentCache, captured: { @@ -1137,8 +1188,8 @@ export const AcpRegistryDriver: ProviderDriver - (current.invalidationGeneration ?? 0) === captured.invalidationGeneration && - (current.liveGenerationByRuntime?.get(probeIdentity) ?? 0) === + current.invalidationGeneration === captured.invalidationGeneration && + (current.liveGenerationByRuntime.get(probeIdentity) ?? 0) === (captured.liveGenerationByRuntime.get(probeIdentity) ?? 0); const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* ( target: CheckedAcpRegistryReadiness, @@ -1146,9 +1197,8 @@ export const AcpRegistryDriver: ProviderDriver(), + invalidationGeneration: cacheState.invalidationGeneration, + liveGenerationByRuntime: cacheState.liveGenerationByRuntime, }; const cached = cacheState.entry; if ( @@ -1165,10 +1215,17 @@ export const AcpRegistryDriver: ProviderDriver(null); + const pendingReconcileIdentity = yield* Ref.make(null); const maybeReconcileUnmatchedRuntime = (incomingIdentity: string | undefined) => { if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; return Effect.gen(function* () { - if ((yield* Ref.get(inFlightProbeIdentity)) === incomingIdentity) return; + if ((yield* Ref.get(retiredRuntimeIdentities)).has(incomingIdentity)) return; + if ((yield* Ref.get(inFlightProbeIdentity)) === incomingIdentity) { + yield* Ref.set(pendingReconcileIdentity, incomingIdentity); + return; + } const claimed = yield* Ref.modify(reconcilingRuntimeIdentity, (current) => current === incomingIdentity ? ([false, current] as const) @@ -1334,65 +1404,180 @@ export const AcpRegistryDriver: ProviderDriver({ published: false, readiness: null }), - onSome: ({ provider, launchIdentity, indexRevision, fallback, captured }) => - liveSnapshotSemaphore.withPermit( - Effect.gen(function* () { - const nextIdentity = provider.installed - ? runtimeIdentityFor(provider, launchIdentity) - : null; - const current = yield* Ref.get(enrichmentCache); - if (!isProbeStillCurrent(current, captured, nextIdentity)) { - return { published: false, readiness: null }; - } - const previousIdentity = yield* Ref.get(activeRuntimeIdentity); - const runtimeChanged = - previousIdentity !== null && - nextIdentity !== null && - previousIdentity !== nextIdentity; - const { provider: nextSnapshot, appliedLiveConfiguration } = - yield* withLiveRuntimeState(provider, { - sessionRuntimeIdentity: nextIdentity, - requireMatchingRuntimeIdentity: runtimeChanged, - useLearnedModels: !runtimeChanged, - persistLearnedModels: false, - }); - const published = yield* tryPublishSnapshot(nextSnapshot); - if (published) { - if (!provider.installed) { - if (previousIdentity !== null || current.entry !== null) { - yield* clearLiveState(); - yield* invalidateEnrichmentCache; - } - yield* Ref.set(expectedRuntimeIdentity, null); - } else if (runtimeChanged) { - yield* clearLiveState({ preserveRuntimeIdentity: nextIdentity }); - if (appliedLiveConfiguration) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - yield* Ref.set(expectedRuntimeIdentity, nextIdentity); - } else { - if (appliedLiveConfiguration && nextSnapshot.models !== provider.models) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - if (nextIdentity !== null) { - yield* Ref.set(activeRuntimeIdentity, nextIdentity); + onSome: ({ + provider, + launchIdentity, + indexRevision, + fallback, + fallbackTargetLaunchIdentity, + fallbackTargetVersion, + probeFailed, + fromCache, + captured, + }) => + liveSnapshotSemaphore + .withPermit( + Effect.gen(function* () { + const previousIdentity = yield* Ref.get(activeRuntimeIdentity); + const resolvedIdentity = + provider.installed && !probeFailed + ? runtimeIdentityFor(provider, launchIdentity) + : null; + const current = yield* Ref.get(enrichmentCache); + if (!isProbeStillCurrent(current, captured, resolvedIdentity)) { + return { + published: false, + readiness: null, + publishedIdentity: null, + }; + } + if (probeFailed && provider.installed && previousIdentity !== null) { + // The new runtime failed before resolving/starting; keep the active runtime's + // identity, installed version, and live state intact so running sessions survive. + const currentSnapshot = yield* getSnapshot; + const preservedVersion = + currentSnapshot.installed && + currentSnapshot.version !== null && + currentSnapshot.version !== provider.version + ? currentSnapshot.version + : provider.version; + const { provider: nextSnapshot } = yield* withLiveRuntimeState( + { ...provider, version: preservedVersion }, + { + sessionRuntimeIdentity: previousIdentity, + requireMatchingRuntimeIdentity: false, + useLearnedModels: true, + persistLearnedModels: false, + }, + ); + const published = yield* tryPublishSnapshot(nextSnapshot); + if (published) { + yield* Ref.set(expectedRuntimeIdentity, previousIdentity); } - yield* Ref.set(expectedRuntimeIdentity, nextIdentity); + return { + published, + readiness: published + ? { + snapshot: nextSnapshot, + launchIdentity: previousIdentity, + indexRevision, + probeFailed: true, + } + : null, + publishedIdentity: previousIdentity, + }; } - } - return { - published, - readiness: published - ? { - snapshot: provider, - launchIdentity, - indexRevision, - ...(fallback ? { fallback: true } : {}), + const fallbackMessage = + fallback && !fromCache + ? fallbackTargetVersion !== null && + provider.version !== null && + fallbackTargetVersion !== provider.version + ? `Could not install ${effectiveConfig.agentId} ${fallbackTargetVersion}; using installed ${provider.version}. Will retry on the next refresh.` + : "Could not install the latest agent update; using the previously installed version. Will retry on the next refresh." + : undefined; + const existingFallback = fallback ? yield* Ref.get(activeFallback) : null; + const effectiveMessage = + provider.message ?? fallbackMessage ?? existingFallback?.message; + const providerToPublish = + fallback && effectiveMessage !== undefined + ? { ...provider, message: effectiveMessage } + : provider; + const runtimeChanged = + previousIdentity !== null && + resolvedIdentity !== null && + previousIdentity !== resolvedIdentity; + const { provider: nextSnapshot, appliedLiveConfiguration } = + yield* withLiveRuntimeState(providerToPublish, { + sessionRuntimeIdentity: resolvedIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: false, + }); + const published = yield* tryPublishSnapshot(nextSnapshot); + if (published) { + if (!providerToPublish.installed) { + yield* Ref.set(activeFallback, null); + if (previousIdentity !== null || current.entry !== null) { + yield* clearLiveState(); + yield* invalidateEnrichmentCache; } - : null, - }; - }), - ), + yield* Ref.set(expectedRuntimeIdentity, null); + } else { + if (fallback && !fromCache) { + const failedAtMs = yield* Clock.currentTimeMillis; + yield* Ref.set(activeFallback, { + targetLaunchIdentity: fallbackTargetLaunchIdentity, + targetVersion: fallbackTargetVersion, + fallbackVersion: providerToPublish.version, + fallbackLaunchIdentity: launchIdentity, + failedAtMs, + message: + fallbackMessage ?? + existingFallback?.message ?? + "Using the previously installed version.", + }); + } else if (!fallback && !probeFailed) { + yield* Ref.set(activeFallback, null); + } + if (runtimeChanged) { + yield* clearLiveState({ preserveRuntimeIdentity: resolvedIdentity }); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + const next = new Set(retired); + next.add(previousIdentity); + next.delete(resolvedIdentity); + return next; + }); + if (appliedLiveConfiguration) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } else { + if ( + appliedLiveConfiguration && + nextSnapshot.models !== providerToPublish.models + ) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + if (resolvedIdentity !== null) { + yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + if (!retired.has(resolvedIdentity)) return retired; + const next = new Set(retired); + next.delete(resolvedIdentity); + return next; + }); + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } + } + } + return { + published, + readiness: published + ? { + snapshot: providerToPublish, + launchIdentity, + indexRevision, + ...(fallback ? { fallback: true } : {}), + ...(probeFailed ? { probeFailed: true } : {}), + } + : null, + publishedIdentity: resolvedIdentity, + }; + }), + ) + .pipe( + Effect.tap(({ publishedIdentity }) => + Ref.getAndSet(pendingReconcileIdentity, null).pipe( + Effect.flatMap((pending) => + pending !== null && pending !== publishedIdentity + ? maybeReconcileUnmatchedRuntime(pending) + : Effect.void, + ), + ), + ), + Effect.map(({ published, readiness }) => ({ published, readiness })), + ), }), ), Effect.ensuring( @@ -1570,6 +1755,7 @@ export const AcpRegistryDriver: ProviderDriver= revision) ? acknowledgeRevision(readiness.indexRevision ?? revision) : Effect.void, @@ -1595,11 +1781,20 @@ export const AcpRegistryDriver: ProviderDriver= revision ) { - return; + const fallbackState = yield* Ref.get(activeFallback); + const now = yield* Clock.currentTimeMillis; + if ( + fallbackState === null || + (now >= fallbackState.failedAtMs && + now - fallbackState.failedAtMs < REGISTRY_FAILURE_BACKOFF_MS) + ) { + return; + } } if ( initialProbe.published && !publishedReadiness.fallback && + !publishedReadiness.probeFailed && publishedReadiness.indexRevision !== null && publishedReadiness.indexRevision >= revision ) { @@ -1628,6 +1823,7 @@ export const AcpRegistryDriver: ProviderDriver= revision) ) { @@ -1638,11 +1834,12 @@ export const AcpRegistryDriver: ProviderDriver= revision) ) { yield* acknowledgeRevision(rechecked.indexRevision ?? revision); } - }); + }).pipe(Effect.withSpan("AcpRegistryDriver.publishEnrichment")); yield* runWithLiveWatchers(publishEnrichment); }), }).pipe( diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index daf7e3c5038c3..95bfe3f60242b 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -455,178 +455,183 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); const result = yield* Effect.gen(function* () { - // Resolution may install packages; bound it by the probe deadline. + // Binary downloads and package installs carry their own bounded timeouts inside AcpRegistryCatalog; + // apply the probe timeout only to spawning and probing the resolved agent. 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, - ).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "probe_failed", - message: "Could not prepare temporary history for the DeepSeek Harness probe.", - cause, - }), - ), - ); - const authMethodsRef = yield* Ref.make>([]); - const authActionRef = yield* Ref.make(undefined); - const runtimeCoordinator = yield* Effect.serviceOption( - AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, - ); - const runtimeContext = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn, - cwd: input.cwd, - clientCapabilities: { - auth: { terminal: Option.isSome(pty) }, - elicitation: { url: {} }, - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { name: "t3-code-provider-test", version: "0.0.0" }, - authenticateOnAuthRequired: false, - onInitialized: (initializeResult) => - Ref.set( - authMethodsRef, - normalizeAcpRegistryAuthMethods(initializeResult.authMethods, { - command: resolved.spawn.command, - args: resolved.spawn.args, + return yield* Effect.gen(function* () { + const spawn = yield* isolateDeepSeekProbeHistory( + input.settings.commandPath, + resolved.spawn, + ).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "probe_failed", + message: "Could not prepare temporary history for the DeepSeek Harness probe.", + cause, }), - ), - ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}), - }).pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - Layer.succeed(SecureRandom.SecureRandom, random), + ), + ); + const authMethodsRef = yield* Ref.make>([]); + const authActionRef = yield* Ref.make(undefined); + const runtimeCoordinator = yield* Effect.serviceOption( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + ); + const runtimeContext = yield* Layer.build( + AcpSessionRuntime.layer({ + spawn, + cwd: input.cwd, + clientCapabilities: { + auth: { terminal: Option.isSome(pty) }, + elicitation: { url: {} }, + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + }, + clientInfo: { name: "t3-code-provider-test", version: "0.0.0" }, + authenticateOnAuthRequired: false, + onInitialized: (initializeResult) => + Ref.set( + authMethodsRef, + normalizeAcpRegistryAuthMethods(initializeResult.authMethods, { + command: resolved.spawn.command, + args: resolved.spawn.args, + }), + ), + ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}), + }).pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + Layer.succeed(SecureRandom.SecureRandom, random), + ), ), ), - ), - ); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(runtimeContext), - ); - const commandsRef = yield* Ref.make( - emptyAcpRegistryAvailableCommands(), - ); - const commandsAdvertised = yield* Deferred.make(); - const configOptionsRef = yield* Ref.make< - ReadonlyArray | undefined - >(undefined); - const modelsAdvertised = yield* Deferred.make(); - yield* runtime.handleElicitation((request) => - Effect.gen(function* () { - if ( - request.mode !== "url" || - !("url" in request) || - !("elicitationId" in request) || - typeof request.url !== "string" || - typeof request.elicitationId !== "string" - ) { - return { action: "decline" } as const; + ); + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + Effect.provide(runtimeContext), + ); + const commandsRef = yield* Ref.make( + emptyAcpRegistryAvailableCommands(), + ); + const commandsAdvertised = yield* Deferred.make(); + const configOptionsRef = yield* Ref.make< + ReadonlyArray | undefined + >(undefined); + const modelsAdvertised = yield* Deferred.make(); + yield* runtime.handleElicitation((request) => + Effect.gen(function* () { + if ( + request.mode !== "url" || + !("url" in request) || + !("elicitationId" in request) || + typeof request.url !== "string" || + typeof request.elicitationId !== "string" + ) { + return { action: "decline" } as const; + } + const url = normalizeAcpRegistryWebUrl(request.url); + const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH); + if (url === undefined || elicitationId === undefined) { + return { action: "decline" } as const; + } + const action: AcpRegistryUrlAuthAction = { + elicitationId, + url, + message: boundedText(request.message, MAX_DESCRIPTION_LENGTH), + }; + yield* Ref.set(authActionRef, action); + const accepted = yield* Option.match(runtimeCoordinator, { + onNone: () => Effect.succeed(false), + onSome: (coordinator) => + coordinator.requestUrlAuthentication(input.instanceId, action), + }); + return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const); + }), + ); + yield* runtime.handleSessionUpdate((notification) => { + const update = notification.update; + if (update.sessionUpdate === "available_commands_update") { + return Ref.set( + commandsRef, + normalizeAcpRegistryCommands(update.availableCommands), + ).pipe(Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)), Effect.asVoid); } - const url = normalizeAcpRegistryWebUrl(request.url); - const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH); - if (url === undefined || elicitationId === undefined) { - return { action: "decline" } as const; + if (update.sessionUpdate === "config_option_update") { + const hasAdvertisedModels = acpRegistryAdvertisesModelCatalog(update.configOptions); + return Ref.set(configOptionsRef, update.configOptions).pipe( + Effect.andThen( + hasAdvertisedModels + ? Deferred.succeed(modelsAdvertised, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ); } - const action: AcpRegistryUrlAuthAction = { - elicitationId, - url, - message: boundedText(request.message, MAX_DESCRIPTION_LENGTH), - }; - yield* Ref.set(authActionRef, action); - const accepted = yield* Option.match(runtimeCoordinator, { - onNone: () => Effect.succeed(false), - onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action), - }); - return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const); - }), - ); - yield* runtime.handleSessionUpdate((notification) => { - const update = notification.update; - if (update.sessionUpdate === "available_commands_update") { - return Ref.set(commandsRef, normalizeAcpRegistryCommands(update.availableCommands)).pipe( - Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)), - Effect.asVoid, + return Effect.void; + }); + const startResult = yield* Effect.result(runtime.start()); + if (Result.isFailure(startResult)) { + return yield* acpRegistryProbeFailure( + startResult.failure, + yield* Ref.get(authMethodsRef), + yield* Ref.get(authActionRef), ); } - if (update.sessionUpdate === "config_option_update") { - const hasAdvertisedModels = acpRegistryAdvertisesModelCatalog(update.configOptions); - return Ref.set(configOptionsRef, update.configOptions).pipe( - Effect.andThen( - hasAdvertisedModels - ? Deferred.succeed(modelsAdvertised, undefined).pipe(Effect.asVoid) - : Effect.void, + const started = startResult.success; + // Agents that persist sessions (OpenCode) would otherwise keep one empty session per probe. + // The runtime only sends session/delete when the agent advertises it. + yield* Effect.addFinalizer(() => + runtime + .deleteSession(started.sessionId) + .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore), + ); + const hasInitialModels = acpRegistryAdvertisesModelCatalog( + started.sessionSetupResult.configOptions, + started.sessionSetupResult.models, + ); + + yield* Effect.all( + [ + hasInitialModels + ? Effect.void + : Deferred.await(modelsAdvertised).pipe( + Effect.timeoutOption(MODEL_ADVERTISEMENT_GRACE), + ), + Deferred.await(commandsAdvertised).pipe( + Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE), ), - ); - } - return Effect.void; - }); - const startResult = yield* Effect.result(runtime.start()); - if (Result.isFailure(startResult)) { - return yield* acpRegistryProbeFailure( - startResult.failure, - yield* Ref.get(authMethodsRef), - yield* Ref.get(authActionRef), + ], + { concurrency: "unbounded" }, ); - } - const started = startResult.success; - // Agents that persist sessions (OpenCode) would otherwise keep one empty session per probe. - // The runtime only sends session/delete when the agent advertises it. - yield* Effect.addFinalizer(() => - runtime - .deleteSession(started.sessionId) - .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore), - ); - const hasInitialModels = acpRegistryAdvertisesModelCatalog( - started.sessionSetupResult.configOptions, - started.sessionSetupResult.models, - ); - yield* Effect.all( - [ - hasInitialModels - ? Effect.void - : Deferred.await(modelsAdvertised).pipe( - Effect.timeoutOption(MODEL_ADVERTISEMENT_GRACE), - ), - Deferred.await(commandsAdvertised).pipe( - Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE), - ), - ], - { concurrency: "unbounded" }, - ); + // config_option_update replaces the full option set, so an empty notice is authoritative. + const liveConfiguration = normalizeAcpRegistryLiveConfiguration( + (yield* Ref.get(configOptionsRef)) ?? (yield* runtime.getConfigOptions), + (yield* runtime.getModeState) ?? parseSessionModeState(started.sessionSetupResult), + started.sessionSetupResult.models, + ); - // config_option_update replaces the full option set, so an empty notice is authoritative. - const liveConfiguration = normalizeAcpRegistryLiveConfiguration( - (yield* Ref.get(configOptionsRef)) ?? (yield* runtime.getConfigOptions), - (yield* runtime.getModeState) ?? parseSessionModeState(started.sessionSetupResult), - started.sessionSetupResult.models, + return { + resolved, + started, + commands: yield* Ref.get(commandsRef), + liveConfiguration, + }; + }).pipe( + Effect.timeoutOrElse({ + duration: probeTimeoutMs, + orElse: () => + Effect.fail( + new AcpRegistryOperationError({ + reason: "probe_failed", + 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.`, + }), + ), + }), ); - - return { - resolved, - started, - commands: yield* Ref.get(commandsRef), - liveConfiguration, - }; }).pipe( Effect.scoped, - Effect.timeoutOrElse({ - duration: probeTimeoutMs, - orElse: () => - 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.`, - }), - ), - }), Effect.mapError((error) => error._tag === "AcpRegistryOperationError" ? error : acpRegistryProbeFailure(error), ), From c77ffacf78fa9f513c6a8b1548a71b8111fbdc65 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 13:51:08 +0000 Subject: [PATCH 13/28] fix(acp-registry): harden fallback state, legacy baselines, archive extraction, and coordinator ordering --- .../src/provider/AcpRegistryProbe.test.ts | 65 +++ docs/user/providers-acp.md | 16 +- .../AcpRegistryRuntimeCoordinator.test.ts | 130 ++++- .../server/AcpRegistryRuntimeCoordinator.ts | 87 +-- .../src/server/AcpRegistrySupport.test.ts | 396 +++++++++++++- .../src/server/AcpRegistrySupport.ts | 494 +++++++++++++----- .../src/server/driver.test.ts | 298 +++++++++-- .../src/server/driver.ts | 437 +++++++++++++--- .../provider-acp-registry/src/server/probe.ts | 4 + 9 files changed, 1628 insertions(+), 299 deletions(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index fa8111aaac185..f268017226bbd 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -8,9 +8,12 @@ import * as Layer from "effect/Layer"; import { ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; 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"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -577,4 +580,66 @@ await import(pathToFileURL(agentPath).href); ).reason, ).toBe("probe_failed"); }); + + it.effect( + "does not count slow catalog resolution against the 60s ACP probe timeout and forwards failedTarget", + () => + Effect.gen(function* () { + const resolveStarted = yield* Deferred.make(); + const failedTarget: AcpRegistrySupport.AcpRegistryFailedTarget = { + version: "2.0.0", + launchIdentity: "v2-identity", + indexRevision: 4, + }; + const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), + invalidateIndex: () => Effect.die("unused invalidateIndex"), + inspect: () => Effect.die("unused inspect"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + resolve: () => + Deferred.succeed(resolveStarted, undefined).pipe( + Effect.andThen(Effect.sleep("2 minutes")), + Effect.as({ + agent: { + id: "mock-agent", + name: "Mock Agent", + version: "1.0.0", + description: "ACP probe timeout-split test agent", + distribution: { npx: { package: "mock-agent@1.0.0" } }, + }, + distribution: "npx" as const, + launchIdentity: "v1-identity", + fallback: true, + failedTarget, + spawn: { + command: "node", + args: [mockAgentPath], + env: { ...process.env, T3_ACP_AVAILABLE_COMMANDS: "status" }, + }, + }), + ), + }); + const probeFiber = yield* probeAcpRegistryConfiguration({ + instanceId, + settings: decodeSettings({ agentId: "mock-agent" }), + cwd: process.cwd(), + environment: process.env, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.await(resolveStarted); + yield* TestClock.adjust("2 minutes"); + const result = yield* Fiber.join(probeFiber); + expect(result.probe.ready).toBe(true); + expect(result.resolved).toMatchObject({ + distribution: "npx", + launchIdentity: "v1-identity", + fallback: true, + failedTarget, + }); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 5bbcc8f11e464..3a19b92a52664 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -53,14 +53,14 @@ but keeps package installs. To use an existing local binary, set **Executable ov T3 Code refreshes the Registry index in the background and automatically installs new versions of prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while -that agent is starting a session. If a newly published version cannot be downloaded, T3 Code keeps -running the newest previously installed version until the update succeeds. Agents using -**Executable override** keep running the configured executable—update those overrides directly on -the server—while Registry refreshes can still pick up updated Registry metadata, arguments, and -environment variables. Refreshing providers (in **Settings → Providers** on web and desktop, or -**Refresh providers** in environment settings on mobile) requests a fresh Registry check right away -for unprepared or unavailable agents, and after the agent's status check finishes for installed -agents. +that agent is starting a session. If a newly published version of a T3-managed binary agent cannot +be installed, T3 Code keeps running the newest previously installed version with a recorded install +receipt until the update succeeds. Agents using **Executable override** keep running the configured +executable—update those overrides directly on the server—while Registry refreshes can still pick up +updated Registry metadata, arguments, and environment variables. Refreshing providers (in +**Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on +mobile) requests a fresh Registry check right away for unprepared or unavailable agents, and after +the agent's status check finishes for installed agents. ## Signing in diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 0ccac34e1c19f..1d8588f62ae39 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -175,29 +176,85 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect(yield* Fiber.join(request)).toBe(true); expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); - // Consent must be rejected at the exact expiry boundary as well as after it. - const expiringSeen = yield* Deferred.make(); + // Decouple current-time reads from TestClock sleep so the exact expiry boundary (>=) is + // tested in both getUrlAuthAction and acceptUrlAuthentication while the request is pending. + const baseClock = yield* Clock.Clock; + let clockNowMs = 0; + const decoupledClock: Clock.Clock = { + ...baseClock, + currentTimeMillisUnsafe: () => clockNowMs, + currentTimeMillis: Effect.sync(() => clockNowMs), + currentTimeNanosUnsafe: () => BigInt(clockNowMs) * 1_000_000n, + currentTimeNanos: Effect.sync(() => BigInt(clockNowMs) * 1_000_000n), + monotonicTimeNanosUnsafe: () => BigInt(clockNowMs) * 1_000_000n, + monotonicTimeNanos: Effect.sync(() => BigInt(clockNowMs) * 1_000_000n), + sleep: (duration) => baseClock.sleep(duration), + }; + const withDecoupledClock = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(Clock.Clock, decoupledClock)); + + // Consent must still succeed 1 ms before expiry while the request is pending. + const beforeExpirySeen = yield* Deferred.make(); const expiringWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-before-expiry" + ? Deferred.succeed(beforeExpirySeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const beforeExpiryRequest = yield* withDecoupledClock( + coordinator.requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-before-expiry", + }), + ).pipe(Effect.forkChild); + yield* Deferred.await(beforeExpirySeen); + clockNowMs = 10 * 60 * 1_000 - 1; + expect( + Option.isSome(yield* withDecoupledClock(coordinator.getUrlAuthAction(instanceId))), + ).toBe(true); + expect( + yield* withDecoupledClock( + coordinator.acceptUrlAuthentication({ + instanceId, + elicitationId: "login-before-expiry", + }), + ), + ).toBe(true); + expect(yield* Fiber.join(beforeExpiryRequest)).toBe(true); + yield* Fiber.interrupt(expiringWatcher); + + // Consent must be rejected at the exact expiry millisecond while the timeout has not fired. + clockNowMs = 0; + const exactExpirySeen = yield* Deferred.make(); + const exactExpiryWatcher = yield* coordinator .watchUrlAuthAction(instanceId, (current) => current?.elicitationId === "login-expiring" - ? Deferred.succeed(expiringSeen, undefined).pipe(Effect.asVoid) + ? Deferred.succeed(exactExpirySeen, undefined).pipe(Effect.asVoid) : Effect.void, ) .pipe(Effect.forkChild); - const expiringRequest = yield* coordinator - .requestUrlAuthentication(instanceId, { + const expiringRequest = yield* withDecoupledClock( + coordinator.requestUrlAuthentication(instanceId, { ...action, elicitationId: "login-expiring", - }) - .pipe(Effect.forkChild); - yield* Deferred.await(expiringSeen); - yield* TestClock.adjust("10 minutes"); - expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + }), + ).pipe(Effect.forkChild); + yield* Deferred.await(exactExpirySeen); + clockNowMs = 10 * 60 * 1_000; + expect(expiringRequest.pollUnsafe()).toBeUndefined(); + expect( + Option.isNone(yield* withDecoupledClock(coordinator.getUrlAuthAction(instanceId))), + ).toBe(true); expect( - yield* coordinator.acceptUrlAuthentication({ instanceId, elicitationId: "login-expiring" }), + yield* withDecoupledClock( + coordinator.acceptUrlAuthentication({ instanceId, elicitationId: "login-expiring" }), + ), ).toBe(false); + expect(expiringRequest.pollUnsafe()).toBeUndefined(); + yield* TestClock.adjust("10 minutes"); expect(yield* Fiber.join(expiringRequest)).toBe(false); - yield* Fiber.interrupt(expiringWatcher); + yield* Fiber.interrupt(exactExpiryWatcher); yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); @@ -421,6 +478,55 @@ describe("AcpRegistryRuntimeCoordinator", () => { ); yield* Deferred.await(replayDone); expect(replayedNames).toEqual(["cmd-reused", "cmd-reused-c", "cmd-after-watch"]); + + // 6. Concurrent publications for the same runtime are serialized so watchers always finish + // on the exact latest committed state returned by get(). + const concurrentCount = 12; + const concurrentStartLength = replayedNames.length; + const concurrentDone = yield* Deferred.make(); + const concurrentWatcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands) => + Effect.gen(function* () { + const name = commands.slashCommands[0]?.name ?? "empty"; + if (name.startsWith("concurrent-")) { + replayedNames.push(name); + if (replayedNames.length - concurrentStartLength >= concurrentCount) { + yield* Deferred.succeed(concurrentDone, undefined); + } + } + }), + ) + .pipe(Effect.forkChild); + // Wait for initial replay of concurrentWatcher before firing the concurrent batch. + const concurrentReady = yield* Deferred.make(); + const syncWatcher = yield* coordinator + .watchAvailableCommands(instanceId, () => + Deferred.succeed(concurrentReady, undefined).pipe(Effect.asVoid), + ) + .pipe(Effect.forkChild); + yield* Deferred.await(concurrentReady); + yield* Fiber.interrupt(syncWatcher); + yield* Effect.all( + Array.from({ length: concurrentCount }, (_, index) => + coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: `concurrent-${index}` }], skills: [] }, + "runtime-b", + ), + ), + { concurrency: "unbounded", discard: true }, + ); + yield* Deferred.await(concurrentDone); + const committedLatest = Option.getOrThrow( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-b", + requireMatchingRuntimeIdentity: true, + }), + ); + expect(replayedNames[replayedNames.length - 1]).toBe( + committedLatest.slashCommands[0]?.name, + ); + yield* Fiber.interrupt(concurrentWatcher); yield* Fiber.interrupt(secondWatcher); yield* Fiber.interrupt(watcher); }).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 f662fb1707feb..9b0d432c686dd 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -202,6 +202,7 @@ interface LiveStateChannelNames { const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveStateChannel")( function* (names: LiveStateChannelNames) { const updates = yield* PubSub.unbounded>(); + const publishPermit = yield* Semaphore.make(1); const stateRef = yield* Ref.make>({ revision: 0, instances: new Map(), @@ -255,24 +256,37 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt value: T, runtimeIdentity?: string, ) { - const event = yield* Ref.modify(stateRef, (state) => { - const revision = state.revision + 1; - const existing = state.instances.get(instanceId); - const lifetime = existing?.lifetime ?? revision; - const nextEntries = new Map(existing?.entries); - nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision, lifetime }); - const nextInstances = new Map(state.instances); - nextInstances.set(instanceId, { - lifetime, - entries: nextEntries, - latestKey: runtimeIdentity, - hasLatest: true, - clear: existing?.clear, - }); - const update: ChannelUpdate = { instanceId, value, runtimeIdentity, revision, lifetime }; - return [update, { revision, instances: nextInstances }] as const; - }); - yield* PubSub.publish(updates, event); + // Serialize state commit and PubSub publication so watchers always observe monotonic revisions. + yield* publishPermit.withPermits(1)( + Effect.uninterruptible( + Ref.modify(stateRef, (state) => { + const revision = state.revision + 1; + const existing = state.instances.get(instanceId); + const lifetime = existing?.lifetime ?? revision; + const nextEntries = new Map(existing?.entries); + nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision, lifetime }); + const nextInstances = new Map(state.instances); + nextInstances.set(instanceId, { + lifetime, + entries: nextEntries, + latestKey: runtimeIdentity, + hasLatest: true, + clear: existing?.clear, + }); + const update: ChannelUpdate = { + instanceId, + value, + runtimeIdentity, + revision, + lifetime, + }; + return [update, { revision, instances: nextInstances }] as const; + }).pipe( + Effect.flatMap((event) => PubSub.publish(updates, event)), + Effect.asVoid, + ), + ), + ); }); const get = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.get}`)(function* ( @@ -299,17 +313,22 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt return inst.hasLatest ? validEntry(inst.entries.get(inst.latestKey)) : Option.none(); }); - const watch = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.watch}`)(function* ( + const watch = ( instanceId: ProviderInstanceId, onUpdate: (value: T, meta: AcpRegistryLiveUpdateMeta) => Effect.Effect, - ) { - yield* Effect.scoped( + ) => + Effect.scoped( Effect.gen(function* () { - // Subscribe before reading to avoid missing publications. - const subscription = yield* PubSub.subscribe(updates); - const snapshot = yield* Ref.get(stateRef); + // Trace subscription setup once without keeping a long-lived parent span around callbacks. + const { subscription, snapshot } = yield* Effect.gen(function* () { + // Subscribe before reading to avoid missing publications. + const sub = yield* PubSub.subscribe(updates); + const snap = yield* Ref.get(stateRef); + return { subscription: sub, snapshot: snap }; + }).pipe(Effect.withSpan(`AcpRegistryRuntimeCoordinator.${names.watch}.subscribe`)); const snapshotRevision = snapshot.revision; const inst = snapshot.instances.get(instanceId); + const lastDeliveredByRuntime = new Map(); const metaFor = ( runtimeIdentity: string | undefined, revision: number, @@ -336,15 +355,21 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt ) .toSorted((left, right) => left.revision - right.revision); for (const entry of replayed) { + lastDeliveredByRuntime.set(entry.runtimeIdentity, entry.revision); yield* onUpdate( entry.value, metaFor(entry.runtimeIdentity, entry.revision, entry.lifetime), ); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter( - (update) => update.instanceId === instanceId && update.revision > snapshotRevision, - ), + Stream.filter((update) => { + if (update.instanceId !== instanceId) return false; + if (update.revision <= snapshotRevision) return false; + const lastDelivered = lastDeliveredByRuntime.get(update.runtimeIdentity) ?? 0; + if (update.revision <= lastDelivered) return false; + lastDeliveredByRuntime.set(update.runtimeIdentity, update.revision); + return true; + }), Stream.runForEach((update) => onUpdate( update.value, @@ -354,7 +379,6 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt ); }), ); - }); return { clear, publish, get, watch } as const; }, @@ -524,8 +548,11 @@ const make = Effect.gen(function* () { ) => Effect.scoped( Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(urlAuthActionUpdates); - const current = yield* getUrlAuthAction(instanceId); + const { subscription, current } = yield* Effect.gen(function* () { + const sub = yield* PubSub.subscribe(urlAuthActionUpdates); + const cur = yield* getUrlAuthAction(instanceId); + return { subscription: sub, current: cur }; + }).pipe(Effect.withSpan("AcpRegistryRuntimeCoordinator.watchUrlAuthAction.subscribe")); if (Option.isSome(current)) { yield* onUpdate(current.value); } diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 460915ee56749..c3d1859dd0f38 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -843,6 +843,34 @@ describe("AcpRegistrySupport", () => { path.dirname(first.spawn.command), ]); + // Rolling back to artifact A (in the primary receipted slot) ranks primary A ahead of the + // newer hashed replacement slot B on terminal PATH. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rolledBackToPrimary = yield* resolver.resolve(settings(), "/workspace"); + expect(rolledBackToPrimary.spawn.command).toBe(first.spawn.command); + const managedDirsAfterRollback = + yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + platform: "linux", + architecture: "x64", + }); + expect(managedDirsAfterRollback.slice(0, 2)).toEqual([ + path.dirname(first.spawn.command), + path.dirname(third.spawn.command), + ]); + // Changing only sha256 at the same archive URL & cmd must install into a new artifact slot. serveRehashedAtReplacement = true; currentAgent = makeAgent({ @@ -933,6 +961,11 @@ describe("AcpRegistrySupport", () => { let offline = true; let failSwappedDownload = false; let failV2Download = true; + let serveEmptyRegistry = false; + let checksumGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; let requests: Array = []; let currentAgent = { ...makeAgent({ @@ -1037,6 +1070,143 @@ describe("AcpRegistrySupport", () => { .resolve(settings(), "/workspace") .pipe(Effect.flip); expect(changedArtifactAfterRestart.reason).toBe("download_failed"); + // Superseded legacy primary slots are also excluded from managed terminal PATH directories. + expect( + yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir, + platform: "linux", + architecture: "x64", + }), + ).not.toContain(path.dirname(legacyBinary)); + + // 2b. A version bump (1.0.0 legacy A -> 2.0.0) followed by a rollback to 1.0.0 (archive B) + // still records legacy A's baseline during the bump so legacy A is never launched as B. + const versionBumpCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-legacy-bump-", + }); + const versionBumpToolsDir = path.join(versionBumpCacheDir, "tools"); + const bumpLegacyBinary = path.join( + versionBumpToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(bumpLegacyBinary), { recursive: true }); + yield* fileSystem.writeFileString(bumpLegacyBinary, "#!/bin/sh\necho legacy-bump\n"); + yield* fileSystem.chmod(bumpLegacyBinary, 0o755); + yield* fileSystem.makeDirectory(path.join(versionBumpCacheDir, "acp-registry"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(versionBumpCacheDir, "acp-registry", "registry.json"), + makeRegistry({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }), + ); + const bumpResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: versionBumpCacheDir, + toolsDir: versionBumpToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { "linux-x86_64": { archive: v2ArchiveUrl, cmd: "./bin/example-agent" } }, + }), + version: "2.0.0", + }; + yield* bumpResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + currentAgent = { + ...makeAgent({ + binary: { "linux-x86_64": { archive: swappedArchiveUrl, cmd: "./bin/example-agent" } }, + }), + version: "1.0.0", + }; + yield* bumpResolver.invalidateIndex(); + yield* bumpResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bumpRollbackError = yield* bumpResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(bumpRollbackError.reason).toBe("download_failed"); + + // 2c. If persisting legacy-baselines.json fails, registry.json must stay on artifact A so + // a restarted server never mistakes legacy A for artifact B. + const unwritableBaselineDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-fail-", + }); + const unwritableToolsDir = path.join(unwritableBaselineDir, "tools"); + const unwritableLegacyBin = path.join( + unwritableToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(unwritableLegacyBin), { recursive: true }); + yield* fileSystem.writeFileString( + unwritableLegacyBin, + "#!/bin/sh\necho legacy-unwritable\n", + ); + yield* fileSystem.chmod(unwritableLegacyBin, 0o755); + const unwritableRegistryPath = path.join( + unwritableBaselineDir, + "acp-registry", + "registry.json", + ); + yield* fileSystem.makeDirectory(path.dirname(unwritableRegistryPath), { recursive: true }); + const initialLegacyRegistryJson = makeRegistry({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }); + yield* fileSystem.writeFileString(unwritableRegistryPath, initialLegacyRegistryJson); + const missingDirErr = yield* fileSystem + .readFileString(path.join(unwritableBaselineDir, "missing-sentinel")) + .pipe(Effect.flip); + const failBaselineWriteFs: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => + filePath.includes("legacy-baselines.json") + ? Effect.fail(missingDirErr) + : fileSystem.writeFileString(filePath, data, options), + }; + const unwritableResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unwritableBaselineDir, + toolsDir: unwritableToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failBaselineWriteFs)); + yield* unwritableResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect( + (yield* unwritableResolver.resolve(settings(), "/workspace").pipe(Effect.flip)).reason, + ).toBe("download_failed"); + // Disk registry.json was NOT overwritten with B because baseline persistence failed. + expect(yield* fileSystem.readFileString(unwritableRegistryPath)).toBe( + initialLegacyRegistryJson, + ); + // After restart while offline, the catalog still reads A from disk (never B). + offline = true; + const restartedOfflineResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unwritableBaselineDir, + toolsDir: unwritableToolsDir, + registryUrl, + }); + const offlineAfterFailedBaseline = yield* restartedOfflineResolver.resolve( + settings(), + "/workspace", + ); + expect(offlineAfterFailedBaseline.spawn.command).toBe(unwritableLegacyBin); + offline = false; // 3. A single resolve() starting from a stale failing archive URL refreshes the index, // retries the updated same-version archive URL, and succeeds. @@ -1239,6 +1409,196 @@ describe("AcpRegistrySupport", () => { const rollbackFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); expect(rollbackFallback.fallback).toBe(true); expect(rollbackFallback.agent?.version).toBe("1.0.0"); + expect(rollbackFallback.failedTarget?.version).toBe("1.5.0"); + + // 7. SemVer 2.0.0 §11 prerelease ordering: non-numeric "1a" has higher precedence than + // numeric "2", so 2.1.0-1a must NOT be chosen as a fallback when 2.1.0-2 fails. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: v2ArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "2.1.0-1a", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* fallbackResolver.resolve(settings(), "/workspace")).agent?.version).toBe( + "2.1.0-1a", + ); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-2.1.0-2.bin", + cmd: "./bin/example-agent", + }, + }, + }), + version: "2.1.0-2", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const semverFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(semverFallback.fallback).toBe(true); + expect(semverFallback.agent?.version).toBe("2.0.0"); + + // 8. A corrupt tar archive (tar exits non-zero) triggers archive_invalid and falls back to + // the newest receipted version below 2.2.0 (2.1.0-1a), whereas a locally corrupted cached + // slot fails with install_failed. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/corrupt-2.2.0.tar.gz", + cmd: "./bin/example-agent", + }, + }, + }), + version: "2.2.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const corruptArchiveFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(corruptArchiveFallback.fallback).toBe(true); + expect(corruptArchiveFallback.agent?.version).toBe("2.1.0-1a"); + expect(corruptArchiveFallback.failedTarget?.version).toBe("2.2.0"); + + // Tampering with an already-installed cached executable must fail with install_failed + // instead of silently falling back to an older version. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* fileSystem.chmod(installedV2.spawn.command, 0o644); + const tamperedCacheError = yield* fallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(tamperedCacheError.reason).toBe("install_failed"); + yield* fileSystem.chmod(installedV2.spawn.command, 0o755); + + // 9. A concurrent agent removal published while a checksum_mismatch download is in flight + // is honored immediately instead of falling back to an older installed version. + const removalGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + checksumGate = removalGate; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + sha256: "0".repeat(64), + }, + }, + }), + version: "2.3.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvingChecksum = yield* fallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(removalGate.started); + serveEmptyRegistry = true; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + checksumGate = null; + yield* Deferred.succeed(removalGate.release, undefined); + const removedDuringChecksumError = yield* Fiber.join(resolvingChecksum); + expect(removedDuringChecksumError.reason).toBe("agent_not_found"); + serveEmptyRegistry = false; + + // 10. Stale-lock promotion interleaving never removes a concurrently published artifact slot. + const raceCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-lock-race-", + }); + const raceToolsDir = path.join(raceCacheDir, "tools"); + const raceBaseResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }; + yield* raceBaseResolver.resolve(settings(), "/workspace"); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: swappedArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }; + const renameBlocked = yield* Deferred.make(); + const releaseFirstRename = yield* Deferred.make(); + let firstRenameIntercepted = false; + let removedArtifactSlot = false; + const raceFs: FileSystem.FileSystem = { + ...fileSystem, + remove: (targetPath, options) => { + if (/linux-x86_64-[0-9a-f]{12}$/u.test(targetPath)) { + removedArtifactSlot = true; + } + return fileSystem.remove(targetPath, options); + }, + rename: (oldPath, newPath) => { + if (!firstRenameIntercepted && /linux-x86_64-[0-9a-f]{12}$/u.test(newPath)) { + firstRenameIntercepted = true; + return Deferred.succeed(renameBlocked, undefined).pipe( + Effect.andThen(Deferred.await(releaseFirstRename)), + Effect.andThen(fileSystem.rename(oldPath, newPath)), + ); + } + return fileSystem.rename(oldPath, newPath); + }, + }; + const raceInstaller1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, raceFs)); + const raceInstaller2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, raceFs)); + yield* raceInstaller1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* raceInstaller2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const install1Fiber = yield* raceInstaller1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(renameBlocked); + // Age the lock past INSTALL_LOCK_STALE_MS so installer 2 takes over and publishes artifactRoot. + const lockPath = path.join(raceToolsDir, "example-agent", "1.0.0", "linux-x86_64.lock"); + yield* fileSystem.utimes(lockPath, new Date(0), new Date(0)); + yield* TestClock.adjust("6 minutes"); + const installedBy2 = yield* raceInstaller2.resolve(settings(), "/workspace"); + yield* Deferred.succeed(releaseFirstRename, undefined); + const installedBy1 = yield* Fiber.join(install1Fiber); + expect(removedArtifactSlot).toBe(false); + expect(installedBy1.spawn.command).toBe(installedBy2.spawn.command); + expect(yield* fileSystem.readFileString(installedBy1.spawn.command)).toBe( + "#!/bin/sh\necho v1-fixed\n", + ); }).pipe( Effect.scoped, Effect.provide( @@ -1251,7 +1611,19 @@ describe("AcpRegistrySupport", () => { } if (request.url === registryUrl) { return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(currentAgent))), + HttpClientResponse.fromWeb( + request, + new Response( + serveEmptyRegistry + ? JSON.stringify({ version: "1.0.0", agents: [] }) + : makeRegistry(currentAgent), + ), + ), + ); + } + if (request.url === "https://example.test/corrupt-2.2.0.tar.gz") { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("not-a-valid-tar-archive")), ); } if (request.url === legacyArchiveUrl) { @@ -1263,7 +1635,16 @@ describe("AcpRegistrySupport", () => { return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v1Bytes))); } if (request.url === v2ArchiveUrl && !failV2Download) { - return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v2Bytes))); + const gate = checksumGate; + const respond = Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(v2Bytes)), + ); + return gate === null + ? respond + : Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); } return Effect.succeed( HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), @@ -1922,8 +2303,15 @@ describe("AcpRegistrySupport", () => { const packageSwapDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-launch-identity-", }); - const hostPlatform = HostProcess.Platform.defaultValue(); - const hostArchitecture = HostProcess.Architecture.defaultValue(); + const rawHostPlatform = HostProcess.Platform.defaultValue(); + const rawHostArchitecture = HostProcess.Architecture.defaultValue(); + const isSupportedHost = + (rawHostPlatform === "darwin" || + rawHostPlatform === "linux" || + rawHostPlatform === "win32") && + (rawHostArchitecture === "arm64" || rawHostArchitecture === "x64"); + const hostPlatform: NodeJS.Platform = isSupportedHost ? rawHostPlatform : "linux"; + const hostArchitecture: NodeJS.Architecture = isSupportedHost ? rawHostArchitecture : "x64"; const isWindowsHost = hostPlatform === "win32"; const hostBinaryOs = hostPlatform === "darwin" ? "darwin" : isWindowsHost ? "windows" : "linux"; diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index f72a325e98da5..730ac0311d5f4 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -68,6 +68,7 @@ const REGISTRY_REQUEST_TIMEOUT = "30 seconds"; // Searches reuse an index fetched this recently; prepare always fetches the latest. const REGISTRY_SEARCH_MAX_AGE_MS = 5 * 60 * 1_000; const ARCHIVE_REQUEST_TIMEOUT = "20 minutes"; +const ARCHIVE_EXTRACT_TIMEOUT = "5 minutes"; const PACKAGE_INSTALL_TIMEOUT = "20 minutes"; const PACKAGE_QUERY_TIMEOUT = "30 seconds"; @@ -414,6 +415,11 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged (agent) => [`${agent.id}\0${encodeURIComponent(agent.version)}`, agent] as const, ), ); + const legacyBaselinesResult = yield* readLegacyBaselinesFile( + fileSystem, + path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME), + ); + const legacyBaselines = legacyBaselinesResult.ok ? legacyBaselinesResult.baselines : undefined; for (const agent of (yield* listDirectories(installsDirectory)).toSorted()) { const versions = (yield* listDirectories(path.join(installsDirectory, agent))).toSorted( (left, right) => @@ -427,50 +433,79 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged .binary?.[candidateTarget]; const preferredCommandSegments = binaryTarget === undefined ? undefined : normalizeRegistryCommandPath(binaryTarget.cmd); - const preferredArtifactDir = - binaryTarget === undefined - ? undefined - : binaryArtifactDirName(candidateTarget, binaryTarget); + const targetKey = + binaryTarget === undefined ? undefined : binaryArtifactIdentityKey(binaryTarget); + const slotKey = legacyBaselineSlotKey(agent, version, candidateTarget); const matchingEntries = versionEntries.filter((entry) => isBinaryPlatformEntry(entry, candidateTarget), ); - const inspectedSlots = yield* Effect.forEach(matchingEntries, (entry) => + const inspectedRaw = yield* Effect.forEach(matchingEntries, (entry) => Effect.gen(function* () { const installRoot = path.join(versionRoot, entry); const rawReceipt = yield* fileSystem .readFileString(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) .pipe(Effect.option); const receipt = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); - const isPreferred = entry === preferredArtifactDir; - const isPrimary = entry === candidateTarget; - // Skip un-receipted artifact-scoped leftovers; they cannot be valid installs. - if (!isPreferred && Option.isNone(receipt) && !isPrimary) { - return Option.none<{ - readonly rank: number; - readonly mtimeMs: number; - readonly isPrimary: boolean; - readonly entry: string; - readonly directory: string; - }>(); - } - const receiptSegments = Option.isSome(receipt) - ? normalizeRegistryCommandPath(receipt.value.cmd) - : undefined; - const segments = isPreferred - ? (preferredCommandSegments ?? receiptSegments) - : (receiptSegments ?? (isPrimary ? preferredCommandSegments : undefined)); - const directory = - segments === undefined - ? installRoot - : path.join(installRoot, ...segments.slice(0, -1)); - const mtimeMs = yield* fileSystem.stat(installRoot).pipe( - Effect.map((info) => (Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0)), - Effect.orElseSucceed(() => 0), - ); - const rank = isPreferred ? 0 : Option.isSome(receipt) ? 1 : 2; - return Option.some({ rank, mtimeMs, isPrimary, entry, directory }); + return { entry, installRoot, receipt }; }), ); + const hasReceiptedSlot = inspectedRaw.some((slot) => Option.isSome(slot.receipt)); + const inspectedSlots = yield* Effect.forEach( + inspectedRaw, + ({ entry, installRoot, receipt }) => + Effect.gen(function* () { + const isPrimary = entry === candidateTarget; + const receiptMatchesTarget = + binaryTarget !== undefined && + Option.isSome(receipt) && + binaryArtifactReceiptMatches(receipt.value, binaryTarget); + // Skip un-receipted artifact-scoped leftovers; they cannot be valid installs. + if (Option.isNone(receipt) && !isPrimary) { + return Option.none<{ + readonly rank: number; + readonly mtimeMs: number; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + // Skip superseded legacy primary slots once a receipted slot exists or a baseline disagrees. + if (Option.isNone(receipt) && isPrimary) { + const baselineSuperseded = + targetKey !== undefined && + (legacyBaselines === undefined || + (legacyBaselines[slotKey] !== undefined && + legacyBaselines[slotKey] !== targetKey)); + if (hasReceiptedSlot || baselineSuperseded) { + return Option.none<{ + readonly rank: number; + readonly mtimeMs: number; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + } + const receiptSegments = Option.isSome(receipt) + ? normalizeRegistryCommandPath(receipt.value.cmd) + : undefined; + const segments = receiptMatchesTarget + ? (preferredCommandSegments ?? receiptSegments) + : (receiptSegments ?? (isPrimary ? preferredCommandSegments : undefined)); + const directory = + segments === undefined + ? installRoot + : path.join(installRoot, ...segments.slice(0, -1)); + const mtimeMs = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => + Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, + ), + Effect.orElseSucceed(() => 0), + ); + const rank = receiptMatchesTarget ? 0 : Option.isSome(receipt) ? 1 : 2; + return Option.some({ rank, mtimeMs, isPrimary, entry, directory }); + }), + ); const orderedSlots = inspectedSlots .filter(Option.isSome) .map((slot) => slot.value) @@ -542,12 +577,19 @@ export function resolveAcpRegistryDistribution(input: { return undefined; } +export interface AcpRegistryFailedTarget { + readonly version: string; + readonly launchIdentity: string; + readonly indexRevision: number; +} + export interface ResolvedAcpRegistryAgent { readonly agent?: AcpRegistryAgent; readonly distribution: AcpRegistryDistributionKind | "local"; readonly launchIdentity?: string; readonly indexRevision?: number; readonly fallback?: boolean; + readonly failedTarget?: AcpRegistryFailedTarget; readonly spawn: AcpSessionRuntime.AcpSpawnInput; } @@ -656,7 +698,7 @@ const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; -const BINARY_LEGACY_BASELINE_FILENAME = ".t3-legacy-baseline.json"; +const BINARY_LEGACY_BASELINES_FILENAME = "legacy-baselines.json"; const BINARY_ARTIFACT_SLOT_HASH_LENGTH = 12; const DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS = 60 * 1_000; @@ -673,13 +715,39 @@ const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( Schema.fromJsonString(AcpRegistryBinaryArtifactReceipt), ); -const AcpRegistryBinaryLegacyBaseline = Schema.Struct({ - artifactKey: Schema.String, -}); -const decodeBinaryLegacyBaseline = Schema.decodeUnknownOption( - Schema.fromJsonString(AcpRegistryBinaryLegacyBaseline), +const AcpRegistryLegacyBaselines = Schema.Record(Schema.String, Schema.String); +const decodeLegacyBaselines = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryLegacyBaselines), ); -const encodeBinaryLegacyBaseline = (artifactKey: string): string => JSON.stringify({ artifactKey }); + +type LegacyBaselinesReadResult = + | { readonly ok: true; readonly baselines: Readonly> } + | { readonly ok: false }; + +function legacyBaselineSlotKey( + agentId: string, + encodedVersion: string, + candidateTarget: AcpRegistryPlatformTarget, +): string { + return `${agentId}\0${encodedVersion}\0${candidateTarget}`; +} + +function readLegacyBaselinesFile( + fileSystem: FileSystem.FileSystem, + baselinesPath: string, +): Effect.Effect { + return fileSystem.readFileString(baselinesPath).pipe( + Effect.map((raw): LegacyBaselinesReadResult => { + const decoded = decodeLegacyBaselines(raw); + return Option.isSome(decoded) ? { ok: true, baselines: decoded.value } : { ok: false }; + }), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" ? { ok: true, baselines: {} } : { ok: false }, + ), + ), + ); +} function safeDecodeVersionDir(value: string): string { try { @@ -689,27 +757,62 @@ function safeDecodeVersionDir(value: string): string { } } +const NUMERIC_VERSION_IDENTIFIER = /^(?:0|[1-9]\d*)$/u; +const DIGITS_ONLY = /^\d+$/u; + +function compareNumericStrings(left: string, right: string): number { + const a = left.replace(/^0+(?=\d)/u, ""); + const b = right.replace(/^0+(?=\d)/u, ""); + if (a.length !== b.length) return a.length - b.length; + return compareText(a, b); +} + function compareRegistryVersions(left: string, right: string): number { const splitVersion = (raw: string) => { const stripped = raw.replace(/^v(?=\d)/iu, "").split("+", 1)[0] ?? raw; const hyphenIndex = stripped.indexOf("-"); const core = hyphenIndex === -1 ? stripped : stripped.slice(0, hyphenIndex); const prerelease = hyphenIndex === -1 ? undefined : stripped.slice(hyphenIndex + 1); - return { core: core.split("."), prerelease }; + return { + core: core.split("."), + prerelease: prerelease === undefined ? undefined : prerelease.split("."), + }; }; const a = splitVersion(left); const b = splitVersion(right); const maxLen = Math.max(a.core.length, b.core.length); for (let index = 0; index < maxLen; index += 1) { - const diff = (a.core[index] ?? "0").localeCompare(b.core[index] ?? "0", undefined, { - numeric: true, - }); + const aPart = a.core[index] ?? "0"; + const bPart = b.core[index] ?? "0"; + if (aPart === bPart) continue; + const diff = + DIGITS_ONLY.test(aPart) && DIGITS_ONLY.test(bPart) + ? compareNumericStrings(aPart, bPart) + : compareText(aPart, bPart); if (diff !== 0) return diff; } if (a.prerelease === undefined && b.prerelease === undefined) return 0; if (a.prerelease === undefined) return 1; if (b.prerelease === undefined) return -1; - return a.prerelease.localeCompare(b.prerelease, undefined, { numeric: true }); + // SemVer 2.0.0 §11.4: numeric identifiers compare numerically and have lower precedence than + // non-numeric identifiers, which compare lexically in ASCII order. + const minPre = Math.min(a.prerelease.length, b.prerelease.length); + for (let index = 0; index < minPre; index += 1) { + const aId = a.prerelease[index]!; + const bId = b.prerelease[index]!; + if (aId === bId) continue; + const aIsNum = NUMERIC_VERSION_IDENTIFIER.test(aId); + const bIsNum = NUMERIC_VERSION_IDENTIFIER.test(bId); + if (aIsNum && bIsNum) { + const diff = compareNumericStrings(aId, bId); + if (diff !== 0) return diff; + continue; + } + if (aIsNum) return -1; + if (bIsNum) return 1; + return compareText(aId, bId); + } + return a.prerelease.length - b.prerelease.length; } function binaryArtifactIdentityKey(target: typeof AcpRegistryBinaryTarget.Type): string { @@ -893,6 +996,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); const registryCachePath = path.join(registryDirectory, "registry.json"); + const legacyBaselinesPath = path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME); const installsDirectory = input.toolsDir; const agentInstallRoot = (agent: AcpRegistryAgent) => path.join(installsDirectory, agent.id, encodeURIComponent(agent.version)); @@ -941,7 +1045,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const preparedBinaryReservations = yield* Ref.make>(new Map()); // In-memory mirror of durable legacy baselines so disk write errors still keep a superseded // pre-receipt binary from matching a newly published artifact at the same version. - const legacyBaselineByInstallRoot = new Map(); + const legacyBaselineBySlotKey = new Map(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -1198,66 +1302,118 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return { registry, text: collected.text }; }); + const writeLegacyBaselinesAtomically = (baselines: Readonly>) => + random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${legacyBaselinesPath}.${process.pid}-${id}.tmp`; + return fileSystem + .makeDirectory(registryDirectory, { recursive: true }) + .pipe( + Effect.andThen(fileSystem.writeFileString(temporaryPath, JSON.stringify(baselines))), + Effect.andThen(fileSystem.rename(temporaryPath, legacyBaselinesPath)), + Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)), + ); + }), + ); + const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( inMemoryPrevious: AcpRegistryIndex | undefined, nextIndex: AcpRegistryIndex, ) { - if (platformTarget === undefined) return; + if (platformTarget === undefined) return true; const candidates = resolveAcpRegistryPlatformTargetCandidates(platformTarget); - const pendingLegacyInstalls: Array<{ + const listDirectories = (directory: string) => + fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): Array => [])); + const unreceiptedLegacySlots: Array<{ readonly agentId: string; - readonly version: string; + readonly encodedVersion: string; readonly candidateTarget: AcpRegistryPlatformTarget; - readonly nextTarget: typeof AcpRegistryBinaryTarget.Type; - readonly installRoot: string; - readonly baselinePath: string; + readonly slotKey: string; }> = []; - for (const nextAgent of nextIndex.agents) { - if (nextAgent.distribution.binary === undefined) continue; - for (const candidateTarget of candidates) { - const nextTarget = nextAgent.distribution.binary[candidateTarget]; - if (nextTarget === undefined) continue; - const installRoot = path.join(agentInstallRoot(nextAgent), candidateTarget); - const baselinePath = path.join(installRoot, BINARY_LEGACY_BASELINE_FILENAME); - if (legacyBaselineByInstallRoot.has(installRoot)) continue; - const installExists = yield* fileSystem - .exists(installRoot) - .pipe(Effect.orElseSucceed(() => false)); - if (!installExists) continue; - const hasReceipt = yield* fileSystem - .exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) - .pipe(Effect.orElseSucceed(() => false)); - if (hasReceipt) continue; - const hasBaseline = yield* fileSystem - .exists(baselinePath) - .pipe(Effect.orElseSucceed(() => false)); - if (hasBaseline) continue; - pendingLegacyInstalls.push({ - agentId: nextAgent.id, - version: nextAgent.version, - candidateTarget, - nextTarget, - installRoot, - baselinePath, - }); + for (const agentId of yield* listDirectories(installsDirectory)) { + const agentRoot = path.join(installsDirectory, agentId); + for (const encodedVersion of yield* listDirectories(agentRoot)) { + const versionRoot = path.join(agentRoot, encodedVersion); + for (const candidateTarget of candidates) { + const installRoot = path.join(versionRoot, candidateTarget); + const installExists = yield* fileSystem + .exists(installRoot) + .pipe(Effect.orElseSucceed(() => false)); + if (!installExists) continue; + const hasReceipt = yield* fileSystem + .exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.orElseSucceed(() => false)); + if (hasReceipt) continue; + unreceiptedLegacySlots.push({ + agentId, + encodedVersion, + candidateTarget, + slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), + }); + } } } - if (pendingLegacyInstalls.length === 0) return; + if (unreceiptedLegacySlots.length === 0) return true; + const existingDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (!existingDisk.ok) return false; + const unpersistedSlots = unreceiptedLegacySlots.filter((slot) => { + const existingBaseline = existingDisk.baselines[slot.slotKey]; + if (existingBaseline !== undefined) { + legacyBaselineBySlotKey.set(slot.slotKey, existingBaseline); + return false; + } + return true; + }); + if (unpersistedSlots.length === 0) return true; + const previousIndex = inMemoryPrevious ?? Option.getOrUndefined(yield* readCachedRegistry); - if (previousIndex === undefined) return; - const previousById = new Map(previousIndex.agents.map((agent) => [agent.id, agent] as const)); - for (const pending of pendingLegacyInstalls) { - const previousAgent = previousById.get(pending.agentId); - if (previousAgent === undefined || previousAgent.version !== pending.version) continue; - const previousTarget = previousAgent.distribution.binary?.[pending.candidateTarget]; + const previousById = new Map( + (previousIndex?.agents ?? []).map((agent) => [agent.id, agent] as const), + ); + const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); + const newBaselines: Record = {}; + let hasUpdates = false; + for (const slot of unpersistedSlots) { + const existingInMemory = legacyBaselineBySlotKey.get(slot.slotKey); + if (existingInMemory !== undefined) { + newBaselines[slot.slotKey] = existingInMemory; + hasUpdates = true; + continue; + } + const previousAgent = previousById.get(slot.agentId); + if ( + previousAgent === undefined || + encodeURIComponent(previousAgent.version) !== slot.encodedVersion + ) { + continue; + } + const previousTarget = previousAgent.distribution.binary?.[slot.candidateTarget]; if (previousTarget === undefined) continue; const previousKey = binaryArtifactIdentityKey(previousTarget); - if (binaryArtifactIdentityKey(pending.nextTarget) === previousKey) continue; - legacyBaselineByInstallRoot.set(pending.installRoot, previousKey); - yield* fileSystem - .writeFileString(pending.baselinePath, encodeBinaryLegacyBaseline(previousKey)) - .pipe(Effect.ignore); + const nextAgent = nextById.get(slot.agentId); + const nextTarget = + nextAgent !== undefined && encodeURIComponent(nextAgent.version) === slot.encodedVersion + ? nextAgent.distribution.binary?.[slot.candidateTarget] + : undefined; + // Record the legacy artifact whenever the slot's artifact changes, version bumps, or disappears + // so a later rollback or repackage at the same version never mistakes the legacy install for it. + if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { + continue; + } + legacyBaselineBySlotKey.set(slot.slotKey, previousKey); + newBaselines[slot.slotKey] = previousKey; + hasUpdates = true; } + if (!hasUpdates) return true; + const mergedBaselines = { ...existingDisk.baselines, ...newBaselines }; + return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( + Effect.as(true), + Effect.catch(() => + Effect.logDebug( + "Could not persist ACP Registry legacy baselines; keeping existing disk registry cache.", + ).pipe(Effect.as(false)), + ), + ); }); const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { @@ -1307,7 +1463,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const result = yield* fetchRegistry().pipe( Effect.flatMap(({ registry, text }) => recordLegacyBaselines(current.index, registry).pipe( - Effect.andThen(writeRegistryCache(text)), + Effect.flatMap((baselinesPersisted) => + baselinesPersisted ? writeRegistryCache(text) : Effect.void, + ), Effect.as({ index: registry, refreshed: true as const }), ), ), @@ -1451,6 +1609,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly cwd?: string; readonly env?: NodeJS.ProcessEnv; readonly timeout?: Duration.Input; + readonly nonZeroExitReason?: AcpRegistryErrorReason; readonly truncatedOutputReason?: AcpRegistryErrorReason; readonly maxStdoutBytes?: number; } = {}, @@ -1488,7 +1647,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); if (Number(exitCode) !== 0) { return yield* new AcpRegistryError({ - reason: "install_failed", + reason: options.nonZeroExitReason ?? "install_failed", detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.trim()}`, }); } @@ -1930,6 +2089,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct installRoot, artifactRoot, platformTarget: matchedPlatformTarget, + slotKey: legacyBaselineSlotKey( + agent.id, + encodeURIComponent(agent.version), + matchedPlatformTarget, + ), executablePath: path.join(installRoot, ...commandSegments), artifactExecutablePath: path.join(artifactRoot, ...commandSegments), }; @@ -1992,17 +2156,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } } const currentKey = binaryArtifactIdentityKey(target); - const memoryBaseline = legacyBaselineByInstallRoot.get(paths.installRoot); + const memoryBaseline = legacyBaselineBySlotKey.get(paths.slotKey); if (memoryBaseline !== undefined) { return memoryBaseline === currentKey; } - const baselinePath = path.join(paths.installRoot, BINARY_LEGACY_BASELINE_FILENAME); - if (!(yield* fileSystem.exists(baselinePath).pipe(Effect.orElseSucceed(() => false)))) { + const diskResult = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (!diskResult.ok) { + return false; + } + const diskBaseline = diskResult.baselines[paths.slotKey]; + if (diskBaseline === undefined) { return true; } - const rawBaseline = yield* fileSystem.readFileString(baselinePath).pipe(Effect.option); - const decoded = Option.flatMap(rawBaseline, decodeBinaryLegacyBaseline); - return Option.isSome(decoded) && decoded.value.artifactKey === currentKey; + legacyBaselineBySlotKey.set(paths.slotKey, diskBaseline); + return diskBaseline === currentKey; }, ); @@ -2051,21 +2218,22 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const { commandSegments, installRoot, artifactRoot } = paths; - const validateSlot = (slot: { readonly root: string; readonly executablePath: string }) => + const validateCachedSlot = (slot: { readonly root: string; readonly executablePath: string }) => assertExecutableInRoot(slot.root, slot.executablePath).pipe( - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "install_failed", - detail: `Could not validate cached ACP Registry agent ${agent.id}.`, - cause, - }), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "install_failed", + detail: isAcpRegistryError(cause) + ? cause.detail + : `Could not validate cached ACP Registry agent ${agent.id}.`, + cause, + }), ), ); const cachedSlot = yield* findMatchingBinarySlot(paths, target); if (Option.isSome(cachedSlot)) { - return yield* validateSlot(cachedSlot.value); + return yield* validateCachedSlot(cachedSlot.value); } yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe( @@ -2094,10 +2262,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return yield* Effect.gen(function* () { const lockedSlot = yield* findMatchingBinarySlot(paths, target); if (Option.isSome(lockedSlot)) { - return yield* assertExecutableInRoot( - lockedSlot.value.root, - lockedSlot.value.executablePath, - ); + return yield* validateCachedSlot(lockedSlot.value); } const primaryExists = yield* fileSystem .exists(installRoot) @@ -2202,7 +2367,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct : platform === "win32" ? ["-tf", archivePath] : undefined; - const listingOptions = { maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES }; + const listingOptions = { + maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES, + timeout: ARCHIVE_EXTRACT_TIMEOUT, + nonZeroExitReason: "archive_invalid", + } as const; + const extractOptions = { + timeout: ARCHIVE_EXTRACT_TIMEOUT, + nonZeroExitReason: "archive_invalid", + } as const; const entries = listArgs === undefined ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) @@ -2214,10 +2387,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } if (kind === "zip" && platform !== "win32") { - yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]); + yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot], extractOptions); } else { const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; - yield* runCommand(tarCommand, [extractFlag, archivePath, "-C", extractionRoot]); + yield* runCommand( + tarCommand, + [extractFlag, archivePath, "-C", extractionRoot], + extractOptions, + ); } } @@ -2234,7 +2411,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct encodeBinaryArtifactReceipt(agent, target), ); // Recheck right before promotion in case a stale-lock takeover let another installer publish - // a valid receipt-matching slot while this staging download was in flight. + // a valid receipt-matching slot while this staging download was in flight. Never remove an + // existing destinationRoot before rename so a concurrent publisher's directory cannot be deleted. const concurrentSlot = yield* findMatchingBinarySlot(paths, target); if (Option.isSome(concurrentSlot)) { const validated = yield* assertExecutableInRoot( @@ -2245,10 +2423,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return validated.value; } } - if (destinationRoot === artifactRoot) { - // Only remove an un-receipted or invalid leftover at the content-addressed slot. - yield* fileSystem.remove(destinationRoot, { recursive: true, force: true }); - } const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), Effect.catch((renameError) => @@ -2556,6 +2730,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly effectiveEnvironment: NodeJS.ProcessEnv; readonly indexRevision?: number; readonly fallback?: boolean; + readonly failedTarget?: AcpRegistryFailedTarget; }) { const baseSpawnEnvironment = { ...input.effectiveEnvironment, @@ -2579,6 +2754,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ...(input.indexRevision === undefined ? {} : { indexRevision: input.indexRevision }), ...(input.fallback ? { fallback: true } : {}), + ...(input.failedTarget === undefined ? {} : { failedTarget: input.failedTarget }), spawn: { command: input.command, args: input.distribution.args, @@ -2596,6 +2772,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct cwd: string, environment: NodeJS.ProcessEnv | undefined, registry: AcpRegistryIndex, + indexRevision: number, ) { if (settings.commandPath.trim().length > 0 || platformTarget === undefined) { return Option.none(); @@ -2610,6 +2787,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (distribution === undefined || distribution.kind !== "binary") { return Option.none(); } + const failedTarget: AcpRegistryFailedTarget = { + version: agent.version, + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + }; const effectiveEnvironment = environment ?? hostEnvironment; return yield* withInstallPermit(agent.id)( Effect.gen(function* () { @@ -2702,6 +2884,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct cwd, effectiveEnvironment, fallback: true, + failedTarget, }); return Option.some(resolved); } @@ -2809,7 +2992,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (error) => canFallbackOnError(error.reason), (error) => Effect.gen(function* () { + const agentId = settings.agentId.trim(); + const artifactSignatureIn = (index: AcpRegistryIndex) => { + const agent = index.agents.find((candidate) => candidate.id === agentId); + if (agent === undefined) return undefined; + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined) return agent.version; + if (distribution.kind === "binary" && distribution.binaryTarget !== undefined) { + return `${agent.version}\0${binaryArtifactIdentityKey(distribution.binaryTarget)}`; + } + return registryLaunchIdentity({ version: agent.version, distribution }); + }; let activeRegistry = registry; + let activeRevision = indexRevision; let activeError = error; if (error.reason === "download_failed") { const refreshed = yield* Effect.result( @@ -2817,22 +3016,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); if (Result.isSuccess(refreshed)) { const { index: latest, indexRevision: latestRevision } = refreshed.success; - const agentId = settings.agentId.trim(); - const artifactSignatureIn = (index: AcpRegistryIndex) => { - const agent = index.agents.find((candidate) => candidate.id === agentId); - if (agent === undefined) return undefined; - const distribution = resolveAcpRegistryDistribution({ - agent, - preference: settings.distribution, - platformTarget, - }); - if (distribution === undefined) return agent.version; - if (distribution.kind === "binary" && distribution.binaryTarget !== undefined) { - return `${agent.version}\0${binaryArtifactIdentityKey(distribution.binaryTarget)}`; - } - return registryLaunchIdentity({ version: agent.version, distribution }); - }; - if (artifactSignatureIn(latest) !== artifactSignatureIn(registry)) { + if (artifactSignatureIn(latest) !== artifactSignatureIn(activeRegistry)) { const retried = yield* Effect.result( resolveWithRegistry(settings, cwd, environment, latest, latestRevision), ); @@ -2841,15 +3025,42 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return yield* retried.failure; } activeRegistry = latest; + activeRevision = latestRevision; activeError = retried.failure; } } } + // Check the latest published index before falling back so concurrent removals, + // incompatibilities, or fixes are honored even on checksum/archive failures. + const latestState = yield* Ref.get(registryState); + if ( + latestState.index !== undefined && + latestState.indexRevision > activeRevision && + artifactSignatureIn(latestState.index) !== artifactSignatureIn(activeRegistry) + ) { + const retried = yield* Effect.result( + resolveWithRegistry( + settings, + cwd, + environment, + latestState.index, + latestState.indexRevision, + ), + ); + if (Result.isSuccess(retried)) return retried.success; + if (!canFallbackOnError(retried.failure.reason)) { + return yield* retried.failure; + } + activeRegistry = latestState.index; + activeRevision = latestState.indexRevision; + activeError = retried.failure; + } const fallback = yield* resolveFallbackInstalledBinary( settings, cwd, environment, activeRegistry, + activeRevision, ); if (Option.isSome(fallback)) return fallback.value; return yield* activeError; @@ -2938,6 +3149,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ), ); + if (removed) { + for (const key of legacyBaselineBySlotKey.keys()) { + if (key.startsWith(`${safeAgentId}\0`)) { + legacyBaselineBySlotKey.delete(key); + } + } + } return { agentId: safeAgentId, removed }; }), ), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index f87cb31d99d82..3b921e7475937 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1864,12 +1864,43 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Fiber.interrupt(backoffCollector); expect(probeResolveAttempts).toBe(resolvesBeforeBackoffRefresh); expect(backoffSnapshots.every((snapshot) => snapshot.version === "3.0.0")).toBe(true); + expect( + backoffSnapshots.every((snapshot) => snapshot.message === fallbackSnapshot.message), + ).toBe(true); expect( backoffSnapshots.every((snapshot) => snapshot.slashCommands.some((command) => command.name === "v3-live-cmd"), ), ).toBe(true); + // Live configuration updates during fallback must also preserve the fallback warning message. + const v3LiveConfigDuringFallback = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => + model.capabilities?.optionDescriptors.some((opt) => opt.id === "fallback-effort"), + ), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([ + { + id: "fallback-effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + ]), + ); + const liveFallbackSnapshot = Option.getOrThrow( + yield* Fiber.join(v3LiveConfigDuringFallback), + ); + expect(liveFallbackSnapshot.message).toBe(fallbackSnapshot.message); + // Once backoff expires, recovering without invalidating the cached 4.0.0 index still upgrades // because fallback did not acknowledge the 4.0.0 revision. failArchiveDownload = false; @@ -1886,12 +1917,98 @@ describe("AcpRegistryDriver registry recovery", () => { expect(v4Snapshot.message).toBeUndefined(); expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(true); - // A freshly created instance on a cached failing 5.0.0 index falls back to 4.0.0 in a single - // probe without double-probing when refreshIndex does not advance the revision. + // A 1-model agent (30s provisional cache TTL) still respects the 60s fallback backoff at +31s, + // and invalidateCaches clears activeFallback so the next refresh retries immediately. remoteVersion = "5.0.0"; failArchiveDownload = true; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const singleModelInstanceId = ProviderInstanceId.make("acpRegistry_single_model_backoff"); + const singleModelFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(singleModelFallbackDone, Exit.void); + } + }; + const singleModelInstance = yield* AcpRegistryDriver.create({ + instanceId: singleModelInstanceId, + displayName: "Single Model Backoff", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(singleModelFallbackDone); + onEnrichmentEnd = null; + const soloFallbackSnapshot = yield* singleModelInstance.snapshot.getSnapshot; + expect(soloFallbackSnapshot.version).toBe("4.0.0"); + expect(soloFallbackSnapshot.message).toContain("5.0.0"); + + // Narrow the cached fallback entry to a single explicit model (30s provisional TTL). + const soloModelApplied = yield* singleModelInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "solo-v4-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + singleModelInstanceId, + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "solo-v4-model", + options: [{ value: "solo-v4-model", name: "Solo V4" }], + }, + ]), + ); + const soloAppliedSnapshot = Option.getOrThrow(yield* Fiber.join(soloModelApplied)); + expect(soloAppliedSnapshot.models.map((model) => model.slug)).toEqual(["solo-v4-model"]); + expect(soloAppliedSnapshot.message).toBe(soloFallbackSnapshot.message); + + const resolvesBeforeSolo31s = probeResolveAttempts; + const solo31sDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(solo31sDone, Exit.void); + } + }; + yield* TestClock.adjust("31 seconds"); + yield* singleModelInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(solo31sDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeSolo31s); + const soloAfter31s = yield* singleModelInstance.snapshot.getSnapshot; + expect(soloAfter31s.message).toBe(soloFallbackSnapshot.message); + expect(soloAfter31s.models.map((model) => model.slug)).toEqual(["solo-v4-model"]); + + // Calling invalidateCaches clears activeFallback and retries immediately even inside 60s. + yield* singleModelInstance.invalidateCaches ?? Effect.void; + const soloAfterInvalidateDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(soloAfterInvalidateDone, Exit.void); + } + }; + yield* singleModelInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(soloAfterInvalidateDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeSolo31s + 1); + + // When inspect() sees cached 5.0.0 while resolve() refreshes to failing 6.0.0 and falls back + // to 4.0.0, activeFallback records 6.0.0 (from resolved.failedTarget), stays in backoff for + // 6.0.0, and does NOT retire never-installed 6.0.0 so external 6.0.0 live state reconciles. + remoteVersion = "6.0.0"; + yield* realCatalog.invalidateIndex(); const resolvesBeforeFreshFallback = probeResolveAttempts; const freshFallbackDone = yield* Deferred.make(); onEnrichmentEnd = (exit) => { @@ -1899,8 +2016,9 @@ describe("AcpRegistryDriver registry recovery", () => { Deferred.doneUnsafe(freshFallbackDone, Exit.void); } }; + const freshInstanceId = ProviderInstanceId.make("acpRegistry_fallback_single_probe"); const freshInstance = yield* AcpRegistryDriver.create({ - instanceId: ProviderInstanceId.make("acpRegistry_fallback_single_probe"), + instanceId: freshInstanceId, displayName: "Fallback Single Probe", enabled: true, environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], @@ -1911,8 +2029,34 @@ describe("AcpRegistryDriver registry recovery", () => { ); yield* Deferred.await(freshFallbackDone); onEnrichmentEnd = null; - expect((yield* freshInstance.snapshot.getSnapshot).version).toBe("4.0.0"); + const freshFallbackSnapshot = yield* freshInstance.snapshot.getSnapshot; + expect(freshFallbackSnapshot.version).toBe("4.0.0"); + expect(freshFallbackSnapshot.message).toContain("6.0.0"); expect(probeResolveAttempts).toBe(resolvesBeforeFreshFallback + 1); + + // External 6.0.0 live state clears activeFallback and reconciles freshInstance to 6.0.0. + failArchiveDownload = false; + const v6Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v6Inspection.status).toBe("ready"); + const v6Identity = v6Inspection.status === "ready" ? v6Inspection.launchIdentity! : ""; + const freshReconciledToV6 = yield* freshInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "6.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v6-external-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + freshInstanceId, + { slashCommands: [{ name: "v6-external-cmd" }], skills: [] }, + v6Identity, + ); + const reconciledV6Snapshot = Option.getOrThrow(yield* Fiber.join(freshReconciledToV6)); + expect(reconciledV6Snapshot.version).toBe("6.0.0"); + expect(reconciledV6Snapshot.message).toBeUndefined(); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); @@ -2755,6 +2899,21 @@ describe("AcpRegistryDriver registry recovery", () => { // 0. Same-runtime live config update arriving while a v1 probe is in flight discards the // older v1 probe so stale probe models cannot overwrite newer live configuration. + // Publish an option-only update (models: []) so without the generation guard the stale + // probe's ["v1-stale-probe-a", "v1-stale-probe-b"] catalog would overwrite ["model-a", "model-b"]. + let onEnrichmentSpanEnd: ((exit: Exit.Exit) => void) | null = null; + const enrichmentTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnrichmentSpanEnd?.(exit); + }; + return inner; + }, + }; yield* instance.invalidateCaches ?? Effect.void; yield* fileSystem.writeFileString( modelsPath, @@ -2775,46 +2934,53 @@ describe("AcpRegistryDriver registry recovery", () => { ), Effect.forkScoped({ startImmediately: true }), ); - yield* instance.snapshot.refresh; + const v1StaleEnrichmentDone = yield* Deferred.make(); + onEnrichmentSpanEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(v1StaleEnrichmentDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); yield* Deferred.await(v1ProbeGate.started); const v1NewerLiveApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => - snapshot.models.some((model) => model.slug === "v1-newer-live-a"), + snapshot.models.some((model) => + model.capabilities?.optionDescriptors.some((opt) => opt.id === "v1-live-effort"), + ), ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); yield* coordinator.publishLiveConfiguration( identity.instanceId, - normalizeAcpRegistryLiveConfiguration([], undefined, { - currentModelId: "v1-newer-live-a", - availableModels: [ - { modelId: "v1-newer-live-a", name: "v1-newer-live-a" }, - { modelId: "v1-newer-live-b", name: "v1-newer-live-b" }, - ], - }), + normalizeAcpRegistryLiveConfiguration([ + { + id: "v1-live-effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + ]), v1Identity, ); expect(Option.isSome(yield* Fiber.join(v1NewerLiveApplied))).toBe(true); yield* Deferred.succeed(v1ProbeGate.release, undefined); - const v1SettledAfterRelease = yield* instance.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => - snapshot.slashCommands.some((command) => command.name === "v1-after-superseded-probe"), - ), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ); - yield* coordinator.publishAvailableCommands( - identity.instanceId, - { slashCommands: [{ name: "v1-after-superseded-probe" }], skills: [] }, - v1Identity, - ); - const v1AfterSuperseded = Option.getOrThrow(yield* Fiber.join(v1SettledAfterRelease)); + yield* Deferred.await(v1StaleEnrichmentDone); + onEnrichmentSpanEnd = null; yield* Fiber.interrupt(v1ProbeCollector); - expect(v1AfterSuperseded.models.map((model) => model.slug)).toEqual([ - "v1-newer-live-a", - "v1-newer-live-b", - ]); + const v1AfterSuperseded = yield* instance.snapshot.getSnapshot; + // Without isProbeStillCurrent, the released probe would overwrite ["default"] with + // ["v1-stale-probe-a", "v1-stale-probe-b"] because the live update sent models: []. + expect(v1AfterSuperseded.models.map((model) => model.slug)).toEqual(["default"]); + expect( + v1AfterSuperseded.models.some((model) => + model.capabilities?.optionDescriptors.some((opt) => opt.id === "v1-live-effort"), + ), + ).toBe(true); expect( v1ProbeSnapshots.every( (snapshot) => !snapshot.models.some((model) => model.slug === "v1-stale-probe-a"), @@ -3012,7 +3178,18 @@ describe("AcpRegistryDriver registry recovery", () => { v2Identity, ); const observedAfterRace = yield* Fiber.join(liveRaceSnapshots); - expect(inspectCalls).toBe(inspectsBeforeRetiredV1); + // Trigger a subsequent unmatched identity inspect on driverScope to drain any concurrently + // forked fibers from retired v1 updates: exactly 1 inspect (for the sentinel) must run. + const retiredDrainDone = yield* Deferred.make(); + onInspectCallback = () => Deferred.succeed(retiredDrainDone, undefined).pipe(Effect.asVoid); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "sentinel-after-retired" }], skills: [] }, + "retired-drain-sentinel", + ); + yield* Deferred.await(retiredDrainDone); + onInspectCallback = null; + expect(inspectCalls).toBe(inspectsBeforeRetiredV1 + 1); expect( observedAfterRace.every( (snapshot) => @@ -3101,7 +3278,8 @@ describe("AcpRegistryDriver registry recovery", () => { expect(inspectCalls).toBe(inspectsBeforeUnmatched + 1); // 6. A failed upgrade probe (4.0.0 fails before resolving/starting) must NOT report 4.0.0 as - // installed, wipe v3 coordinator state, or reject subsequent v3 live updates. + // installed, drop v3's discovered models, wipe v3 coordinator state, or reject v3 live updates— + // even across repeated refreshes while 4.0.0 remains broken. remoteVersion = "4.0.0"; failProbeSpawn = true; yield* realCatalog.invalidateIndex(); @@ -3113,6 +3291,10 @@ describe("AcpRegistryDriver registry recovery", () => { yield* instance.snapshot.refresh; const warningSnapshot = Option.getOrThrow(yield* Fiber.join(failedUpgradeWarning)); expect(warningSnapshot.version).toBe("3.0.0"); + expect(warningSnapshot.models.map((model) => model.slug)).toEqual([ + "v3-model-a", + "v3-model-b", + ]); expect(warningSnapshot.slashCommands).toEqual([{ name: "v3-still-active" }]); expect( yield* coordinator.getAvailableCommands(identity.instanceId, { @@ -3133,7 +3315,59 @@ describe("AcpRegistryDriver registry recovery", () => { v3Identity, ); expect(Option.isSome(yield* Fiber.join(v3AfterFailedUpgrade))).toBe(true); + + // A second refresh while 4.0.0 is still failing must stay on 3.0.0 without flickering to + // 4.0.0 and must preserve v3's discovered models and live commands. + const secondFailedRefreshSnapshots: Array = []; + const secondFailedCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + secondFailedRefreshSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const secondFailedDone = yield* Deferred.make(); + onEnrichmentSpanEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(secondFailedDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(secondFailedDone); + onEnrichmentSpanEnd = null; + yield* Fiber.interrupt(secondFailedCollector); + expect(secondFailedRefreshSnapshots.every((snapshot) => snapshot.version === "3.0.0")).toBe( + true, + ); + const afterSecondFailed = yield* instance.snapshot.getSnapshot; + expect(afterSecondFailed.version).toBe("3.0.0"); + expect(afterSecondFailed.status).toBe("warning"); + expect(afterSecondFailed.models.map((model) => model.slug)).toEqual([ + "v3-model-a", + "v3-model-b", + ]); + expect(afterSecondFailed.slashCommands).toEqual([{ name: "v3-after-failed-v4" }]); + + // Once 4.0.0 recovers, the next refresh cleanly upgrades and clears the warning. failProbeSpawn = false; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v4-model-a", "v4-model-b"])); + const recoveredToV4 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const v4Recovered = Option.getOrThrow(yield* Fiber.join(recoveredToV4)); + expect(v4Recovered.models.map((model) => model.slug)).toEqual(["v4-model-a", "v4-model-b"]); + expect(v4Recovered.message).toBeUndefined(); // 7. Disposing a driver instance removes its coordinator state and marks earlier metadata stale. const disposedInstanceId = ProviderInstanceId.make("acpRegistry_disposed_cleanup"); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index f045a328ec368..58bbd9fa68bb4 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -73,6 +73,7 @@ const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000; const PROBE_PROVISIONAL_TTL_MS = 30 * 1_000; const REGISTRY_INDEX_MAX_AGE_MS = 15 * 60 * 1_000; const REGISTRY_FAILURE_BACKOFF_MS = 60 * 1_000; +const FALLBACK_RETRY_BACKOFF_MS = 60 * 1_000; function acpRegistryProbeTtlMs(provider: ServerProvider): number { const discoveredModels = provider.models.filter((model) => !model.isCustom); @@ -584,18 +585,28 @@ interface CheckedAcpRegistryReadiness { readonly launchIdentity: string | null; readonly indexRevision: number | null; readonly fallback?: boolean; + readonly fallbackTargetIndexRevision?: number | null; + readonly retryFailedUpgrade?: boolean; readonly probeFailed?: boolean; } interface ActiveFallbackState { readonly targetLaunchIdentity: string | null; readonly targetVersion: string | null; + readonly targetIndexRevision: number | null; readonly fallbackVersion: string | null; readonly fallbackLaunchIdentity: string | null; readonly failedAtMs: number; readonly message: string; } +interface FailedUpgradeTargetState { + readonly targetLaunchIdentity: string | null; + readonly status: ServerProvider["status"]; + readonly auth: ServerProvider["auth"]; + readonly message: string | undefined; +} + function runtimeIdentityFor( provider: Pick, launchIdentity: string | null, @@ -643,6 +654,8 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( readonly fallback?: boolean; readonly fallbackTargetLaunchIdentity?: string | null; readonly fallbackTargetVersion?: string | null; + readonly fallbackTargetIndexRevision?: number | null; + readonly failedTargetLaunchIdentity?: string | null; readonly probeFailed?: boolean; }, never, @@ -707,6 +720,7 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( launchIdentity: null, indexRevision: inspectedIndexRevision, cacheable: false, + failedTargetLaunchIdentity: inspected.success.launchIdentity ?? null, probeFailed: true, }; } @@ -770,8 +784,11 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( ...(resolved.fallback ? { fallback: true, - fallbackTargetLaunchIdentity: inspected.success.launchIdentity ?? null, - fallbackTargetVersion: inspected.success.version, + fallbackTargetLaunchIdentity: + resolved.failedTarget?.launchIdentity ?? inspected.success.launchIdentity ?? null, + fallbackTargetVersion: resolved.failedTarget?.version ?? inspected.success.version, + fallbackTargetIndexRevision: + resolved.failedTarget?.indexRevision ?? inspectedIndexRevision, } : {}), }; @@ -951,6 +968,11 @@ export const AcpRegistryDriver: ProviderDriver(null); + const lastSuccessfulRuntime = yield* Ref.make<{ + readonly identity: string; + readonly provider: ServerProvider; + } | null>(null); + const failedUpgradeTarget = yield* Ref.make(null); const clearLiveState = ( options?: AcpRegistryRuntimeCoordinator.AcpRegistryClearLiveStateOptions, ) => @@ -964,6 +986,13 @@ export const AcpRegistryDriver: ProviderDriver { + Effect.map(({ version, fallbackState, failedUpgrade, lastRuntime, activeIdentity }) => { const withLocalVersion = snapshot.installed && snapshot.version === null && version !== null ? { ...snapshot, version } @@ -1072,15 +1104,65 @@ export const AcpRegistryDriver: ProviderDriver { - const nextIdentity = snapshot.installed - ? runtimeIdentityFor(snapshot, launchIdentity) - : null; - return Ref.modify(activeRuntimeIdentity, (previousIdentity) => { - if ( - options?.seedActiveRuntimeIdentity === true && - snapshot.installed && - previousIdentity === null && - nextIdentity !== null - ) { - return [nextIdentity, nextIdentity] as const; - } - return [previousIdentity, previousIdentity] as const; - }).pipe( - Effect.flatMap((previousIdentity) => { - const runtimeChanged = - previousIdentity !== null && - nextIdentity !== null && - previousIdentity !== nextIdentity; - return withLiveRuntimeState(snapshot, { - applySessionLiveState: options?.applySessionLiveState ?? true, - sessionRuntimeIdentity: nextIdentity, - requireMatchingRuntimeIdentity: runtimeChanged, - useLearnedModels: !runtimeChanged, - persistLearnedModels: !runtimeChanged, - }).pipe( - Effect.map(({ provider }) => ({ - snapshot: provider, - launchIdentity, - indexRevision, - ...(fallback ? { fallback: true } : {}), - })), - ); - }), - ); - }), + Effect.flatMap( + ({ + snapshot, + launchIdentity, + indexRevision, + fallback, + fallbackTargetIndexRevision, + retryFailedUpgrade, + preserveStatus, + preserveMessage, + }) => { + const nextIdentity = snapshot.installed + ? runtimeIdentityFor(snapshot, launchIdentity) + : null; + return Ref.modify(activeRuntimeIdentity, (previousIdentity) => { + if ( + options?.seedActiveRuntimeIdentity === true && + snapshot.installed && + previousIdentity === null && + nextIdentity !== null + ) { + return [nextIdentity, nextIdentity] as const; + } + return [previousIdentity, previousIdentity] as const; + }).pipe( + Effect.flatMap((previousIdentity) => { + const runtimeChanged = + previousIdentity !== null && + nextIdentity !== null && + previousIdentity !== nextIdentity; + return withLiveRuntimeState(snapshot, { + applySessionLiveState: options?.applySessionLiveState ?? true, + sessionRuntimeIdentity: nextIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: !runtimeChanged, + }).pipe( + Effect.map(({ provider }) => ({ + snapshot: + preserveMessage !== undefined || preserveStatus !== undefined + ? { + ...provider, + ...(preserveStatus !== undefined ? { status: preserveStatus } : {}), + ...(preserveMessage !== undefined ? { message: preserveMessage } : {}), + } + : provider, + launchIdentity, + indexRevision, + ...(fallback ? { fallback: true, fallbackTargetIndexRevision } : {}), + ...(retryFailedUpgrade ? { retryFailedUpgrade: true } : {}), + })), + ); + }), + ); + }, + ), ); const checkProvider = inspectReadiness({ seedActiveRuntimeIdentity: true, @@ -1172,6 +1277,7 @@ export const AcpRegistryDriver: ProviderDriver ({ invalidationGeneration: current.invalidationGeneration + 1, @@ -1201,7 +1307,49 @@ export const AcpRegistryDriver: ProviderDriver= fallbackState.failedAtMs && + now - fallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS + ) { + const targetIdentity = runtimeIdentityFor(target.snapshot, target.launchIdentity); + const cachedMatchesTarget = + cached !== null && + cached.provider.version === target.snapshot.version && + (cached.launchIdentity === undefined || + target.launchIdentity === null || + cached.launchIdentity === target.launchIdentity); + const lastRuntime = cachedMatchesTarget ? null : yield* Ref.get(lastSuccessfulRuntime); + const baseFallbackProvider = cachedMatchesTarget + ? cached.provider + : lastRuntime !== null && lastRuntime.identity === targetIdentity + ? lastRuntime.provider + : target.snapshot; + return { + provider: { + ...applyRegistryReadinessMetadata(baseFallbackProvider, target.snapshot), + checkedAt: target.snapshot.checkedAt, + status: target.snapshot.enabled ? ("ready" as const) : ("disabled" as const), + message: fallbackState.message, + }, + launchIdentity: target.launchIdentity, + indexRevision: target.indexRevision, + fallback: true, + fallbackTargetLaunchIdentity: fallbackState.targetLaunchIdentity, + fallbackTargetVersion: fallbackState.targetVersion, + fallbackTargetIndexRevision: fallbackState.targetIndexRevision, + failedTargetLaunchIdentity: null, + probeFailed: false, + fromCache: true, + captured, + }; + } + } else if ( + target.retryFailedUpgrade !== true && cached !== null && isAcpRegistryCacheValid( cached, @@ -1215,15 +1363,14 @@ export const AcpRegistryDriver: ProviderDriver + current?.targetLaunchIdentity === incomingIdentity ? null : current, + ); + yield* Ref.update(failedUpgradeTarget, (current) => + current?.targetLaunchIdentity === incomingIdentity ? null : current, + ); yield* triggerSnapshotRefresh; } }).pipe( @@ -1411,6 +1574,8 @@ export const AcpRegistryDriver: ProviderDriver { + const { message: _previousMessage, ...base } = + lastRuntime.provider; + return { + ...base, + checkedAt: provider.checkedAt, + status: provider.status, + auth: + provider.auth.status === "unauthenticated" + ? provider.auth + : base.auth, + ...(provider.message !== undefined + ? { message: provider.message } + : {}), + }; + })() + : provider; + const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState( + preservedBase, { sessionRuntimeIdentity: previousIdentity, requireMatchingRuntimeIdentity: false, @@ -1450,9 +1632,26 @@ export const AcpRegistryDriver: ProviderDriver= existingFallback.failedAtMs && + now - existingFallback.failedAtMs < FALLBACK_RETRY_BACKOFF_MS; yield* Ref.set(activeFallback, { targetLaunchIdentity: fallbackTargetLaunchIdentity, targetVersion: fallbackTargetVersion, + targetIndexRevision: fallbackTargetIndexRevision, fallbackVersion: providerToPublish.version, fallbackLaunchIdentity: launchIdentity, - failedAtMs, + failedAtMs: keepFailedAt ? existingFallback.failedAtMs : now, message: fallbackMessage ?? existingFallback?.message ?? @@ -1523,7 +1740,11 @@ export const AcpRegistryDriver: ProviderDriver { const next = new Set(retired); - next.add(previousIdentity); + // Retire only a runtime that actually succeeded; a never-installed + // target replaced during cold fallback stays eligible to reconcile. + if (previousLastSuccessful?.identity === previousIdentity) { + next.add(previousIdentity); + } next.delete(resolvedIdentity); return next; }); @@ -1549,6 +1770,13 @@ export const AcpRegistryDriver: ProviderDriver + prev !== null && prev.identity === activeId + ? { + identity: prev.identity, + provider: { ...prev.provider, slashCommands, skills }, + } + : prev, + ); + } + } return undefined; }), ) @@ -1621,17 +1867,48 @@ export const AcpRegistryDriver: ProviderDriver 0 ? learned : current.models, ); + const activeId = yield* Ref.get(activeRuntimeIdentity); + const fallbackState = yield* Ref.get(activeFallback); + const failedUpgrade = yield* Ref.get(failedUpgradeTarget); + const effectiveIdentity = meta.runtimeIdentity ?? activeId ?? gate.expected; + const preserveFallbackMessage = + fallbackState !== null && + fallbackState.fallbackLaunchIdentity !== null && + effectiveIdentity === fallbackState.fallbackLaunchIdentity; + const preserveUpgradeFailure = + !preserveFallbackMessage && + failedUpgrade !== null && + activeId !== null && + failedUpgrade.targetLaunchIdentity !== activeId; + const next = preserveFallbackMessage + ? { ...applied, message: fallbackState.message } + : preserveUpgradeFailure + ? { + ...applied, + status: applied.enabled ? failedUpgrade.status : applied.status, + ...(failedUpgrade.message !== undefined + ? { message: failedUpgrade.message } + : {}), + } + : applied; const published = yield* tryPublishSnapshot(next); if (!published) return undefined; if (!gate.runtimeTransitioning && next.models !== current.models) { yield* Ref.set(learnedModels, next.models); } + if (!gate.runtimeTransitioning && activeId !== null) { + yield* Ref.update(lastSuccessfulRuntime, (prev) => + prev !== null && prev.identity === activeId + ? { identity: prev.identity, provider: applied } + : prev, + ); + } const now = yield* Clock.currentTimeMillis; yield* Ref.update(enrichmentCache, (cache) => updateAcpRegistryEnrichmentCache({ @@ -1775,22 +2052,32 @@ export const AcpRegistryDriver: ProviderDriver= revision + fallbackTargetRevision !== null && + fallbackTargetRevision >= revision ) { const fallbackState = yield* Ref.get(activeFallback); const now = yield* Clock.currentTimeMillis; if ( fallbackState === null || (now >= fallbackState.failedAtMs && - now - fallbackState.failedAtMs < REGISTRY_FAILURE_BACKOFF_MS) + now - fallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS) ) { return; } } + if ( + initialProbe.published && + publishedReadiness.probeFailed && + publishedReadiness.indexRevision !== null && + publishedReadiness.indexRevision >= revision + ) { + return; + } if ( initialProbe.published && !publishedReadiness.fallback && diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 95bfe3f60242b..3974b85044070 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -388,6 +388,7 @@ export interface AcpRegistryConfigurationProbeResolved { readonly launchIdentity?: string; readonly indexRevision?: number; readonly fallback?: boolean; + readonly failedTarget?: AcpRegistrySupport.AcpRegistryFailedTarget; } export interface AcpRegistryConfigurationProbeResult { @@ -659,6 +660,9 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ? {} : { indexRevision: result.resolved.indexRevision }), ...(result.resolved.fallback ? { fallback: true } : {}), + ...(result.resolved.failedTarget === undefined + ? {} + : { failedTarget: result.resolved.failedTarget }), }, }; }, From 5da35d448e275b97a79f85a1412390b80655fce5 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 13:58:58 +0000 Subject: [PATCH 14/28] test(acp-registry): fix Effect DateTime and optional-chaining typecheck diagnostics --- .../src/server/AcpRegistrySupport.test.ts | 2 +- packages/provider-acp-registry/src/server/driver.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 2cac5d3491f53..332159c0217b5 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1589,7 +1589,7 @@ describe("AcpRegistrySupport", () => { yield* Deferred.await(renameBlocked); // Age the lock past INSTALL_LOCK_STALE_MS so installer 2 takes over and publishes artifactRoot. const lockPath = path.join(raceToolsDir, "example-agent", "1.0.0", "linux-x86_64.lock"); - yield* fileSystem.utimes(lockPath, new Date(0), new Date(0)); + yield* fileSystem.utimes(lockPath, 0, 0); yield* TestClock.adjust("6 minutes"); const installedBy2 = yield* raceInstaller2.resolve(settings(), "/workspace"); yield* Deferred.succeed(releaseFirstRename, undefined); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 3b921e7475937..c9978d3ef9d25 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1877,7 +1877,7 @@ describe("AcpRegistryDriver registry recovery", () => { const v3LiveConfigDuringFallback = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.models.some((model) => - model.capabilities?.optionDescriptors.some((opt) => opt.id === "fallback-effort"), + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "fallback-effort"), ), ), Stream.runHead, @@ -2947,7 +2947,7 @@ describe("AcpRegistryDriver registry recovery", () => { const v1NewerLiveApplied = yield* instance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.models.some((model) => - model.capabilities?.optionDescriptors.some((opt) => opt.id === "v1-live-effort"), + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "v1-live-effort"), ), ), Stream.runHead, @@ -2978,7 +2978,7 @@ describe("AcpRegistryDriver registry recovery", () => { expect(v1AfterSuperseded.models.map((model) => model.slug)).toEqual(["default"]); expect( v1AfterSuperseded.models.some((model) => - model.capabilities?.optionDescriptors.some((opt) => opt.id === "v1-live-effort"), + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "v1-live-effort"), ), ).toBe(true); expect( From 1efb73d78a3f2ec1813cdee6ac2c78aef0a03e9d Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 14:34:21 +0000 Subject: [PATCH 15/28] fix(acp-registry): harden fallback backoff, broken slot recovery, and legacy baselines --- docs/user/providers-acp.md | 17 +- .../AcpRegistryRuntimeCoordinator.test.ts | 48 +- .../server/AcpRegistryRuntimeCoordinator.ts | 18 +- .../src/server/AcpRegistrySupport.test.ts | 443 +++++++++++++++++ .../src/server/AcpRegistrySupport.ts | 454 ++++++++++++------ .../src/server/driver.test.ts | 69 ++- .../src/server/driver.ts | 44 +- 7 files changed, 893 insertions(+), 200 deletions(-) diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 3a19b92a52664..2096fe34eae26 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -53,14 +53,15 @@ but keeps package installs. To use an existing local binary, set **Executable ov T3 Code refreshes the Registry index in the background and automatically installs new versions of prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while -that agent is starting a session. If a newly published version of a T3-managed binary agent cannot -be installed, T3 Code keeps running the newest previously installed version with a recorded install -receipt until the update succeeds. Agents using **Executable override** keep running the configured -executable—update those overrides directly on the server—while Registry refreshes can still pick up -updated Registry metadata, arguments, and environment variables. Refreshing providers (in -**Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on -mobile) requests a fresh Registry check right away for unprepared or unavailable agents, and after -the agent's status check finishes for installed agents. +that agent is starting a session. If a newly published version of a T3-managed binary agent fails +to download or verify, T3 Code keeps running the newest previously installed version until the +update succeeds (versions installed by older releases before update tracking cannot be used as +fallback). Agents using **Executable override** keep running the configured executable—update those +overrides directly on the server—while Registry refreshes can still pick up updated Registry +metadata, arguments, and environment variables. Refreshing providers (in **Settings → Providers** on +web and desktop, or **Refresh providers** in environment settings on mobile) requests a fresh +Registry check right away for unprepared or unavailable agents, and after the agent's status check +finishes for installed agents. ## Signing in diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index 1d8588f62ae39..21b82416bebbb 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -246,15 +246,35 @@ describe("AcpRegistryRuntimeCoordinator", () => { expect( Option.isNone(yield* withDecoupledClock(coordinator.getUrlAuthAction(instanceId))), ).toBe(true); + expect(expiringRequest.pollUnsafe()).toBeUndefined(); expect( yield* withDecoupledClock( coordinator.acceptUrlAuthentication({ instanceId, elicitationId: "login-expiring" }), ), ).toBe(false); - expect(expiringRequest.pollUnsafe()).toBeUndefined(); - yield* TestClock.adjust("10 minutes"); expect(yield* Fiber.join(expiringRequest)).toBe(false); yield* Fiber.interrupt(exactExpiryWatcher); + + // An unaccepted request also expires cleanly when the timeout fires. + const timeoutSeen = yield* Deferred.make(); + const timeoutWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-timeout" + ? Deferred.succeed(timeoutSeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const timeoutRequest = yield* coordinator + .requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-timeout", + }) + .pipe(Effect.forkChild); + yield* Deferred.await(timeoutSeen); + yield* TestClock.adjust("10 minutes"); + expect(yield* Fiber.join(timeoutRequest)).toBe(false); + expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + yield* Fiber.interrupt(timeoutWatcher); yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); @@ -478,34 +498,31 @@ describe("AcpRegistryRuntimeCoordinator", () => { ); yield* Deferred.await(replayDone); expect(replayedNames).toEqual(["cmd-reused", "cmd-reused-c", "cmd-after-watch"]); + yield* Fiber.interrupt(secondWatcher); // 6. Concurrent publications for the same runtime are serialized so watchers always finish // on the exact latest committed state returned by get(). const concurrentCount = 12; - const concurrentStartLength = replayedNames.length; + const concurrentNames: Array = []; + const concurrentReady = yield* Deferred.make(); const concurrentDone = yield* Deferred.make(); const concurrentWatcher = yield* coordinator .watchAvailableCommands(instanceId, (commands) => Effect.gen(function* () { const name = commands.slashCommands[0]?.name ?? "empty"; - if (name.startsWith("concurrent-")) { - replayedNames.push(name); - if (replayedNames.length - concurrentStartLength >= concurrentCount) { + if (name === "cmd-after-watch") { + yield* Deferred.succeed(concurrentReady, undefined); + } else if (name.startsWith("concurrent-")) { + concurrentNames.push(name); + if (concurrentNames.length >= concurrentCount) { yield* Deferred.succeed(concurrentDone, undefined); } } }), ) .pipe(Effect.forkChild); - // Wait for initial replay of concurrentWatcher before firing the concurrent batch. - const concurrentReady = yield* Deferred.make(); - const syncWatcher = yield* coordinator - .watchAvailableCommands(instanceId, () => - Deferred.succeed(concurrentReady, undefined).pipe(Effect.asVoid), - ) - .pipe(Effect.forkChild); + // Wait for concurrentWatcher itself to finish its initial replay before firing the batch. yield* Deferred.await(concurrentReady); - yield* Fiber.interrupt(syncWatcher); yield* Effect.all( Array.from({ length: concurrentCount }, (_, index) => coordinator.publishAvailableCommands( @@ -523,11 +540,10 @@ describe("AcpRegistryRuntimeCoordinator", () => { requireMatchingRuntimeIdentity: true, }), ); - expect(replayedNames[replayedNames.length - 1]).toBe( + expect(concurrentNames[concurrentNames.length - 1]).toBe( committedLatest.slashCommands[0]?.name, ); yield* Fiber.interrupt(concurrentWatcher); - yield* Fiber.interrupt(secondWatcher); yield* Fiber.interrupt(watcher); }).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 9b0d432c686dd..c81e2189cd942 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -328,7 +328,6 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt }).pipe(Effect.withSpan(`AcpRegistryRuntimeCoordinator.${names.watch}.subscribe`)); const snapshotRevision = snapshot.revision; const inst = snapshot.instances.get(instanceId); - const lastDeliveredByRuntime = new Map(); const metaFor = ( runtimeIdentity: string | undefined, revision: number, @@ -355,21 +354,15 @@ const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveSt ) .toSorted((left, right) => left.revision - right.revision); for (const entry of replayed) { - lastDeliveredByRuntime.set(entry.runtimeIdentity, entry.revision); yield* onUpdate( entry.value, metaFor(entry.runtimeIdentity, entry.revision, entry.lifetime), ); } yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => { - if (update.instanceId !== instanceId) return false; - if (update.revision <= snapshotRevision) return false; - const lastDelivered = lastDeliveredByRuntime.get(update.runtimeIdentity) ?? 0; - if (update.revision <= lastDelivered) return false; - lastDeliveredByRuntime.set(update.runtimeIdentity, update.revision); - return true; - }), + Stream.filter( + (update) => update.instanceId === instanceId && update.revision > snapshotRevision, + ), Stream.runForEach((update) => onUpdate( update.value, @@ -494,12 +487,9 @@ const make = Effect.gen(function* () { } }), ); - const remaining = Duration.millis( - Math.max(0, DateTime.toEpochMillis(expiresAt) - DateTime.toEpochMillis(createdAt)), - ); return yield* Deferred.await(consent).pipe( Effect.timeoutOrElse({ - duration: remaining, + duration: URL_AUTH_ACTION_TTL, orElse: () => Effect.succeed(false), }), ); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 332159c0217b5..58dfdbd4c49b1 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -18,6 +18,8 @@ import * as Path from "effect/Path"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -3871,6 +3873,447 @@ describe("AcpRegistrySupport", () => { ), ); }); + + it.effect( + "repairs broken artifact slots, recovers corrupt or transiently unreadable legacy baselines, and prunes uninstalled baselines", + () => { + const archiveAUrl = "https://registry.test/v1-a.bin"; + const archiveBUrl = "https://registry.test/v1-b.bin"; + const archiveCUrl = "https://registry.test/v2-c.bin"; + const bytesA = new TextEncoder().encode("#!/bin/sh\necho archive-a\n"); + const bytesB = new TextEncoder().encode("#!/bin/sh\necho archive-b\n"); + const bytesC = new TextEncoder().encode("#!/bin/sh\necho archive-c\n"); + const binaryAgent = (version: string, archive: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive, cmd: "./bin/example-agent" }, + }, + }), + version, + }); + let upstream = binaryAgent("1.2.3", archiveAUrl); + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + // 1. A broken artifact-scoped slot (receipt present, executable deleted) self-repairs on resolve(). + const repairDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-repair-slot-", + }); + const repairResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: repairDir, + toolsDir: `${repairDir}/tools`, + registryUrl, + }); + const resolvedA = yield* repairResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedA.spawn.command)).toBe( + "#!/bin/sh\necho archive-a\n", + ); + + upstream = binaryAgent("1.2.3", archiveBUrl); + yield* repairResolver.invalidateIndex(); + yield* repairResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedB = yield* repairResolver.resolve(settings(), "/workspace"); + expect(resolvedB.spawn.command).toMatch(/linux-x86_64-[0-9a-f]{12}\/bin\/example-agent$/u); + expect(yield* fileSystem.readFileString(resolvedB.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Delete B's executable while leaving the artifact slot directory and receipt behind. + yield* fileSystem.remove(resolvedB.spawn.command); + expect(yield* fileSystem.exists(resolvedB.spawn.command)).toBe(false); + const repairedB = yield* repairResolver.resolve(settings(), "/workspace"); + expect(repairedB.spawn.command).toBe(resolvedB.spawn.command); + expect(yield* fileSystem.readFileString(repairedB.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 2. A transient I/O failure reading legacy-baselines.json preserves A's baseline in memory + // so the next successful refresh still persists A and updates registry.json to B. + const ioDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-io-", + }); + const ioRegistryDir = `${ioDir}/acp-registry`; + const ioRegistryPath = `${ioRegistryDir}/registry.json`; + const ioBaselinesPath = `${ioRegistryDir}/legacy-baselines.json`; + const ioLegacyExe = `${ioDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(ioLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(ioLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(ioLegacyExe, 0o755); + yield* fileSystem.makeDirectory(ioRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + ioRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + + let failLegacyRead = true; + const flakyBaselinesFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + failLegacyRead && filePath === ioBaselinesPath + ? fileSystem.readFileString(ioDir, encoding) + : fileSystem.readFileString(filePath, encoding), + }; + upstream = binaryAgent("1.0.0", archiveBUrl); + const ioResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: ioDir, + toolsDir: `${ioDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, flakyBaselinesFs)); + yield* ioResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(ioRegistryPath)).toContain(archiveAUrl); + expect(yield* fileSystem.exists(ioBaselinesPath)).toBe(false); + + failLegacyRead = false; + yield* ioResolver.invalidateIndex(); + yield* ioResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(ioRegistryPath)).toContain(archiveBUrl); + const persistedBaselines = yield* fileSystem.readFileString(ioBaselinesPath); + expect(persistedBaselines).toContain("example-agent\\u00001.0.0\\u0000linux-x86_64"); + expect(persistedBaselines).toContain(archiveAUrl); + + // Restarting against the recovered disk files must install B instead of reusing legacy A. + const restartedIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: ioDir, + toolsDir: `${ioDir}/tools`, + registryUrl, + }); + const resolvedAfterIoRecovery = yield* restartedIoResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterIoRecovery.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 3. A corrupt legacy-baselines.json is quarantined and rebuilt cleanly so disk registry + // updates do not freeze, and uninstallManagedBinary prunes removed agents from disk. + const corruptDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-corrupt-", + }); + const corruptRegistryDir = `${corruptDir}/acp-registry`; + const corruptRegistryPath = `${corruptRegistryDir}/registry.json`; + const corruptBaselinesPath = `${corruptRegistryDir}/legacy-baselines.json`; + const corruptLegacyExe = `${corruptDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(corruptLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(corruptLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(corruptLegacyExe, 0o755); + yield* fileSystem.makeDirectory(corruptRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + corruptRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + yield* fileSystem.writeFileString(corruptBaselinesPath, "{not json"); + + upstream = binaryAgent("2.0.0", archiveCUrl); + const corruptResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: corruptDir, + toolsDir: `${corruptDir}/tools`, + registryUrl, + }); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${corruptBaselinesPath}.corrupt`)).toBe( + "{not json", + ); + expect(yield* fileSystem.readFileString(corruptRegistryPath)).toContain(archiveCUrl); + const rebuiltBaselines = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + const exampleSlotKey = "example-agent\u00001.0.0\u0000linux-x86_64"; + const otherSlotKey = "other-agent\u00001.0.0\u0000linux-x86_64"; + expect(rebuiltBaselines[exampleSlotKey]).toContain(archiveAUrl); + + // Add another agent's baseline entry, uninstall example-agent, and verify only example-agent is pruned. + rebuiltBaselines[otherSlotKey] = "other-baseline"; + yield* fileSystem.writeFileString(corruptBaselinesPath, JSON.stringify(rebuiltBaselines)); + expect(yield* corruptResolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual( + { + agentId: "example-agent", + removed: true, + }, + ); + const prunedBaselines = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(prunedBaselines[exampleSlotKey]).toBeUndefined(); + expect(prunedBaselines[otherSlotKey]).toBe("other-baseline"); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(upstream))), + ); + } + const bytes = + request.url === archiveAUrl ? bytesA : request.url === archiveBUrl ? bytesB : bytesC; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)), + ); + }), + ), + ); + }, + ); + + it.effect( + "enforces post-retry removal, archive extraction timeout, and pre-promotion concurrent slot checks", + () => { + const archiveV1Url = "https://registry.test/v1.bin"; + const archiveV2AUrl = "https://registry.test/v2-a.bin"; + const archiveV2BUrl = "https://registry.test/v2-b.bin"; + const archiveTarUrl = "https://registry.test/v3.tar.gz"; + const archivePlainUrl = "https://registry.test/v3-plain.bin"; + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho ok\n"); + const binaryAgent = (version: string, archive: string, sha256Hex?: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive, + cmd: "./bin/example-agent", + ...(sha256Hex ? { sha256: sha256Hex } : {}), + }, + }, + }), + version, + }); + let upstreamAgents: ReadonlyArray = [ + binaryAgent("1.0.0", archiveV1Url), + ]; + let downloadGate: { + readonly url: string; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + // 1. Post-retry concurrent removal: retry B fails with checksum_mismatch while the agent is + // concurrently removed from the index -> resolve() fails with agent_not_found without fallback. + const removalDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-post-retry-remove-", + }); + const removalResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removalDir, + toolsDir: `${removalDir}/tools`, + registryUrl, + }); + const v1Resolved = yield* removalResolver.resolve(settings(), "/workspace"); + expect(v1Resolved.agent?.version).toBe("1.0.0"); + + // Cache 2.0.0 archive A (which returns 503), then point upstream to failing 2.0.0 archive B. + upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl)]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + const bGate = { + url: archiveV2BUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + downloadGate = bGate; + const resolveFiber = yield* removalResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(bGate.started); + + // Concurrently remove the agent from the registry index while retry B's download is in flight. + upstreamAgents = []; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(bGate.release, undefined); + expect((yield* Fiber.join(resolveFiber)).reason).toBe("agent_not_found"); + + // 2. Archive extraction timeout maps to archive_invalid (falls back when a prior receipted + // version exists, and surfaces archive_invalid while releasing locks when none exists). + let tarStartedGate: Deferred.Deferred | null = null; + const hangingTarSpawner = ChildProcessSpawner.make((command) => { + if ( + ChildProcess.isStandardCommand(command) && + (command.command === "tar" || command.command.endsWith("/tar")) + ) { + const gate = tarStartedGate; + tarStartedGate = null; + return (gate === null ? Effect.void : Deferred.succeed(gate, undefined)).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ); + } + return realSpawner.spawn(command); + }); + const timeoutFallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removalDir, + toolsDir: `${removalDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, hangingTarSpawner), + Effect.provideService(SpawnExecutableResolution, (command) => command), + ); + upstreamAgents = [binaryAgent("3.0.0", archiveTarUrl)]; + yield* timeoutFallbackResolver.invalidateIndex(); + yield* timeoutFallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + tarStartedGate = yield* Deferred.make(); + const tarWithFallback = tarStartedGate; + const fallbackTimeoutFiber = yield* timeoutFallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(tarWithFallback); + yield* TestClock.adjust("5 minutes"); + const fallbackOnTimeout = yield* Fiber.join(fallbackTimeoutFiber); + expect(fallbackOnTimeout.fallback).toBe(true); + expect(fallbackOnTimeout.agent?.version).toBe("1.0.0"); + + const noFallbackDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-extract-timeout-", + }); + const noFallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: noFallbackDir, + toolsDir: `${noFallbackDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, hangingTarSpawner), + Effect.provideService(SpawnExecutableResolution, (command) => command), + ); + tarStartedGate = yield* Deferred.make(); + const tarWithoutFallback = tarStartedGate; + const noFallbackTimeoutFiber = yield* noFallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(tarWithoutFallback); + yield* TestClock.adjust("5 minutes"); + expect((yield* Fiber.join(noFallbackTimeoutFiber)).reason).toBe("archive_invalid"); + + // Locks and permits are released cleanly after extraction timeout so a later install succeeds. + upstreamAgents = [binaryAgent("3.0.0", archivePlainUrl)]; + yield* noFallbackResolver.invalidateIndex(); + yield* noFallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const recoveredAfterTimeout = yield* noFallbackResolver.resolve(settings(), "/workspace"); + expect(recoveredAfterTimeout.agent?.version).toBe("3.0.0"); + + // 3. Pre-promotion concurrentSlot recheck returns the sibling install without renaming again. + const concurrentDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-pre-promote-", + }); + upstreamAgents = [binaryAgent("1.2.3", archiveV1Url)]; + const baseSeedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }); + yield* baseSeedResolver.resolve(settings(), "/workspace"); + + upstreamAgents = [binaryAgent("1.2.3", archivePlainUrl)]; + let receiptGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const firstReceiptGate = receiptGate; + let renameToArtifactCount = 0; + const instrumentedFs: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => { + if (receiptGate !== null && filePath.endsWith("/.t3-artifact.json")) { + const gate = receiptGate; + receiptGate = null; + return fileSystem.writeFileString(filePath, data, options).pipe( + Effect.tap(() => Deferred.succeed(gate.started, undefined)), + Effect.tap(() => Deferred.await(gate.release)), + ); + } + return fileSystem.writeFileString(filePath, data, options); + }, + rename: (oldPath, newPath) => { + if (/linux-x86_64-[0-9a-f]{12}$/u.test(newPath)) { + renameToArtifactCount += 1; + } + return fileSystem.rename(oldPath, newPath); + }, + }; + const installer1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, instrumentedFs)); + const installer2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, instrumentedFs)); + yield* installer1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* installer2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + + const firstInstallFiber = yield* installer1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstReceiptGate.started); + // Age installer1's lock so installer2 takes over and publishes the artifact slot first. + yield* fileSystem.utimes( + `${concurrentDir}/tools/example-agent/1.2.3/linux-x86_64.lock`, + 0, + 0, + ); + const secondResult = yield* installer2.resolve(settings(), "/workspace"); + expect(renameToArtifactCount).toBe(1); + + yield* Deferred.succeed(firstReceiptGate.release, undefined); + const firstResult = yield* Fiber.join(firstInstallFiber); + expect(firstResult.spawn.command).toBe(secondResult.spawn.command); + expect(renameToArtifactCount).toBe(1); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify({ version: "1.0.0", agents: upstreamAgents })), + ), + ); + } + if (request.url === archiveV2AUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ); + } + const respond = Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(binaryBytes.buffer as ArrayBuffer)), + ); + if (downloadGate !== null && request.url === downloadGate.url) { + const gate = downloadGate; + downloadGate = null; + return Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); + } + return respond; + }), + ), + ); + }, + ); }); describe("acpRegistryManagedBinaryDirectories", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 6ca4f7022718f..2068c15fba632 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -397,6 +397,8 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged } if (target === undefined) return Array.from(new Set(directories)); + const agentDirectories = (yield* listDirectories(installsDirectory)).toSorted(); + if (agentDirectories.length === 0) return Array.from(new Set(directories)); const cachedAgents = yield* fileSystem .readFileString(path.join(registryDirectory, "registry.json")) .pipe( @@ -415,12 +417,17 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged (agent) => [`${agent.id}\0${encodeURIComponent(agent.version)}`, agent] as const, ), ); - const legacyBaselinesResult = yield* readLegacyBaselinesFile( - fileSystem, - path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME), - ); - const legacyBaselines = legacyBaselinesResult.ok ? legacyBaselinesResult.baselines : undefined; - for (const agent of (yield* listDirectories(installsDirectory)).toSorted()) { + let legacyBaselinesCache: Readonly> | undefined | null = null; + const getLegacyBaselines = Effect.gen(function* () { + if (legacyBaselinesCache !== null) return legacyBaselinesCache; + const result = yield* readLegacyBaselinesFile( + fileSystem, + path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME), + ); + legacyBaselinesCache = result.status === "ok" ? result.baselines : undefined; + return legacyBaselinesCache; + }); + for (const agent of agentDirectories) { const versions = (yield* listDirectories(path.join(installsDirectory, agent))).toSorted( (left, right) => compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), @@ -463,7 +470,7 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged if (Option.isNone(receipt) && !isPrimary) { return Option.none<{ readonly rank: number; - readonly mtimeMs: number; + readonly installRoot: string; readonly isPrimary: boolean; readonly entry: string; readonly directory: string; @@ -471,20 +478,31 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged } // Skip superseded legacy primary slots once a receipted slot exists or a baseline disagrees. if (Option.isNone(receipt) && isPrimary) { - const baselineSuperseded = - targetKey !== undefined && - (legacyBaselines === undefined || - (legacyBaselines[slotKey] !== undefined && - legacyBaselines[slotKey] !== targetKey)); - if (hasReceiptedSlot || baselineSuperseded) { + if (hasReceiptedSlot) { return Option.none<{ readonly rank: number; - readonly mtimeMs: number; + readonly installRoot: string; readonly isPrimary: boolean; readonly entry: string; readonly directory: string; }>(); } + if (targetKey !== undefined) { + const legacyBaselines = yield* getLegacyBaselines; + if ( + legacyBaselines === undefined || + (legacyBaselines[slotKey] !== undefined && + legacyBaselines[slotKey] !== targetKey) + ) { + return Option.none<{ + readonly rank: number; + readonly installRoot: string; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + } } const receiptSegments = Option.isSome(receipt) ? normalizeRegistryCommandPath(receipt.value.cmd) @@ -496,26 +514,33 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged segments === undefined ? installRoot : path.join(installRoot, ...segments.slice(0, -1)); - const mtimeMs = yield* fileSystem.stat(installRoot).pipe( - Effect.map((info) => - Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, - ), - Effect.orElseSucceed(() => 0), - ); const rank = receiptMatchesTarget ? 0 : Option.isSome(receipt) ? 1 : 2; - return Option.some({ rank, mtimeMs, isPrimary, entry, directory }); + return Option.some({ rank, installRoot, isPrimary, entry, directory }); }), ); - const orderedSlots = inspectedSlots - .filter(Option.isSome) - .map((slot) => slot.value) - .toSorted( - (left, right) => - left.rank - right.rank || - right.mtimeMs - left.mtimeMs || - Number(left.isPrimary) - Number(right.isPrimary) || - left.entry.localeCompare(right.entry), - ); + const candidateSlots = inspectedSlots.filter(Option.isSome).map((slot) => slot.value); + const rankCounts = new Map(); + for (const slot of candidateSlots) { + rankCounts.set(slot.rank, (rankCounts.get(slot.rank) ?? 0) + 1); + } + const rankedSlots = yield* Effect.forEach(candidateSlots, (slot) => + (rankCounts.get(slot.rank) ?? 0) > 1 + ? fileSystem.stat(slot.installRoot).pipe( + Effect.map((info) => ({ + ...slot, + mtimeMs: Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, + })), + Effect.orElseSucceed(() => ({ ...slot, mtimeMs: 0 })), + ) + : Effect.succeed({ ...slot, mtimeMs: 0 }), + ); + const orderedSlots = rankedSlots.toSorted( + (left, right) => + left.rank - right.rank || + right.mtimeMs - left.mtimeMs || + Number(left.isPrimary) - Number(right.isPrimary) || + left.entry.localeCompare(right.entry), + ); for (const slot of orderedSlots) { if (yield* fileSystem.exists(slot.directory).pipe(Effect.orElseSucceed(() => false))) { directories.push(slot.directory); @@ -721,8 +746,9 @@ const decodeLegacyBaselines = Schema.decodeUnknownOption( ); type LegacyBaselinesReadResult = - | { readonly ok: true; readonly baselines: Readonly> } - | { readonly ok: false }; + | { readonly status: "ok"; readonly baselines: Readonly> } + | { readonly status: "corrupt" } + | { readonly status: "io_error" }; function legacyBaselineSlotKey( agentId: string, @@ -739,11 +765,13 @@ function readLegacyBaselinesFile( return fileSystem.readFileString(baselinesPath).pipe( Effect.map((raw): LegacyBaselinesReadResult => { const decoded = decodeLegacyBaselines(raw); - return Option.isSome(decoded) ? { ok: true, baselines: decoded.value } : { ok: false }; + return Option.isSome(decoded) + ? { status: "ok", baselines: decoded.value } + : { status: "corrupt" }; }), Effect.catch((error) => Effect.succeed( - error.reason._tag === "NotFound" ? { ok: true, baselines: {} } : { ok: false }, + error.reason._tag === "NotFound" ? { status: "ok", baselines: {} } : { status: "io_error" }, ), ), ); @@ -1308,6 +1336,33 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return { registry, text: collected.text }; }); + const acquireFileLock = Effect.fn("AcpRegistryCatalog.acquireInstallLock")(function* ( + lockPath: string, + ) { + for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { + const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( + Effect.as(true), + Effect.catchIf( + (error) => isAlreadyExists(error), + () => Effect.succeed(false), + ), + ); + if (acquired) return; + const now = yield* Clock.currentTimeMillis; + const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); + const mtime = Option.flatMap(lockInfo, (info) => info.mtime); + if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { + yield* fileSystem.remove(lockPath, { force: true }); + continue; + } + yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); + } + return yield* new AcpRegistryError({ + reason: "install_failed", + detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, + }); + }); + const writeLegacyBaselinesAtomically = (baselines: Readonly>) => random.uuidV4().pipe( Effect.flatMap((id) => { @@ -1322,6 +1377,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ); + const withLegacyBaselinesLock = (effect: Effect.Effect) => { + const lockPath = `${legacyBaselinesPath}.lock`; + return fileSystem + .makeDirectory(registryDirectory, { recursive: true }) + .pipe( + Effect.andThen(acquireFileLock(lockPath)), + Effect.andThen( + effect.pipe( + Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), + ), + ), + ); + }; + const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( inMemoryPrevious: AcpRegistryIndex | undefined, nextIndex: AcpRegistryIndex, @@ -1360,64 +1429,120 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } } if (unreceiptedLegacySlots.length === 0) return true; - const existingDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); - if (!existingDisk.ok) return false; - const unpersistedSlots = unreceiptedLegacySlots.filter((slot) => { - const existingBaseline = existingDisk.baselines[slot.slotKey]; - if (existingBaseline !== undefined) { - legacyBaselineBySlotKey.set(slot.slotKey, existingBaseline); - return false; - } - return true; - }); - if (unpersistedSlots.length === 0) return true; - const previousIndex = inMemoryPrevious ?? Option.getOrUndefined(yield* readCachedRegistry); - const previousById = new Map( - (previousIndex?.agents ?? []).map((agent) => [agent.id, agent] as const), + const recordDivergingInMemory = Effect.fn("AcpRegistryCatalog.recordDivergingLegacyBaselines")( + function* (existingBaselines: Readonly>) { + const unpersistedSlots = unreceiptedLegacySlots.filter((slot) => { + const existingBaseline = existingBaselines[slot.slotKey]; + if (existingBaseline !== undefined) { + legacyBaselineBySlotKey.set(slot.slotKey, existingBaseline); + return false; + } + return true; + }); + if (unpersistedSlots.length === 0) { + return { newBaselines: {} as Record, hasUpdates: false }; + } + const previousIndex = inMemoryPrevious ?? Option.getOrUndefined(yield* readCachedRegistry); + const previousById = new Map( + (previousIndex?.agents ?? []).map((agent) => [agent.id, agent] as const), + ); + const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); + const newBaselines: Record = {}; + let hasUpdates = false; + for (const slot of unpersistedSlots) { + const existingInMemory = legacyBaselineBySlotKey.get(slot.slotKey); + if (existingInMemory !== undefined) { + newBaselines[slot.slotKey] = existingInMemory; + hasUpdates = true; + continue; + } + const previousAgent = previousById.get(slot.agentId); + if ( + previousAgent === undefined || + encodeURIComponent(previousAgent.version) !== slot.encodedVersion + ) { + continue; + } + const previousTarget = previousAgent.distribution.binary?.[slot.candidateTarget]; + if (previousTarget === undefined) continue; + const previousKey = binaryArtifactIdentityKey(previousTarget); + const nextAgent = nextById.get(slot.agentId); + const nextTarget = + nextAgent !== undefined && encodeURIComponent(nextAgent.version) === slot.encodedVersion + ? nextAgent.distribution.binary?.[slot.candidateTarget] + : undefined; + // Record the legacy artifact whenever the slot's artifact changes, version bumps, or disappears + // so a later rollback or repackage at the same version never mistakes the legacy install for it. + if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { + continue; + } + legacyBaselineBySlotKey.set(slot.slotKey, previousKey); + newBaselines[slot.slotKey] = previousKey; + hasUpdates = true; + } + return { newBaselines, hasUpdates }; + }, ); - const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); - const newBaselines: Record = {}; - let hasUpdates = false; - for (const slot of unpersistedSlots) { - const existingInMemory = legacyBaselineBySlotKey.get(slot.slotKey); - if (existingInMemory !== undefined) { - newBaselines[slot.slotKey] = existingInMemory; - hasUpdates = true; - continue; - } - const previousAgent = previousById.get(slot.agentId); - if ( - previousAgent === undefined || - encodeURIComponent(previousAgent.version) !== slot.encodedVersion - ) { - continue; - } - const previousTarget = previousAgent.distribution.binary?.[slot.candidateTarget]; - if (previousTarget === undefined) continue; - const previousKey = binaryArtifactIdentityKey(previousTarget); - const nextAgent = nextById.get(slot.agentId); - const nextTarget = - nextAgent !== undefined && encodeURIComponent(nextAgent.version) === slot.encodedVersion - ? nextAgent.distribution.binary?.[slot.candidateTarget] - : undefined; - // Record the legacy artifact whenever the slot's artifact changes, version bumps, or disappears - // so a later rollback or repackage at the same version never mistakes the legacy install for it. - if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { - continue; + + const initialDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if ( + initialDisk.status === "ok" && + unreceiptedLegacySlots.every((slot) => initialDisk.baselines[slot.slotKey] !== undefined) + ) { + for (const slot of unreceiptedLegacySlots) { + legacyBaselineBySlotKey.set(slot.slotKey, initialDisk.baselines[slot.slotKey]!); } - legacyBaselineBySlotKey.set(slot.slotKey, previousKey); - newBaselines[slot.slotKey] = previousKey; - hasUpdates = true; + return true; } - if (!hasUpdates) return true; - const mergedBaselines = { ...existingDisk.baselines, ...newBaselines }; - return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( - Effect.as(true), + if (initialDisk.status === "io_error") { + // Preserve diverging legacy baselines in memory across transient read failures so a later + // recovery refresh still writes artifact A instead of comparing B against B. + yield* recordDivergingInMemory({}); + return false; + } + + return yield* withLegacyBaselinesLock( + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (disk.status === "io_error") { + yield* recordDivergingInMemory({}); + return false; + } + let baseBaselines: Readonly>; + let mustRewrite = false; + if (disk.status === "corrupt") { + // Quarantine a corrupt baselines file and rebuild cleanly so disk registry updates do not freeze. + yield* fileSystem + .rename(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) + .pipe(Effect.ignore); + baseBaselines = {}; + mustRewrite = true; + } else { + baseBaselines = disk.baselines; + } + const { newBaselines, hasUpdates } = yield* recordDivergingInMemory(baseBaselines); + if (!hasUpdates && !mustRewrite) return true; + const mergedBaselines = { ...baseBaselines, ...newBaselines }; + return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( + Effect.as(true), + Effect.catch(() => + Effect.logDebug( + "Could not persist ACP Registry legacy baselines; keeping existing disk registry cache.", + ).pipe(Effect.as(false)), + ), + ); + }), + ).pipe( Effect.catch(() => - Effect.logDebug( - "Could not persist ACP Registry legacy baselines; keeping existing disk registry cache.", - ).pipe(Effect.as(false)), + recordDivergingInMemory(initialDisk.status === "ok" ? initialDisk.baselines : {}).pipe( + Effect.andThen( + Effect.logDebug( + "Could not lock ACP Registry legacy baselines; keeping existing disk registry cache.", + ), + ), + Effect.as(false), + ), ), ); }); @@ -1615,6 +1740,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly cwd?: string; readonly env?: NodeJS.ProcessEnv; readonly timeout?: Duration.Input; + readonly timeoutReason?: AcpRegistryErrorReason; readonly nonZeroExitReason?: AcpRegistryErrorReason; readonly truncatedOutputReason?: AcpRegistryErrorReason; readonly maxStdoutBytes?: number; @@ -1686,7 +1812,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct orElse: () => Effect.fail( new AcpRegistryError({ - reason: "install_failed", + reason: options.timeoutReason ?? "install_failed", detail: `Timed out running ACP Registry install command '${command}'.`, }), ), @@ -2022,33 +2148,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return installed.value; }); - const acquireInstallLock = Effect.fn("AcpRegistryCatalog.acquireInstallLock")(function* ( - lockPath: string, - ) { - for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { - const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( - Effect.as(true), - Effect.catchIf( - (error) => isAlreadyExists(error), - () => Effect.succeed(false), - ), - ); - if (acquired) return; - const now = yield* Clock.currentTimeMillis; - const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); - const mtime = Option.flatMap(lockInfo, (info) => info.mtime); - if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { - yield* fileSystem.remove(lockPath, { force: true }); - continue; - } - yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); - } - return yield* new AcpRegistryError({ - reason: "install_failed", - detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, - }); - }); - const assertExecutableInRoot = Effect.fn("AcpRegistryCatalog.assertExecutableInRoot")(function* ( root: string, executablePath: string, @@ -2168,7 +2267,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return memoryBaseline === currentKey; } const diskResult = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); - if (!diskResult.ok) { + if (diskResult.status !== "ok") { return false; } const diskBaseline = diskResult.baselines[paths.slotKey]; @@ -2254,7 +2353,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); const lockPath = `${installRoot}.lock`; - yield* acquireInstallLock(lockPath).pipe( + yield* acquireFileLock(lockPath).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -2282,6 +2381,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct directory: path.dirname(installRoot), prefix: `.${agent.id}-install-`, }); + if ( + destinationRoot === artifactRoot && + (yield* fileSystem.exists(artifactRoot).pipe(Effect.orElseSucceed(() => false))) + ) { + // Under a freshly acquired lock after findMatchingBinarySlot returned None, an existing + // artifactRoot is a broken/incomplete slot (e.g., deleted executable). Move it into the + // scoped temp directory so promotion can publish cleanly without a post-download TOCTOU. + yield* fileSystem + .rename(artifactRoot, path.join(temporaryRoot, "replaced-broken-slot")) + .pipe(Effect.ignore); + } const extractionRoot = path.join(temporaryRoot, "extracted"); yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); const kind = archiveKind(target.archive); @@ -2377,10 +2487,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const listingOptions = { maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES, timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", nonZeroExitReason: "archive_invalid", } as const; const extractOptions = { timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", nonZeroExitReason: "archive_invalid", } as const; const entries = @@ -3021,50 +3133,71 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct let activeRegistry = registry; let activeRevision = indexRevision; let activeError = error; - if (error.reason === "download_failed") { - const refreshed = yield* Effect.result( - refreshRegistry({ failureBackoffMs: DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS }), - ); - if (Result.isSuccess(refreshed)) { - const { index: latest, indexRevision: latestRevision } = refreshed.success; - if (artifactSignatureIn(latest) !== artifactSignatureIn(activeRegistry)) { - const retried = yield* Effect.result( - resolveWithRegistry(settings, cwd, environment, latest, latestRevision), - ); - if (Result.isSuccess(retried)) return retried.success; - if (!canFallbackOnError(retried.failure.reason)) { - return yield* retried.failure; - } - activeRegistry = latest; - activeRevision = latestRevision; - activeError = retried.failure; - } + const retryIfSignatureChanged = Effect.fn( + "AcpRegistryCatalog.retryResolveOnIndexChange", + )(function* (candidateRegistry: AcpRegistryIndex, candidateRevision: number) { + if ( + artifactSignatureIn(candidateRegistry) === artifactSignatureIn(activeRegistry) + ) { + return Option.none(); } - } - // Check the latest published index before falling back so concurrent removals, - // incompatibilities, or fixes are honored even on checksum/archive failures. - const latestState = yield* Ref.get(registryState); - if ( - latestState.index !== undefined && - latestState.indexRevision > activeRevision && - artifactSignatureIn(latestState.index) !== artifactSignatureIn(activeRegistry) - ) { const retried = yield* Effect.result( resolveWithRegistry( settings, cwd, environment, - latestState.index, - latestState.indexRevision, + candidateRegistry, + candidateRevision, ), ); - if (Result.isSuccess(retried)) return retried.success; + if (Result.isSuccess(retried)) return Option.some(retried.success); if (!canFallbackOnError(retried.failure.reason)) { return yield* retried.failure; } - activeRegistry = latestState.index; - activeRevision = latestState.indexRevision; + activeRegistry = candidateRegistry; + activeRevision = candidateRevision; activeError = retried.failure; + return Option.none(); + }); + if (error.reason === "download_failed") { + const refreshed = yield* Effect.result( + refreshRegistry({ failureBackoffMs: DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS }), + ); + if (Result.isSuccess(refreshed)) { + const retried = yield* retryIfSignatureChanged( + refreshed.success.index, + refreshed.success.indexRevision, + ); + if (Option.isSome(retried)) return retried.value; + } + } + // Recheck the latest published index (including after any failed retry) so concurrent + // removals, incompatibilities, or fixes are honored before falling back. + for (let attempt = 0; attempt < 3; attempt += 1) { + const latestState = yield* Ref.get(registryState); + if ( + latestState.index === undefined || + latestState.indexRevision <= activeRevision || + artifactSignatureIn(latestState.index) === artifactSignatureIn(activeRegistry) + ) { + break; + } + const retried = yield* retryIfSignatureChanged( + latestState.index, + latestState.indexRevision, + ); + if (Option.isSome(retried)) return retried.value; + } + // Final authoritative check on the latest published index right before falling back. + const finalState = yield* Ref.get(registryState); + if (finalState.index !== undefined && finalState.indexRevision > activeRevision) { + const finalAgent = yield* findAgent(finalState.index, agentId); + yield* compatibleDistribution(finalAgent, settings.distribution); + if (artifactSignatureIn(finalState.index) !== artifactSignatureIn(activeRegistry)) { + return yield* activeError; + } + activeRegistry = finalState.index; + activeRevision = finalState.indexRevision; } const fallback = yield* resolveFallbackInstalledBinary( settings, @@ -3161,11 +3294,30 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); if (removed) { + const prefix = `${safeAgentId}\0`; for (const key of legacyBaselineBySlotKey.keys()) { - if (key.startsWith(`${safeAgentId}\0`)) { + if (key.startsWith(prefix)) { legacyBaselineBySlotKey.delete(key); } } + if ( + yield* fileSystem + .exists(legacyBaselinesPath) + .pipe(Effect.orElseSucceed(() => false)) + ) { + yield* withLegacyBaselinesLock( + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (disk.status !== "ok") return; + const remaining = Object.fromEntries( + Object.entries(disk.baselines).filter(([key]) => !key.startsWith(prefix)), + ); + if (Object.keys(remaining).length !== Object.keys(disk.baselines).length) { + yield* writeLegacyBaselinesAtomically(remaining); + } + }), + ).pipe(Effect.ignore); + } } return { agentId: safeAgentId, removed }; }), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index c9978d3ef9d25..93a42dfeae223 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -1621,7 +1621,7 @@ describe("AcpRegistryDriver registry recovery", () => { ); it.effect( - "publishes cold and cached probes immediately without waiting for a slow registry refresh", + "publishes cold and cached probes immediately while backing off and reconciling failed upgrade fallbacks", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1633,6 +1633,7 @@ describe("AcpRegistryDriver registry recovery", () => { let remoteVersion = "2.0.0"; let remoteWebsite: string | undefined = undefined; + let remoteExtraAgentVersion: string | undefined = undefined; let failArchiveDownload = false; let probeResolveAttempts = 0; let onFallbackResolved: (() => Effect.Effect) | null = null; @@ -1672,11 +1673,12 @@ describe("AcpRegistryDriver registry recovery", () => { request, request.url === registryUrl ? new Response( - makeBinaryRegistry( - remoteVersion, - compatibleRegistryTarget, - remoteWebsite ? { website: remoteWebsite } : undefined, - ), + makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + ...(remoteWebsite ? { website: remoteWebsite } : {}), + ...(remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : {}), + }), ) : failArchiveDownload ? new Response("archive unavailable", { status: 503 }) @@ -1901,6 +1903,29 @@ describe("AcpRegistryDriver registry recovery", () => { ); expect(liveFallbackSnapshot.message).toBe(fallbackSnapshot.message); + // Unrelated agent changes or non-launch metadata updates during fallback backoff must + // refresh displayed metadata without re-probing or resetting backoff. + remoteWebsite = "https://example.test/v4-updated-docs"; + remoteExtraAgentVersion = "9.9.9"; + yield* realCatalog.invalidateIndex(); + const resolvesBeforeMetadataBackoff = probeResolveAttempts; + const metadataBackoffDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(metadataBackoffDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(metadataBackoffDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeMetadataBackoff); + const metadataBackoffSnapshot = yield* instance.snapshot.getSnapshot; + expect(metadataBackoffSnapshot.version).toBe("3.0.0"); + expect(metadataBackoffSnapshot.setup?.documentationUrl).toBe( + "https://example.test/v4-updated-docs", + ); + expect(metadataBackoffSnapshot.message).toBe(fallbackSnapshot.message); + // Once backoff expires, recovering without invalidating the cached 4.0.0 index still upgrades // because fallback did not acknowledge the 4.0.0 revision. failArchiveDownload = false; @@ -2003,10 +2028,13 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Deferred.await(soloAfterInvalidateDone); onEnrichmentEnd = null; expect(probeResolveAttempts).toBe(resolvesBeforeSolo31s + 1); + const v5Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v5Inspection.status).toBe("ready"); + const v5Identity = v5Inspection.status === "ready" ? v5Inspection.launchIdentity! : ""; // When inspect() sees cached 5.0.0 while resolve() refreshes to failing 6.0.0 and falls back - // to 4.0.0, activeFallback records 6.0.0 (from resolved.failedTarget), stays in backoff for - // 6.0.0, and does NOT retire never-installed 6.0.0 so external 6.0.0 live state reconciles. + // to 4.0.0, activeFallback records 6.0.0 (from resolved.failedTarget) and external 6.0.0 live + // state reconciles freshInstance to 6.0.0. remoteVersion = "6.0.0"; yield* realCatalog.invalidateIndex(); const resolvesBeforeFreshFallback = probeResolveAttempts; @@ -2057,6 +2085,31 @@ describe("AcpRegistryDriver registry recovery", () => { const reconciledV6Snapshot = Option.getOrThrow(yield* Fiber.join(freshReconciledToV6)); expect(reconciledV6Snapshot.version).toBe("6.0.0"); expect(reconciledV6Snapshot.message).toBeUndefined(); + + // On cold-start fallback where inspect() already seeded activeRuntimeIdentity to the failing + // target (5.0.0 on singleModelInstance), 5.0.0 was never successfully started and must not be + // retired, so external 5.0.0 live state still reconciles singleModelInstance once 5.0.0 recovers. + remoteVersion = "5.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const singleReconciledToV5 = yield* singleModelInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "5.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v5-external-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + singleModelInstanceId, + { slashCommands: [{ name: "v5-external-cmd" }], skills: [] }, + v5Identity, + ); + const reconciledV5Snapshot = Option.getOrThrow(yield* Fiber.join(singleReconciledToV5)); + expect(reconciledV5Snapshot.version).toBe("5.0.0"); + expect(reconciledV5Snapshot.message).toBeUndefined(); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 58bbd9fa68bb4..a425cea0effec 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -13,6 +13,7 @@ import { AcpRegistrySettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -1117,7 +1118,6 @@ export const AcpRegistryDriver: ProviderDriver(null); - let triggerSnapshotRefresh: Effect.Effect = Effect.void; + const refreshTarget = yield* Deferred.make>(); + const triggerSnapshotRefresh = Deferred.await(refreshTarget).pipe(Effect.flatten); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< ProviderSnapshotSettings @@ -2099,6 +2100,43 @@ export const AcpRegistryDriver: ProviderDriver= activeFallbackState.failedAtMs && + now - activeFallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS && + rechecked.launchIdentity !== null && + rechecked.launchIdentity === activeFallbackState.targetLaunchIdentity + ) { + // Unrelated agents or non-launch metadata changed while the failed target itself is + // unchanged; stay in backoff without re-probing while keeping displayed metadata fresh. + yield* liveSnapshotSemaphore.withPermit( + Effect.gen(function* () { + const liveFallback = yield* Ref.get(activeFallback); + if ( + liveFallback === null || + liveFallback.targetLaunchIdentity !== activeFallbackState.targetLaunchIdentity + ) { + return; + } + yield* Ref.set(activeFallback, { + ...liveFallback, + targetIndexRevision: rechecked.indexRevision ?? revision, + }); + const currentSnapshot = yield* getSnapshot; + if (!currentSnapshot.installed) return; + const withMetadata = applyRegistryReadinessMetadata( + currentSnapshot, + rechecked.snapshot, + ); + if (!Equal.equals(withMetadata, currentSnapshot)) { + yield* tryPublishSnapshot(withMetadata); + } + }), + ); + return; + } if ( !Equal.equals( installedRegistrySignature(rechecked), @@ -2140,7 +2178,7 @@ export const AcpRegistryDriver: ProviderDriver( effect: Effect.Effect< From 39133b0f4777232d0d83b117c3a17d07128e9d89 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 15:10:20 +0000 Subject: [PATCH 16/28] fix(acp-registry): harden baseline recovery, receipt writes, and runtime reconciliation --- .../src/provider/AcpRegistryProbe.test.ts | 2 +- docs/user/providers-acp.md | 6 +- .../src/server/AcpRegistrySupport.test.ts | 322 +++++++- .../src/server/AcpRegistrySupport.ts | 761 +++++++++++------- .../src/server/driver.test.ts | 100 ++- .../src/server/driver.ts | 478 ++++++----- 6 files changed, 1115 insertions(+), 554 deletions(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index f268017226bbd..7d90942ebb74b 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -625,7 +625,7 @@ await import(pathToFileURL(agentPath).href); instanceId, settings: decodeSettings({ agentId: "mock-agent" }), cwd: process.cwd(), - environment: process.env, + environment: {}, }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.forkScoped({ startImmediately: true }), diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 2096fe34eae26..7df448b0b71d1 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -54,9 +54,9 @@ but keeps package installs. To use an existing local binary, set **Executable ov T3 Code refreshes the Registry index in the background and automatically installs new versions of prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while that agent is starting a session. If a newly published version of a T3-managed binary agent fails -to download or verify, T3 Code keeps running the newest previously installed version until the -update succeeds (versions installed by older releases before update tracking cannot be used as -fallback). Agents using **Executable override** keep running the configured executable—update those +to download, verify, or unpack, T3 Code keeps running the newest previously installed version until +the update succeeds (agent versions installed by T3 Code releases before this fallback existed +cannot be used as fallback). Agents using **Executable override** keep running the configured executable—update those overrides directly on the server—while Registry refreshes can still pick up updated Registry metadata, arguments, and environment variables. Refreshing providers (in **Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on mobile) requests a fresh diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 58dfdbd4c49b1..3798bbc279dba 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -3892,6 +3892,8 @@ describe("AcpRegistrySupport", () => { version, }); let upstream = binaryAgent("1.2.3", archiveAUrl); + let archiveRequestsDuringLockedSlot = 0; + let countArchiveRequests = false; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -3929,6 +3931,31 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); + // If moving a broken artifact slot fails (e.g., locked files on Windows), fail fast with + // install_failed before making any archive download request. + yield* fileSystem.remove(repairedB.spawn.command); + const brokenSlotRoot = path.dirname(path.dirname(repairedB.spawn.command)); + archiveRequestsDuringLockedSlot = 0; + countArchiveRequests = true; + const unmovableSlotFs: FileSystem.FileSystem = { + ...fileSystem, + rename: (oldPath, newPath) => + oldPath === brokenSlotRoot + ? fileSystem.readFileString(repairDir).pipe(Effect.asVoid) + : fileSystem.rename(oldPath, newPath), + }; + const lockedSlotResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: repairDir, + toolsDir: `${repairDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, unmovableSlotFs)); + const lockedSlotError = yield* lockedSlotResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + countArchiveRequests = false; + expect(lockedSlotError.reason).toBe("install_failed"); + expect(archiveRequestsDuringLockedSlot).toBe(0); + // 2. A transient I/O failure reading legacy-baselines.json preserves A's baseline in memory // so the next successful refresh still persists A and updates registry.json to B. const ioDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -3987,8 +4014,63 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); - // 3. A corrupt legacy-baselines.json is quarantined and rebuilt cleanly so disk registry - // updates do not freeze, and uninstallManagedBinary prunes removed agents from disk. + // 2b. An incomplete tools-directory scan during A -> B keeps disk registry.json on A; once + // the directory is readable again, the next refresh compares against disk A and records A. + const scanDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-scan-error-", + }); + const scanRegistryDir = `${scanDir}/acp-registry`; + const scanRegistryPath = `${scanRegistryDir}/registry.json`; + const scanBaselinesPath = `${scanRegistryDir}/legacy-baselines.json`; + const scanToolsDir = `${scanDir}/tools`; + const scanLegacyExe = `${scanToolsDir}/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(scanLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(scanLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(scanLegacyExe, 0o755); + yield* fileSystem.makeDirectory(scanRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + scanRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + let failToolsScan = true; + const flakyScanFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + failToolsScan && dirPath === scanToolsDir + ? fileSystem.readDirectory(scanLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + upstream = binaryAgent("1.0.0", archiveBUrl); + const scanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: scanDir, + toolsDir: scanToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, flakyScanFs)); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveAUrl); + expect(yield* fileSystem.exists(scanBaselinesPath)).toBe(false); + + failToolsScan = false; + yield* scanResolver.invalidateIndex(); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveBUrl); + expect(yield* fileSystem.readFileString(scanBaselinesPath)).toContain(archiveAUrl); + const restartedScanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: scanDir, + toolsDir: scanToolsDir, + registryUrl, + }); + const resolvedAfterScanRecovery = yield* restartedScanResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterScanRecovery.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 3. A corrupt legacy-baselines.json is copied aside and rebuilt cleanly so disk registry + // updates do not freeze, unrecoverable legacy slots are marked unknown rather than trusted, + // and uninstallManagedBinary prunes removed agents from disk. const corruptDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-corrupt-", }); @@ -4024,6 +4106,47 @@ describe("AcpRegistrySupport", () => { const otherSlotKey = "other-agent\u00001.0.0\u0000linux-x86_64"; expect(rebuiltBaselines[exampleSlotKey]).toContain(archiveAUrl); + // When legacy-baselines.json corrupts AFTER registry.json already moved to same-version B + // and the server restarts (comparing B vs B), rebuilding must mark the legacy slot unknown + // so resolve() installs B instead of running legacy A as B. + const unrecoverableDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-unrecoverable-", + }); + const unrecoverableRegistryDir = `${unrecoverableDir}/acp-registry`; + const unrecoverableBaselinesPath = `${unrecoverableRegistryDir}/legacy-baselines.json`; + const unrecoverableLegacyExe = `${unrecoverableDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(unrecoverableLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(unrecoverableLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(unrecoverableLegacyExe, 0o755); + yield* fileSystem.makeDirectory(unrecoverableRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + `${unrecoverableRegistryDir}/registry.json`, + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), + ); + yield* fileSystem.writeFileString(unrecoverableBaselinesPath, "{corrupt"); + + upstream = binaryAgent("1.0.0", archiveBUrl); + const unrecoverableResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unrecoverableDir, + toolsDir: `${unrecoverableDir}/tools`, + registryUrl, + }); + yield* unrecoverableResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${unrecoverableBaselinesPath}.corrupt`)).toBe( + "{corrupt", + ); + const unknownBaselines = JSON.parse( + yield* fileSystem.readFileString(unrecoverableBaselinesPath), + ) as Record; + expect(unknownBaselines[exampleSlotKey]).toBe("unknown"); + const resolvedAfterCorruptRebuild = yield* unrecoverableResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterCorruptRebuild.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + // Add another agent's baseline entry, uninstall example-agent, and verify only example-agent is pruned. rebuiltBaselines[otherSlotKey] = "other-baseline"; yield* fileSystem.writeFileString(corruptBaselinesPath, JSON.stringify(rebuiltBaselines)); @@ -4047,6 +4170,9 @@ describe("AcpRegistrySupport", () => { HttpClientResponse.fromWeb(request, new Response(makeRegistry(upstream))), ); } + if (countArchiveRequests) { + archiveRequestsDuringLockedSlot += 1; + } const bytes = request.url === archiveAUrl ? bytesA : request.url === archiveBUrl ? bytesB : bytesC; return Effect.succeed( @@ -4092,8 +4218,9 @@ describe("AcpRegistrySupport", () => { const fileSystem = yield* FileSystem.FileSystem; const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - // 1. Post-retry concurrent removal: retry B fails with checksum_mismatch while the agent is - // concurrently removed from the index -> resolve() fails with agent_not_found without fallback. + // 1. Post-retry concurrent removal: initial A fails checksum_mismatch while the index + // advances to B, then recheck-retry B fails checksum_mismatch while the agent is removed -> + // resolve() rechecks after retry B and fails with agent_not_found instead of falling back. const removalDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-post-retry-remove-", }); @@ -4105,38 +4232,69 @@ describe("AcpRegistrySupport", () => { const v1Resolved = yield* removalResolver.resolve(settings(), "/workspace"); expect(v1Resolved.agent?.version).toBe("1.0.0"); - // Cache 2.0.0 archive A (which returns 503), then point upstream to failing 2.0.0 archive B. - upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl)]; + upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl, "0".repeat(64))]; yield* removalResolver.invalidateIndex(); yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; - yield* removalResolver.invalidateIndex(); + const aGate = { + url: archiveV2AUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; const bGate = { url: archiveV2BUrl, started: yield* Deferred.make(), release: yield* Deferred.make(), }; - downloadGate = bGate; + downloadGate = aGate; const resolveFiber = yield* removalResolver .resolve(settings(), "/workspace") .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(aGate.started); + + // Advance the index from A to B while A's download is in flight, then arm bGate. + upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + downloadGate = bGate; + yield* Deferred.succeed(aGate.release, undefined); yield* Deferred.await(bGate.started); - // Concurrently remove the agent from the registry index while retry B's download is in flight. + // Concurrently remove the agent while the recheck's own retry B download is in flight. upstreamAgents = []; yield* removalResolver.invalidateIndex(); yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* Deferred.succeed(bGate.release, undefined); expect((yield* Fiber.join(resolveFiber)).reason).toBe("agent_not_found"); - // 2. Archive extraction timeout maps to archive_invalid (falls back when a prior receipted - // version exists, and surfaces archive_invalid while releasing locks when none exists). + // 2. Both archive extraction and listing timeouts map to archive_invalid (falling back when + // a prior receipted version exists, and surfacing archive_invalid while releasing locks + // when none exists). let tarStartedGate: Deferred.Deferred | null = null; + let hangTarStage: "list" | "extract" = "extract"; const hangingTarSpawner = ChildProcessSpawner.make((command) => { if ( ChildProcess.isStandardCommand(command) && (command.command === "tar" || command.command.endsWith("/tar")) ) { + const firstArg = command.args[0]; + const isListing = typeof firstArg === "string" && firstArg.startsWith("-t"); + if (isListing && hangTarStage === "extract") { + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(new TextEncoder().encode("bin/example-agent\n")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + } const gate = tarStartedGate; tarStartedGate = null; return (gate === null ? Effect.void : Deferred.succeed(gate, undefined)).pipe( @@ -4170,6 +4328,7 @@ describe("AcpRegistrySupport", () => { upstreamAgents = [binaryAgent("3.0.0", archiveTarUrl)]; yield* timeoutFallbackResolver.invalidateIndex(); yield* timeoutFallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + hangTarStage = "extract"; tarStartedGate = yield* Deferred.make(); const tarWithFallback = tarStartedGate; const fallbackTimeoutFiber = yield* timeoutFallbackResolver @@ -4192,6 +4351,7 @@ describe("AcpRegistrySupport", () => { Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, hangingTarSpawner), Effect.provideService(SpawnExecutableResolution, (command) => command), ); + hangTarStage = "list"; tarStartedGate = yield* Deferred.make(); const tarWithoutFallback = tarStartedGate; const noFallbackTimeoutFiber = yield* noFallbackResolver @@ -4267,12 +4427,14 @@ describe("AcpRegistrySupport", () => { .resolve(settings(), "/workspace") .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(firstReceiptGate.started); - // Age installer1's lock so installer2 takes over and publishes the artifact slot first. + // Age installer1's lock and advance the clock past the 5-minute stale threshold explicitly + // so this check is independent of earlier clock adjustments. yield* fileSystem.utimes( `${concurrentDir}/tools/example-agent/1.2.3/linux-x86_64.lock`, 0, 0, ); + yield* TestClock.adjust("6 minutes"); const secondResult = yield* installer2.resolve(settings(), "/workspace"); expect(renameToArtifactCount).toBe(1); @@ -4292,11 +4454,6 @@ describe("AcpRegistrySupport", () => { ), ); } - if (request.url === archiveV2AUrl) { - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), - ); - } const respond = Effect.succeed( HttpClientResponse.fromWeb(request, new Response(binaryBytes.buffer as ArrayBuffer)), ); @@ -4314,6 +4471,135 @@ describe("AcpRegistrySupport", () => { ); }, ); + + it.effect( + "rejects reserved receipt command paths, ignores superseded broken primaries on inspect, and syncs receipt launch options for fallback", + () => { + const archiveAUrl = "https://registry.test/receipt-a.bin"; + const archiveBUrl = "https://registry.test/receipt-b.bin"; + const archiveFailUrl = "https://registry.test/receipt-fail.bin"; + const bytesA = new TextEncoder().encode("#!/bin/sh\necho receipt-a\n"); + const bytesB = new TextEncoder().encode("#!/bin/sh\necho receipt-b\n"); + const makeBinary = ( + version: string, + target: { + readonly archive: string; + readonly cmd: string; + readonly args?: ReadonlyArray; + readonly env?: Readonly>; + }, + ) => ({ + ...makeAgent({ binary: { "linux-x86_64": target } }), + version, + }); + let upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: ".t3-artifact.json" }); + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + // 1. A raw binary declaring .t3-artifact.json as its command fails with archive_invalid + // instead of letting the receipt overwrite the staged executable. + const reservedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-reserved-receipt-", + }); + const reservedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: reservedDir, + toolsDir: `${reservedDir}/tools`, + registryUrl, + }); + const reservedError = yield* reservedResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(reservedError.reason).toBe("archive_invalid"); + + // 2. A superseded primary executable that lost execute permission must not fail inspect() + // when the registry selects a different same-version artifact. + const supersededDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-superseded-inspect-", + }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + env: { STAGE: "initial" }, + }); + const supersededResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: `${supersededDir}/tools`, + registryUrl, + }); + const installedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(installedA.spawn.args).toEqual(["--v1"]); + expect(installedA.spawn.env?.STAGE).toBe("initial"); + + // 3. Updating args/env on the same binary syncs the existing receipt so a later fallback + // launches with the last resolved args and env. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const syncedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(syncedA.spawn.command).toBe(installedA.spawn.command); + expect(syncedA.spawn.args).toEqual(["--v1", "--updated"]); + expect(syncedA.spawn.env?.STAGE).toBe("updated"); + + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(fallbackA.fallback).toBe(true); + expect(fallbackA.agent?.version).toBe("1.0.0"); + expect(fallbackA.spawn.args).toEqual(["--v1", "--updated"]); + expect(fallbackA.spawn.env?.STAGE).toBe("updated"); + + // Now remove execute permission on primary A and swap same-version 1.0.0 to archive B: + // inspect() must stay ready so resolve() can install replacement B in a sibling slot. + yield* fileSystem.chmod(installedA.spawn.command, 0o644); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* supersededResolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.0.0", + }); + const installedB = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(installedB.spawn.command).not.toBe(installedA.spawn.command); + expect(yield* fileSystem.readFileString(installedB.spawn.command)).toBe( + "#!/bin/sh\necho receipt-b\n", + ); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(upstream))), + ); + } + if (request.url === archiveFailUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ); + } + const bytes = request.url === archiveAUrl ? bytesA : bytesB; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)), + ); + }), + ), + ); + }, + ); }); describe("acpRegistryManagedBinaryDirectories", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 2068c15fba632..f7f134d981f5d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -671,6 +671,7 @@ export class AcpRegistryCatalog extends Context.Service< readonly maxAgeMs: number; readonly failureBackoffMs: number; }) => Effect.Effect; + readonly currentIndexRevision?: () => Effect.Effect; readonly invalidateIndex: () => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, @@ -720,10 +721,15 @@ const UNPACKING_AGENT_IDS: ReadonlySet = new Set(["antigravity-acp"]); const INSTALL_LOCK_RETRY_COUNT = 300; const INSTALL_LOCK_RETRY_DELAY = "100 millis"; const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; +const LEGACY_BASELINES_LOCK_RETRY_COUNT = 20; +const LEGACY_BASELINES_LOCK_STALE_MS = 10 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; const BINARY_LEGACY_BASELINES_FILENAME = "legacy-baselines.json"; +// Sentinel recorded for unrecoverable unreceipted slots when rebuilding a corrupt baselines file; +// never equals binaryArtifactIdentityKey (which is always JSON) so the slot must be reinstalled. +const LEGACY_BASELINE_UNKNOWN = "unknown"; const BINARY_ARTIFACT_SLOT_HASH_LENGTH = 12; const DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS = 60 * 1_000; @@ -1069,6 +1075,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct invalidationGeneration: 0, }); const registrySemaphore = yield* Semaphore.make(1); + const legacyBaselinesSemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. const installPermits = new Map(); const withInstallPermit = (agentId: string) => { @@ -1336,10 +1343,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return { registry, text: collected.text }; }); - const acquireFileLock = Effect.fn("AcpRegistryCatalog.acquireInstallLock")(function* ( + const acquireFileLock = Effect.fn("AcpRegistryCatalog.acquireFileLock")(function* ( lockPath: string, + options?: { + readonly retryCount?: number; + readonly staleMs?: number; + }, ) { - for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { + const retryCount = options?.retryCount ?? INSTALL_LOCK_RETRY_COUNT; + const staleMs = options?.staleMs ?? INSTALL_LOCK_STALE_MS; + for (let attempt = 0; attempt < retryCount; attempt += 1) { const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( Effect.as(true), Effect.catchIf( @@ -1351,7 +1364,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const now = yield* Clock.currentTimeMillis; const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); const mtime = Option.flatMap(lockInfo, (info) => info.mtime); - if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { + if (Option.isSome(mtime) && now - mtime.value.getTime() > staleMs) { yield* fileSystem.remove(lockPath, { force: true }); continue; } @@ -1363,6 +1376,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); }); + const withFileLock = ( + lockPath: string, + effect: Effect.Effect, + options?: { + readonly retryCount?: number; + readonly staleMs?: number; + }, + ) => + Effect.acquireUseRelease( + acquireFileLock(lockPath, options), + () => effect, + () => fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore), + ); + const writeLegacyBaselinesAtomically = (baselines: Readonly>) => random.uuidV4().pipe( Effect.flatMap((id) => { @@ -1377,19 +1404,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ); - const withLegacyBaselinesLock = (effect: Effect.Effect) => { - const lockPath = `${legacyBaselinesPath}.lock`; - return fileSystem - .makeDirectory(registryDirectory, { recursive: true }) - .pipe( - Effect.andThen(acquireFileLock(lockPath)), + const withLegacyBaselinesLock = (effect: Effect.Effect) => + legacyBaselinesSemaphore.withPermits(1)( + fileSystem.makeDirectory(registryDirectory, { recursive: true }).pipe( Effect.andThen( - effect.pipe( - Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), - ), + withFileLock(`${legacyBaselinesPath}.lock`, effect, { + retryCount: LEGACY_BASELINES_LOCK_RETRY_COUNT, + staleMs: LEGACY_BASELINES_LOCK_STALE_MS, + }), ), - ); - }; + ), + ); const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( inMemoryPrevious: AcpRegistryIndex | undefined, @@ -1397,37 +1422,48 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) { if (platformTarget === undefined) return true; const candidates = resolveAcpRegistryPlatformTargetCandidates(platformTarget); - const listDirectories = (directory: string) => - fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): Array => [])); - const unreceiptedLegacySlots: Array<{ - readonly agentId: string; - readonly encodedVersion: string; - readonly candidateTarget: AcpRegistryPlatformTarget; - readonly slotKey: string; - }> = []; - for (const agentId of yield* listDirectories(installsDirectory)) { - const agentRoot = path.join(installsDirectory, agentId); - for (const encodedVersion of yield* listDirectories(agentRoot)) { - const versionRoot = path.join(agentRoot, encodedVersion); - for (const candidateTarget of candidates) { - const installRoot = path.join(versionRoot, candidateTarget); - const installExists = yield* fileSystem - .exists(installRoot) - .pipe(Effect.orElseSucceed(() => false)); - if (!installExists) continue; - const hasReceipt = yield* fileSystem - .exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) - .pipe(Effect.orElseSucceed(() => false)); - if (hasReceipt) continue; - unreceiptedLegacySlots.push({ - agentId, - encodedVersion, - candidateTarget, - slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), - }); + const readDirectoryOrMissing = (directory: string) => + fileSystem.readDirectory(directory).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed>([]), + ), + ); + const scanUnreceiptedLegacySlots = Effect.gen(function* () { + const slots: Array<{ + readonly agentId: string; + readonly encodedVersion: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly slotKey: string; + }> = []; + for (const agentId of yield* readDirectoryOrMissing(installsDirectory)) { + const agentRoot = path.join(installsDirectory, agentId); + for (const encodedVersion of yield* readDirectoryOrMissing(agentRoot)) { + const versionRoot = path.join(agentRoot, encodedVersion); + for (const candidateTarget of candidates) { + const installRoot = path.join(versionRoot, candidateTarget); + if (!(yield* fileSystem.exists(installRoot))) continue; + if (yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME))) + continue; + slots.push({ + agentId, + encodedVersion, + candidateTarget, + slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), + }); + } } } + return slots; + }); + const scanResult = yield* Effect.result(scanUnreceiptedLegacySlots); + if (Result.isFailure(scanResult)) { + yield* Effect.logDebug( + "Could not scan managed ACP binary directories for legacy baselines; keeping existing disk registry cache.", + ); + return false; } + const unreceiptedLegacySlots = scanResult.success; if (unreceiptedLegacySlots.length === 0) return true; const recordDivergingInMemory = Effect.fn("AcpRegistryCatalog.recordDivergingLegacyBaselines")( @@ -1441,9 +1477,38 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return true; }); if (unpersistedSlots.length === 0) { - return { newBaselines: {} as Record, hasUpdates: false }; + return { + newBaselines: {} as Record, + hasUpdates: false, + readError: false, + }; + } + // Prefer the on-disk registry cache over in-memory state so a recovery refresh after a + // previous skipped disk write still compares against the index persisted on disk. + const diskIndexResult = yield* fileSystem.readFileString(registryCachePath).pipe( + Effect.flatMap((text) => + decodeRegistryText(text).pipe( + Effect.map((index) => ({ status: "ok" as const, index })), + Effect.orElseSucceed(() => ({ status: "missing" as const })), + ), + ), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" + ? ({ status: "missing" as const } as const) + : ({ status: "io_error" as const } as const), + ), + ), + ); + if (diskIndexResult.status === "io_error") { + return { + newBaselines: {} as Record, + hasUpdates: false, + readError: true, + }; } - const previousIndex = inMemoryPrevious ?? Option.getOrUndefined(yield* readCachedRegistry); + const previousIndex = + diskIndexResult.status === "ok" ? diskIndexResult.index : inMemoryPrevious; const previousById = new Map( (previousIndex?.agents ?? []).map((agent) => [agent.id, agent] as const), ); @@ -1481,7 +1546,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct newBaselines[slot.slotKey] = previousKey; hasUpdates = true; } - return { newBaselines, hasUpdates }; + return { newBaselines, hasUpdates, readError: false }; + }, + ); + + const preserveAndFail = Effect.fn("AcpRegistryCatalog.preserveLegacyBaselinesOnError")( + function* (existingBaselines: Readonly>, reason: string) { + yield* recordDivergingInMemory(existingBaselines); + yield* Effect.logDebug(reason); + return false; }, ); @@ -1496,34 +1569,42 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return true; } if (initialDisk.status === "io_error") { - // Preserve diverging legacy baselines in memory across transient read failures so a later - // recovery refresh still writes artifact A instead of comparing B against B. - yield* recordDivergingInMemory({}); - return false; + return yield* preserveAndFail( + {}, + "Could not read ACP Registry legacy baselines; keeping existing disk registry cache.", + ); } return yield* withLegacyBaselinesLock( Effect.gen(function* () { const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); if (disk.status === "io_error") { - yield* recordDivergingInMemory({}); - return false; + return yield* preserveAndFail( + {}, + "Could not read ACP Registry legacy baselines; keeping existing disk registry cache.", + ); } - let baseBaselines: Readonly>; - let mustRewrite = false; - if (disk.status === "corrupt") { - // Quarantine a corrupt baselines file and rebuild cleanly so disk registry updates do not freeze. + const isCorrupt = disk.status === "corrupt"; + const baseBaselines: Readonly> = isCorrupt ? {} : disk.baselines; + const { newBaselines, hasUpdates, readError } = + yield* recordDivergingInMemory(baseBaselines); + if (readError) return false; + if (!hasUpdates && !isCorrupt) return true; + const mergedBaselines: Record = { ...baseBaselines, ...newBaselines }; + if (isCorrupt) { + // Copy the corrupt bytes aside before atomically replacing legacy-baselines.json so there + // is no missing-file window, and mark any unrecoverable legacy slot as unknown so a + // rebuilt file never treats an unverified pre-receipt install as matching the new target. yield* fileSystem - .rename(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) + .copyFile(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) .pipe(Effect.ignore); - baseBaselines = {}; - mustRewrite = true; - } else { - baseBaselines = disk.baselines; + for (const slot of unreceiptedLegacySlots) { + if (mergedBaselines[slot.slotKey] === undefined) { + mergedBaselines[slot.slotKey] = LEGACY_BASELINE_UNKNOWN; + legacyBaselineBySlotKey.set(slot.slotKey, LEGACY_BASELINE_UNKNOWN); + } + } } - const { newBaselines, hasUpdates } = yield* recordDivergingInMemory(baseBaselines); - if (!hasUpdates && !mustRewrite) return true; - const mergedBaselines = { ...baseBaselines, ...newBaselines }; return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( Effect.as(true), Effect.catch(() => @@ -1535,13 +1616,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ).pipe( Effect.catch(() => - recordDivergingInMemory(initialDisk.status === "ok" ? initialDisk.baselines : {}).pipe( - Effect.andThen( - Effect.logDebug( - "Could not lock ACP Registry legacy baselines; keeping existing disk registry cache.", - ), - ), - Effect.as(false), + preserveAndFail( + initialDisk.status === "ok" ? initialDisk.baselines : {}, + "Could not lock ACP Registry legacy baselines; keeping existing disk registry cache.", ), ), ); @@ -2225,15 +2302,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); - const isCachedBinarySlotMatching = Effect.fn("AcpRegistryCatalog.isCachedBinarySlotMatching")( + const readMatchingBinaryReceipt = Effect.fn("AcpRegistryCatalog.readMatchingBinaryReceipt")( function* (root: string, executablePath: string, target: typeof AcpRegistryBinaryTarget.Type) { if (!(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false)))) { - return false; + return Option.none(); } const receiptPath = path.join(root, BINARY_ARTIFACT_RECEIPT_FILENAME); const rawReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); const decoded = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); - return Option.isSome(decoded) && binaryArtifactReceiptMatches(decoded.value, target); + return Option.isSome(decoded) && binaryArtifactReceiptMatches(decoded.value, target) + ? Option.some(decoded.value) + : Option.none(); }, ); @@ -2283,18 +2362,28 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct paths: NonNullable>, target: typeof AcpRegistryBinaryTarget.Type, ) { - if ( - yield* isCachedBinarySlotMatching(paths.artifactRoot, paths.artifactExecutablePath, target) - ) { + const artifactReceipt = yield* readMatchingBinaryReceipt( + paths.artifactRoot, + paths.artifactExecutablePath, + target, + ); + if (Option.isSome(artifactReceipt)) { return Option.some({ root: paths.artifactRoot, executablePath: paths.artifactExecutablePath, + receipt: artifactReceipt.value, }); } - if (yield* isCachedBinarySlotMatching(paths.installRoot, paths.executablePath, target)) { + const primaryReceipt = yield* readMatchingBinaryReceipt( + paths.installRoot, + paths.executablePath, + target, + ); + if (Option.isSome(primaryReceipt)) { return Option.some({ root: paths.installRoot, executablePath: paths.executablePath, + receipt: primaryReceipt.value, }); } if (yield* isLegacyBinarySlotEligible(paths, target)) { @@ -2303,9 +2392,44 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct executablePath: paths.executablePath, }); } - return Option.none<{ readonly root: string; readonly executablePath: string }>(); + return Option.none<{ + readonly root: string; + readonly executablePath: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }>(); }); + const syncReceiptLaunchOptions = Effect.fn("AcpRegistryCatalog.syncReceiptLaunchOptions")( + function* ( + slot: { + readonly root: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }, + agent: AcpRegistryAgent, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if (slot.receipt === undefined) return; + const sameArgs = Equal.equals(slot.receipt.args ?? [], target.args ?? []); + const sameEnv = Equal.equals(slot.receipt.env ?? {}, target.env ?? {}); + if (sameArgs && sameEnv) return; + const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); + yield* random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; + return fileSystem + .writeFileString(temporaryPath, encodeBinaryArtifactReceipt(agent, target)) + .pipe( + Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), + Effect.ensuring( + fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), + ), + ); + }), + Effect.ignore, + ); + }, + ); + const installBinary = Effect.fn("AcpRegistryCatalog.installBinary")(function* ( agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type, @@ -2324,8 +2448,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const { commandSegments, installRoot, artifactRoot } = paths; - const validateCachedSlot = (slot: { readonly root: string; readonly executablePath: string }) => + const validateCachedSlot = (slot: { + readonly root: string; + readonly executablePath: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }) => assertExecutableInRoot(slot.root, slot.executablePath).pipe( + Effect.tap(() => syncReceiptLaunchOptions(slot, agent, target)), Effect.mapError( (cause) => new AcpRegistryError({ @@ -2353,213 +2482,234 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); const lockPath = `${installRoot}.lock`; - yield* acquireFileLock(lockPath).pipe( - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "install_failed", - detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`, - cause, - }), - ), - ); - return yield* Effect.gen(function* () { - const lockedSlot = yield* findMatchingBinarySlot(paths, target); - if (Option.isSome(lockedSlot)) { - return yield* validateCachedSlot(lockedSlot.value); - } - const primaryExists = yield* fileSystem - .exists(installRoot) - .pipe(Effect.orElseSucceed(() => false)); - // Keep an existing primary directory intact for active sessions (and Windows file locks) - // by installing same-version replacements into an immutable artifact-scoped sibling slot. - const destinationRoot = primaryExists ? artifactRoot : installRoot; - const destinationExecutable = path.join(destinationRoot, ...commandSegments); - const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ - directory: path.dirname(installRoot), - prefix: `.${agent.id}-install-`, - }); - if ( - destinationRoot === artifactRoot && - (yield* fileSystem.exists(artifactRoot).pipe(Effect.orElseSucceed(() => false))) - ) { - // Under a freshly acquired lock after findMatchingBinarySlot returned None, an existing - // artifactRoot is a broken/incomplete slot (e.g., deleted executable). Move it into the - // scoped temp directory so promotion can publish cleanly without a post-download TOCTOU. - yield* fileSystem - .rename(artifactRoot, path.join(temporaryRoot, "replaced-broken-slot")) - .pipe(Effect.ignore); - } - const extractionRoot = path.join(temporaryRoot, "extracted"); - yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); - const kind = archiveKind(target.archive); - const archivePath = path.join(temporaryRoot, archiveFileName(kind)); - const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.mapError( - (cause) => - new AcpRegistryError({ - reason: "download_failed", - detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, - cause, - }), - ), - Effect.timeoutOrElse({ - duration: ARCHIVE_REQUEST_TIMEOUT, - orElse: () => - Effect.fail( + return yield* withFileLock( + lockPath, + Effect.gen(function* () { + const lockedSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(lockedSlot)) { + return yield* validateCachedSlot(lockedSlot.value); + } + const primaryExists = yield* fileSystem + .exists(installRoot) + .pipe(Effect.orElseSucceed(() => false)); + // Keep an existing primary directory intact for active sessions (and Windows file locks) + // by installing same-version replacements into an immutable artifact-scoped sibling slot. + const destinationRoot = primaryExists ? artifactRoot : installRoot; + const destinationExecutable = path.join(destinationRoot, ...commandSegments); + const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ + directory: path.dirname(installRoot), + prefix: `.${agent.id}-install-`, + }); + if ( + destinationRoot === artifactRoot && + (yield* fileSystem.exists(artifactRoot).pipe(Effect.orElseSucceed(() => false))) + ) { + // Under a freshly acquired lock after findMatchingBinarySlot returned None, an existing + // artifactRoot is a broken/incomplete slot (e.g., deleted executable). Move it aside + // before downloading; fail fast if moving fails (e.g., locked files on Windows) instead + // of wasting a full archive download. + yield* fileSystem + .rename(artifactRoot, path.join(temporaryRoot, "replaced-broken-slot")) + .pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.void, + ), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "install_failed", + detail: `Could not replace broken ACP Registry install slot for ${agent.id}.`, + cause, + }), + ), + ); + } + const extractionRoot = path.join(temporaryRoot, "extracted"); + yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); + const kind = archiveKind(target.archive); + const archivePath = path.join(temporaryRoot, archiveFileName(kind)); + const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.mapError( + (cause) => new AcpRegistryError({ reason: "download_failed", - detail: `Timed out downloading ACP Registry agent ${agent.id} ${agent.version}.`, - }), - ), - }), - ); - // Stream hashes to avoid buffering large archives; Effect Crypto requires a whole buffer. - const hash = sha256.create(); - let downloadedBytes = 0; - yield* response.stream.pipe( - Stream.tap((chunk) => { - if (downloadedBytes + chunk.byteLength > MAX_ARCHIVE_BYTES) { - return Effect.fail( - new AcpRegistryError({ - reason: "archive_invalid", - detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, + detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, + cause, }), + ), + Effect.timeoutOrElse({ + duration: ARCHIVE_REQUEST_TIMEOUT, + orElse: () => + Effect.fail( + new AcpRegistryError({ + reason: "download_failed", + detail: `Timed out downloading ACP Registry agent ${agent.id} ${agent.version}.`, + }), + ), + }), + ); + // Stream hashes to avoid buffering large archives; Effect Crypto requires a whole buffer. + const hash = sha256.create(); + let downloadedBytes = 0; + yield* response.stream.pipe( + Stream.tap((chunk) => { + if (downloadedBytes + chunk.byteLength > MAX_ARCHIVE_BYTES) { + return Effect.fail( + new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, + }), + ); + } + downloadedBytes += chunk.byteLength; + hash.update(chunk); + return Effect.void; + }), + Stream.run(fileSystem.sink(archivePath)), + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "download_failed", + detail: `Could not save ACP Registry agent ${agent.id} ${agent.version}.`, + cause, + }), + ), + Effect.timeoutOrElse({ + duration: ARCHIVE_REQUEST_TIMEOUT, + orElse: () => + Effect.fail( + new AcpRegistryError({ + reason: "download_failed", + detail: `Timed out reading ACP Registry agent ${agent.id} download.`, + }), + ), + }), + ); + if (target.sha256 !== undefined) { + const actual = Hex.encode(hash.digest()); + if (actual !== target.sha256.toLowerCase()) { + return yield* new AcpRegistryError({ + reason: "checksum_mismatch", + detail: `ACP Registry agent ${agent.id} download did not match its declared SHA-256.`, + }); + } + } + + if (kind === "raw") { + const targetPath = path.join(extractionRoot, ...commandSegments); + yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); + yield* fileSystem.rename(archivePath, targetPath); + } else { + const tarCommand = + platformTarget === "windows-aarch64" && + paths.platformTarget === "windows-x86_64" && + kind === "zip" + ? cliArchiveTarCommand(platform, hostEnvironment) + : "tar"; + const listArgs = + kind === "tar_gz" + ? ["-tzf", archivePath] + : kind === "tar_bz2" + ? ["-tjf", archivePath] + : platform === "win32" + ? ["-tf", archivePath] + : undefined; + const listingOptions = { + maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES, + timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", + nonZeroExitReason: "archive_invalid", + } as const; + const extractOptions = { + timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", + nonZeroExitReason: "archive_invalid", + } as const; + const entries = + listArgs === undefined + ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) + : yield* runCommand(tarCommand, listArgs, listingOptions); + if (!validateArchiveEntries(entries)) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, + }); + } + if (kind === "zip" && platform !== "win32") { + yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot], extractOptions); + } else { + const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; + yield* runCommand( + tarCommand, + [extractFlag, archivePath, "-C", extractionRoot], + extractOptions, ); } - downloadedBytes += chunk.byteLength; - hash.update(chunk); - return Effect.void; - }), - Stream.run(fileSystem.sink(archivePath)), - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "download_failed", - detail: `Could not save ACP Registry agent ${agent.id} ${agent.version}.`, - cause, - }), - ), - Effect.timeoutOrElse({ - duration: ARCHIVE_REQUEST_TIMEOUT, - orElse: () => - Effect.fail( - new AcpRegistryError({ - reason: "download_failed", - detail: `Timed out reading ACP Registry agent ${agent.id} download.`, - }), - ), - }), - ); - if (target.sha256 !== undefined) { - const actual = Hex.encode(hash.digest()); - if (actual !== target.sha256.toLowerCase()) { - return yield* new AcpRegistryError({ - reason: "checksum_mismatch", - detail: `ACP Registry agent ${agent.id} download did not match its declared SHA-256.`, - }); } - } - if (kind === "raw") { - const targetPath = path.join(extractionRoot, ...commandSegments); - yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); - yield* fileSystem.rename(archivePath, targetPath); - } else { - const tarCommand = - platformTarget === "windows-aarch64" && - paths.platformTarget === "windows-x86_64" && - kind === "zip" - ? cliArchiveTarCommand(platform, hostEnvironment) - : "tar"; - const listArgs = - kind === "tar_gz" - ? ["-tzf", archivePath] - : kind === "tar_bz2" - ? ["-tjf", archivePath] - : platform === "win32" - ? ["-tf", archivePath] - : undefined; - const listingOptions = { - maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES, - timeout: ARCHIVE_EXTRACT_TIMEOUT, - timeoutReason: "archive_invalid", - nonZeroExitReason: "archive_invalid", - } as const; - const extractOptions = { - timeout: ARCHIVE_EXTRACT_TIMEOUT, - timeoutReason: "archive_invalid", - nonZeroExitReason: "archive_invalid", - } as const; - const entries = - listArgs === undefined - ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) - : yield* runCommand(tarCommand, listArgs, listingOptions); - if (!validateArchiveEntries(entries)) { + const stagedExecutable = path.join(extractionRoot, ...commandSegments); + if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { return yield* new AcpRegistryError({ reason: "archive_invalid", - detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, + detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, }); } - if (kind === "zip" && platform !== "win32") { - yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot], extractOptions); - } else { - const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; - yield* runCommand( - tarCommand, - [extractFlag, archivePath, "-C", extractionRoot], - extractOptions, + yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); + yield* fileSystem + .writeFileString( + path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), + encodeBinaryArtifactReceipt(agent, target), + { flag: "wx" }, + ) + .pipe( + Effect.mapError((cause) => + isAlreadyExists(cause) + ? new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry archive for ${agent.id} contains a reserved '${BINARY_ARTIFACT_RECEIPT_FILENAME}' entry.`, + cause, + }) + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not write ACP Registry artifact receipt for ${agent.id}.`, + cause, + }), + ), ); + // Recheck right before promotion in case a stale-lock takeover let another installer publish + // a valid receipt-matching slot while this staging download was in flight. Never remove an + // existing destinationRoot before rename so a concurrent publisher's directory cannot be deleted. + const concurrentSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(concurrentSlot)) { + const validated = yield* assertExecutableInRoot( + concurrentSlot.value.root, + concurrentSlot.value.executablePath, + ).pipe(Effect.option); + if (Option.isSome(validated)) { + return validated.value; + } } - } - - const stagedExecutable = path.join(extractionRoot, ...commandSegments); - if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { - return yield* new AcpRegistryError({ - reason: "archive_invalid", - detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, - }); - } - yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); - yield* fileSystem.writeFileString( - path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), - encodeBinaryArtifactReceipt(agent, target), - ); - // Recheck right before promotion in case a stale-lock takeover let another installer publish - // a valid receipt-matching slot while this staging download was in flight. Never remove an - // existing destinationRoot before rename so a concurrent publisher's directory cannot be deleted. - const concurrentSlot = yield* findMatchingBinarySlot(paths, target); - if (Option.isSome(concurrentSlot)) { - const validated = yield* assertExecutableInRoot( - concurrentSlot.value.root, - concurrentSlot.value.executablePath, - ).pipe(Effect.option); - if (Option.isSome(validated)) { - return validated.value; - } - } - const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( - Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), - Effect.catch((renameError) => - findMatchingBinarySlot(paths, target).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.fail(renameError), - onSome: (slot) => assertExecutableInRoot(slot.root, slot.executablePath), - }), + const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( + Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), + Effect.catch((renameError) => + findMatchingBinarySlot(paths, target).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(renameError), + onSome: (slot) => assertExecutableInRoot(slot.root, slot.executablePath), + }), + ), + Effect.mapError(() => renameError), ), - Effect.mapError(() => renameError), ), - ), - ); - return promotedPath; - }).pipe( - Effect.scoped, - Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), + ); + return promotedPath; + }).pipe(Effect.scoped), + ).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -2767,18 +2917,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } yield* consumePreparedBinaryReservation(agent.id); const activeSlot = yield* findMatchingBinarySlot(paths, distribution.binaryTarget!); - const primaryExists = - Option.isNone(activeSlot) && - (yield* fileSystem - .exists(paths.executablePath) - .pipe(Effect.orElseSucceed(() => false))); - const slotToValidate = Option.isSome(activeSlot) - ? activeSlot.value - : primaryExists - ? { root: paths.installRoot, executablePath: paths.executablePath } - : undefined; // Any prepared version keeps the agent ready; resolve installs the current one on demand. - if (slotToValidate === undefined && !(yield* hasInstalledBinaryVersion(agent.id))) { + if (Option.isNone(activeSlot) && !(yield* hasInstalledBinaryVersion(agent.id))) { return { status: "unprepared", agentId, @@ -2787,10 +2927,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct indexRevision, } as const; } - if (slotToValidate !== undefined) { + if (Option.isSome(activeSlot)) { yield* assertExecutableInRoot( - slotToValidate.root, - slotToValidate.executablePath, + activeSlot.value.root, + activeSlot.value.executablePath, ).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) @@ -3300,30 +3440,43 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct legacyBaselineBySlotKey.delete(key); } } - if ( - yield* fileSystem - .exists(legacyBaselinesPath) - .pipe(Effect.orElseSucceed(() => false)) - ) { - yield* withLegacyBaselinesLock( - Effect.gen(function* () { - const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); - if (disk.status !== "ok") return; - const remaining = Object.fromEntries( - Object.entries(disk.baselines).filter(([key]) => !key.startsWith(prefix)), - ); - if (Object.keys(remaining).length !== Object.keys(disk.baselines).length) { - yield* writeLegacyBaselinesAtomically(remaining); - } - }), - ).pipe(Effect.ignore); - } } return { agentId: safeAgentId, removed }; }), ), ) .pipe( + Effect.tap(({ agentId: removedAgentId, removed }) => + removed + ? fileSystem.exists(legacyBaselinesPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasBaselinesFile) => + hasBaselinesFile + ? withLegacyBaselinesLock( + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile( + fileSystem, + legacyBaselinesPath, + ); + if (disk.status !== "ok") return; + const prefix = `${removedAgentId}\0`; + const remaining = Object.fromEntries( + Object.entries(disk.baselines).filter( + ([key]) => !key.startsWith(prefix), + ), + ); + if ( + Object.keys(remaining).length !== Object.keys(disk.baselines).length + ) { + yield* writeLegacyBaselinesAtomically(remaining); + } + }), + ).pipe(Effect.ignore) + : Effect.void, + ), + ) + : Effect.void, + ), Effect.catchTags({ ServerSettingsError: (cause) => new AcpRegistryError({ @@ -3335,10 +3488,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ); + const currentIndexRevision = () => + Ref.get(registryState).pipe(Effect.map((state) => state.indexRevision)); + return AcpRegistryCatalog.of({ search, prepare, refreshIndex, + currentIndexRevision, invalidateIndex, inspect, resolve, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 93a42dfeae223..bbc564b4be551 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -893,7 +893,7 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.entry).toBeNull(); }); - it("ignores live updates tagged for a different runtime identity than the cached entry", () => { + it("advances the incoming runtime's generation without replacing another runtime's cached entry", () => { const provider = providerWithModels( [{ id: "smodel", name: "Default", description: null }], "smodel", @@ -904,7 +904,7 @@ describe("acpRegistryEnrichmentCache", () => { entry: { provider, expiresAt: 1_000, launchIdentity: "runtime-v1" }, }; - const ignored = updateAcpRegistryEnrichmentCache({ + const updated = updateAcpRegistryEnrichmentCache({ cache, configuration: settledConfiguration, customModels: [], @@ -912,10 +912,11 @@ describe("acpRegistryEnrichmentCache", () => { runtimeIdentity: "runtime-v2", }); - expect(ignored).toBe(cache); - expect(ignored.invalidationGeneration).toBe(3); - expect(ignored.liveGenerationByRuntime.size).toBe(0); - expect(ignored.entry?.provider.models.map((m) => m.slug)).toEqual(["smodel"]); + expect(updated.entry).toBe(cache.entry); + expect(updated.invalidationGeneration).toBe(3); + expect(updated.liveGenerationByRuntime.get("runtime-v2")).toBe(1); + expect(updated.liveGenerationByRuntime.get("runtime-v1")).toBeUndefined(); + expect(updated.entry?.provider.models.map((m) => m.slug)).toEqual(["smodel"]); }); }); @@ -1635,6 +1636,7 @@ describe("AcpRegistryDriver registry recovery", () => { let remoteWebsite: string | undefined = undefined; let remoteExtraAgentVersion: string | undefined = undefined; let failArchiveDownload = false; + let inspectCalls = 0; let probeResolveAttempts = 0; let onFallbackResolved: (() => Effect.Effect) | null = null; let onEnrichmentEnd: ((exit: Exit.Exit) => void) | null = null; @@ -1697,6 +1699,10 @@ describe("AcpRegistryDriver registry recovery", () => { ); const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCalls += 1; + }).pipe(Effect.andThen(() => realCatalog.inspect(settings, environment))), resolve: (settings, cwd, environment) => Effect.sync(() => { if (environment?.MISE_OFFLINE === "1") { @@ -1926,6 +1932,22 @@ describe("AcpRegistryDriver registry recovery", () => { ); expect(metadataBackoffSnapshot.message).toBe(fallbackSnapshot.message); + // A follow-up refresh at the same revision inside backoff skips enrichment recheck + // completely because targetIndexRevision was updated to the new revision. + const inspectsBeforeSameRevBackoff = inspectCalls; + const sameRevBackoffDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(sameRevBackoffDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(sameRevBackoffDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeMetadataBackoff); + // Only checkProvider + auth.refreshMethods run; 0 enrichment inspectReadiness rechecks. + expect(inspectCalls).toBe(inspectsBeforeSameRevBackoff + 2); + // Once backoff expires, recovering without invalidating the cached 4.0.0 index still upgrades // because fallback did not acknowledge the 4.0.0 revision. failArchiveDownload = false; @@ -2832,6 +2854,7 @@ describe("AcpRegistryDriver registry recovery", () => { let remoteVersion = "1.0.0"; let failProbeSpawn = false; + let failProbeSpawnOnce = false; let inspectCalls = 0; let resolveGate: { readonly matchVersion: string; @@ -2909,7 +2932,8 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Deferred.succeed(gate.started, undefined); yield* Deferred.await(gate.release); } - if (environment?.MISE_OFFLINE === "1" && failProbeSpawn) { + if (environment?.MISE_OFFLINE === "1" && (failProbeSpawn || failProbeSpawnOnce)) { + failProbeSpawnOnce = false; return yield* new AcpRegistrySupport.AcpRegistryError({ reason: "install_failed", detail: `Simulated probe install failure for ${resolved.agent?.version ?? "unknown"}.`, @@ -3421,8 +3445,68 @@ describe("AcpRegistryDriver registry recovery", () => { const v4Recovered = Option.getOrThrow(yield* Fiber.join(recoveredToV4)); expect(v4Recovered.models.map((model) => model.slug)).toEqual(["v4-model-a", "v4-model-b"]); expect(v4Recovered.message).toBeUndefined(); + const v4Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v4Inspection.status).toBe("ready"); + const v4Identity = v4Inspection.status === "ready" ? v4Inspection.launchIdentity! : ""; + + // 7. Rolling the shared registry back to a previously retired version (3.0.0) allows a new + // 3.0.0 session's live state to reconcile the driver back to 3.0.0. + remoteVersion = "3.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rolledBackToV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v3-rollback-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-rollback-cmd" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(rolledBackToV3))).toBe(true); + + // 8. If a live update parks in pendingReconcileIdentity while an upgrade probe is in flight + // (while 3.0.0 is still displayed) and that probe fails, releasing inFlightProbeIdentity + // first lets the parked identity drain and reconcile automatically without another event. + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + const v4ParkedGate = { + matchVersion: "4.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v4ParkedGate; + failProbeSpawnOnce = true; + const v4ReconciledFromParked = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v4-parked-after-fail"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(v4ParkedGate.started); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v4-parked-after-fail" }], skills: [] }, + v4Identity, + ); + yield* Deferred.succeed(v4ParkedGate.release, undefined); + const reconciledFromParked = Option.getOrThrow(yield* Fiber.join(v4ReconciledFromParked)); + expect(reconciledFromParked.version).toBe("4.0.0"); + expect(reconciledFromParked.message).toBeUndefined(); - // 7. Disposing a driver instance removes its coordinator state and marks earlier metadata stale. + // 9. Disposing a driver instance removes its coordinator state and marks earlier metadata stale. const disposedInstanceId = ProviderInstanceId.make("acpRegistry_disposed_cleanup"); const disposedScope = yield* Scope.make(); let disposedMeta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta | null = null; diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index a425cea0effec..84eb85882a43b 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -151,9 +151,16 @@ export function updateAcpRegistryEnrichmentCache(input: { entryRuntimeIdentity !== null && entryRuntimeIdentity !== runtimeIdentity ) { - // Live configuration belongs to a different runtime than the cached probe; - // leave the cache untouched so an in-flight probe for the new runtime can finish. - return cache; + // Keep the cached entry for the older runtime intact, while advancing the + // incoming runtime's live epoch so an older in-flight probe for that + // incoming runtime cannot overwrite this newer live configuration. + return { + ...cache, + liveGenerationByRuntime: nextLiveGenerationByRuntime( + cache.liveGenerationByRuntime, + runtimeKey, + ), + }; } const provider = applyAcpRegistryLiveConfiguration( cache.entry.provider, @@ -1077,7 +1084,7 @@ export const AcpRegistryDriver: ProviderDriver(null); const latestCheckedReadiness = yield* Ref.make(null); const activeFallback = yield* Ref.make(null); - const retiredRuntimeIdentities = yield* Ref.make>(new Set()); + const retiredRuntimeIdentities = yield* Ref.make>(new Map()); const inspectReadiness = (options?: { readonly applySessionLiveState?: boolean; readonly seedActiveRuntimeIdentity?: boolean; @@ -1259,6 +1266,7 @@ export const AcpRegistryDriver: ProviderDriver 0; + const currentCatalogIndexRevision = catalog.currentIndexRevision?.() ?? Effect.succeed(0); const lastSeenIndexRevision = yield* Ref.make(0); const acknowledgeRevision = (revision: number) => Ref.update(lastSeenIndexRevision, (seen) => Math.max(seen, revision)); @@ -1475,7 +1483,18 @@ export const AcpRegistryDriver: ProviderDriver { if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; return Effect.gen(function* () { - if ((yield* Ref.get(retiredRuntimeIdentities)).has(incomingIdentity)) return; + const retiredAtRevision = (yield* Ref.get(retiredRuntimeIdentities)).get( + incomingIdentity, + ); + const currentRevision = + retiredAtRevision === undefined ? undefined : yield* currentCatalogIndexRevision; + if ( + retiredAtRevision !== undefined && + currentRevision !== undefined && + currentRevision <= retiredAtRevision + ) { + return; + } if ((yield* Ref.get(inFlightProbeIdentity)) === incomingIdentity) { yield* Ref.set(pendingReconcileIdentity, incomingIdentity); return; @@ -1502,6 +1521,22 @@ export const AcpRegistryDriver: ProviderDriver { + if (!retired.has(incomingIdentity)) return retired; + const next = new Map(retired); + next.set(incomingIdentity, stampRevision); + return next; + }); } }).pipe( Effect.ensuring( @@ -1567,7 +1602,8 @@ export const AcpRegistryDriver: ProviderDriver({ published: false, readiness: null }), + readonly publishedIdentity: string | null; + }>({ published: false, readiness: null, publishedIdentity: null }), onSome: ({ provider, launchIdentity, @@ -1581,237 +1617,225 @@ export const AcpRegistryDriver: ProviderDriver - liveSnapshotSemaphore - .withPermit( - Effect.gen(function* () { - const previousIdentity = yield* Ref.get(activeRuntimeIdentity); - const resolvedIdentity = - provider.installed && !probeFailed - ? runtimeIdentityFor(provider, launchIdentity) - : null; - const current = yield* Ref.get(enrichmentCache); - if (!isProbeStillCurrent(current, captured, resolvedIdentity)) { - return { - published: false, - readiness: null, - publishedIdentity: null, - }; - } - if (probeFailed && provider.installed && previousIdentity !== null) { - // The new runtime failed before resolving/starting; keep the last known - // working runtime's identity, version, models, and live state intact so - // running sessions survive across repeated refreshes. - const lastRuntime = yield* Ref.get(lastSuccessfulRuntime); - const isUpgradeFailure = - failedTargetLaunchIdentity !== null && - failedTargetLaunchIdentity !== previousIdentity; - const preservedBase: ServerProvider = - lastRuntime !== null && lastRuntime.identity === previousIdentity - ? (() => { - const { message: _previousMessage, ...base } = - lastRuntime.provider; - return { - ...base, - checkedAt: provider.checkedAt, - status: provider.status, - auth: - provider.auth.status === "unauthenticated" - ? provider.auth - : base.auth, - ...(provider.message !== undefined - ? { message: provider.message } - : {}), - }; - })() - : provider; - const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState( - preservedBase, - { - sessionRuntimeIdentity: previousIdentity, - requireMatchingRuntimeIdentity: false, - useLearnedModels: true, - persistLearnedModels: false, - }, - ); - const nextSnapshot = isUpgradeFailure - ? { - ...nextSnapshotRaw, - status: provider.status, - ...(provider.message !== undefined - ? { message: provider.message } - : {}), - } - : nextSnapshotRaw; - const published = yield* tryPublishSnapshot(nextSnapshot); - if (published) { - yield* Ref.set(expectedRuntimeIdentity, previousIdentity); - if (isUpgradeFailure) { - yield* Ref.set(failedUpgradeTarget, { - targetLaunchIdentity: failedTargetLaunchIdentity, - status: provider.status, - auth: provider.auth, - message: provider.message, - }); - } - } - return { - published, - readiness: published - ? { - snapshot: nextSnapshot, - launchIdentity: previousIdentity, - indexRevision, - probeFailed: true, - } - : null, - publishedIdentity: previousIdentity, - }; - } - const existingFallback = fallback ? yield* Ref.get(activeFallback) : null; - const fallbackMessage = - fallback && !fromCache - ? fallbackTargetVersion !== null && - provider.version !== null && - fallbackTargetVersion !== provider.version - ? `Could not install ${effectiveConfig.agentId} ${fallbackTargetVersion}; using installed ${provider.version}. Will retry on the next refresh.` - : "Could not install the latest agent update; using the previously installed version. Will retry on the next refresh." - : existingFallback?.message; - const effectiveMessage = fallback - ? (fallbackMessage ?? provider.message) - : provider.message; - const providerToPublish = - fallback && effectiveMessage !== undefined - ? { ...provider, message: effectiveMessage } + liveSnapshotSemaphore.withPermit( + Effect.gen(function* () { + const previousIdentity = yield* Ref.get(activeRuntimeIdentity); + const resolvedIdentity = + provider.installed && !probeFailed + ? runtimeIdentityFor(provider, launchIdentity) + : null; + const current = yield* Ref.get(enrichmentCache); + if (!isProbeStillCurrent(current, captured, resolvedIdentity)) { + return { + published: false, + readiness: null, + publishedIdentity: null, + }; + } + if (probeFailed && provider.installed && previousIdentity !== null) { + // The new runtime failed before resolving/starting; keep the last known + // working runtime's identity, version, models, and live state intact so + // running sessions survive across repeated refreshes. + const lastRuntime = yield* Ref.get(lastSuccessfulRuntime); + const isUpgradeFailure = + failedTargetLaunchIdentity !== null && + failedTargetLaunchIdentity !== previousIdentity; + const preservedBase: ServerProvider = + lastRuntime !== null && lastRuntime.identity === previousIdentity + ? (() => { + const { message: _previousMessage, ...base } = lastRuntime.provider; + return { + ...base, + checkedAt: provider.checkedAt, + status: provider.status, + auth: + provider.auth.status === "unauthenticated" + ? provider.auth + : base.auth, + ...(provider.message !== undefined + ? { message: provider.message } + : {}), + }; + })() : provider; - const runtimeChanged = - previousIdentity !== null && - resolvedIdentity !== null && - previousIdentity !== resolvedIdentity; - const { provider: nextSnapshotRaw, appliedLiveConfiguration } = - yield* withLiveRuntimeState(providerToPublish, { - sessionRuntimeIdentity: resolvedIdentity, - requireMatchingRuntimeIdentity: runtimeChanged, - useLearnedModels: !runtimeChanged, + const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState( + preservedBase, + { + sessionRuntimeIdentity: previousIdentity, + requireMatchingRuntimeIdentity: false, + useLearnedModels: true, persistLearnedModels: false, - }); - const nextSnapshot = - fallback && effectiveMessage !== undefined - ? { ...nextSnapshotRaw, message: effectiveMessage } - : nextSnapshotRaw; + }, + ); + const nextSnapshot = isUpgradeFailure + ? { + ...nextSnapshotRaw, + status: provider.status, + ...(provider.message !== undefined + ? { message: provider.message } + : {}), + } + : nextSnapshotRaw; const published = yield* tryPublishSnapshot(nextSnapshot); if (published) { - if (!providerToPublish.installed) { - yield* Ref.set(activeFallback, null); + yield* Ref.set(expectedRuntimeIdentity, previousIdentity); + if (isUpgradeFailure) { + yield* Ref.set(failedUpgradeTarget, { + targetLaunchIdentity: failedTargetLaunchIdentity, + status: provider.status, + auth: provider.auth, + message: provider.message, + }); + } + } + return { + published, + readiness: published + ? { + snapshot: nextSnapshot, + launchIdentity: previousIdentity, + indexRevision, + probeFailed: true, + } + : null, + publishedIdentity: published ? previousIdentity : null, + }; + } + const existingFallback = fallback ? yield* Ref.get(activeFallback) : null; + const fallbackMessage = + fallback && !fromCache + ? fallbackTargetVersion !== null && + provider.version !== null && + fallbackTargetVersion !== provider.version + ? `Could not install ${effectiveConfig.agentId} ${fallbackTargetVersion}; using installed ${provider.version}. Will retry on the next refresh.` + : "Could not install the latest agent update; using the previously installed version. Will retry on the next refresh." + : existingFallback?.message; + const effectiveMessage = fallback + ? (fallbackMessage ?? provider.message) + : provider.message; + const providerToPublish = + fallback && effectiveMessage !== undefined + ? { ...provider, message: effectiveMessage } + : provider; + const runtimeChanged = + previousIdentity !== null && + resolvedIdentity !== null && + previousIdentity !== resolvedIdentity; + const { provider: nextSnapshotRaw, appliedLiveConfiguration } = + yield* withLiveRuntimeState(providerToPublish, { + sessionRuntimeIdentity: resolvedIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: false, + }); + const nextSnapshot = + fallback && effectiveMessage !== undefined + ? { ...nextSnapshotRaw, message: effectiveMessage } + : nextSnapshotRaw; + const published = yield* tryPublishSnapshot(nextSnapshot); + if (published) { + if (!providerToPublish.installed) { + yield* Ref.set(activeFallback, null); + yield* Ref.set(failedUpgradeTarget, null); + yield* Ref.set(lastSuccessfulRuntime, null); + if (previousIdentity !== null || current.entry !== null) { + yield* clearLiveState(); + yield* invalidateEnrichmentCache; + } + yield* Ref.set(expectedRuntimeIdentity, null); + } else { + const previousLastSuccessful = yield* Ref.get(lastSuccessfulRuntime); + if (!probeFailed) { yield* Ref.set(failedUpgradeTarget, null); - yield* Ref.set(lastSuccessfulRuntime, null); - if (previousIdentity !== null || current.entry !== null) { - yield* clearLiveState(); - yield* invalidateEnrichmentCache; + } + if (fallback && !fromCache) { + const now = yield* Clock.currentTimeMillis; + const keepFailedAt = + existingFallback !== null && + existingFallback.targetLaunchIdentity === + fallbackTargetLaunchIdentity && + now >= existingFallback.failedAtMs && + now - existingFallback.failedAtMs < FALLBACK_RETRY_BACKOFF_MS; + yield* Ref.set(activeFallback, { + targetLaunchIdentity: fallbackTargetLaunchIdentity, + targetVersion: fallbackTargetVersion, + targetIndexRevision: fallbackTargetIndexRevision, + fallbackVersion: providerToPublish.version, + fallbackLaunchIdentity: launchIdentity, + failedAtMs: keepFailedAt ? existingFallback.failedAtMs : now, + message: + fallbackMessage ?? + existingFallback?.message ?? + "Using the previously installed version.", + }); + } else if (!fallback && !probeFailed) { + yield* Ref.set(activeFallback, null); + } + if (runtimeChanged) { + yield* clearLiveState({ preserveRuntimeIdentity: resolvedIdentity }); + const retiredAtRevision = + indexRevision ?? (yield* currentCatalogIndexRevision); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + const next = new Map(retired); + // Retire only a runtime that actually succeeded; a never-installed + // target replaced during cold fallback stays eligible to reconcile. + if (previousLastSuccessful?.identity === previousIdentity) { + next.set(previousIdentity, retiredAtRevision); + } + next.delete(resolvedIdentity); + return next; + }); + if (appliedLiveConfiguration) { + yield* Ref.set(learnedModels, nextSnapshot.models); } - yield* Ref.set(expectedRuntimeIdentity, null); + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); } else { - const previousLastSuccessful = yield* Ref.get(lastSuccessfulRuntime); - if (!probeFailed) { - yield* Ref.set(failedUpgradeTarget, null); + if ( + appliedLiveConfiguration && + nextSnapshot.models !== providerToPublish.models + ) { + yield* Ref.set(learnedModels, nextSnapshot.models); } - if (fallback && !fromCache) { - const now = yield* Clock.currentTimeMillis; - const keepFailedAt = - existingFallback !== null && - existingFallback.targetLaunchIdentity === - fallbackTargetLaunchIdentity && - now >= existingFallback.failedAtMs && - now - existingFallback.failedAtMs < FALLBACK_RETRY_BACKOFF_MS; - yield* Ref.set(activeFallback, { - targetLaunchIdentity: fallbackTargetLaunchIdentity, - targetVersion: fallbackTargetVersion, - targetIndexRevision: fallbackTargetIndexRevision, - fallbackVersion: providerToPublish.version, - fallbackLaunchIdentity: launchIdentity, - failedAtMs: keepFailedAt ? existingFallback.failedAtMs : now, - message: - fallbackMessage ?? - existingFallback?.message ?? - "Using the previously installed version.", - }); - } else if (!fallback && !probeFailed) { - yield* Ref.set(activeFallback, null); - } - if (runtimeChanged) { - yield* clearLiveState({ preserveRuntimeIdentity: resolvedIdentity }); + if (resolvedIdentity !== null) { + yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); yield* Ref.update(retiredRuntimeIdentities, (retired) => { - const next = new Set(retired); - // Retire only a runtime that actually succeeded; a never-installed - // target replaced during cold fallback stays eligible to reconcile. - if (previousLastSuccessful?.identity === previousIdentity) { - next.add(previousIdentity); - } + if (!retired.has(resolvedIdentity)) return retired; + const next = new Map(retired); next.delete(resolvedIdentity); return next; }); - if (appliedLiveConfiguration) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); - } else { - if ( - appliedLiveConfiguration && - nextSnapshot.models !== providerToPublish.models - ) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - if (resolvedIdentity !== null) { - yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); - yield* Ref.update(retiredRuntimeIdentities, (retired) => { - if (!retired.has(resolvedIdentity)) return retired; - const next = new Set(retired); - next.delete(resolvedIdentity); - return next; - }); - } - yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); - } - if (!probeFailed && resolvedIdentity !== null) { - const { message: _fallbackMsg, ...cleanProvider } = nextSnapshotRaw; - yield* Ref.set(lastSuccessfulRuntime, { - identity: resolvedIdentity, - provider: fallback ? cleanProvider : nextSnapshotRaw, - }); } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } + if (!probeFailed && resolvedIdentity !== null) { + const { message: _fallbackMsg, ...cleanProvider } = nextSnapshotRaw; + yield* Ref.set(lastSuccessfulRuntime, { + identity: resolvedIdentity, + provider: fallback ? cleanProvider : nextSnapshotRaw, + }); } } - return { - published, - readiness: published - ? { - snapshot: providerToPublish, - launchIdentity, - indexRevision, - ...(fallback - ? { - fallback: true, - fallbackTargetIndexRevision, - } - : {}), - ...(probeFailed ? { probeFailed: true } : {}), - } - : null, - publishedIdentity: resolvedIdentity, - }; - }), - ) - .pipe( - Effect.tap(({ publishedIdentity }) => - Ref.getAndSet(pendingReconcileIdentity, null).pipe( - Effect.flatMap((pending) => - pending !== null && pending !== publishedIdentity - ? maybeReconcileUnmatchedRuntime(pending) - : Effect.void, - ), - ), - ), - Effect.map(({ published, readiness }) => ({ published, readiness })), - ), + } + return { + published, + readiness: published + ? { + snapshot: providerToPublish, + launchIdentity, + indexRevision, + ...(fallback + ? { + fallback: true, + fallbackTargetIndexRevision, + } + : {}), + ...(probeFailed ? { probeFailed: true } : {}), + } + : null, + publishedIdentity: published ? resolvedIdentity : null, + }; + }), + ), }), ), Effect.ensuring( @@ -1819,6 +1843,16 @@ export const AcpRegistryDriver: ProviderDriver + Ref.getAndSet(pendingReconcileIdentity, null).pipe( + Effect.flatMap((pending) => + pending !== null && pending !== publishedIdentity + ? maybeReconcileUnmatchedRuntime(pending) + : Effect.void, + ), + ), + ), + Effect.map(({ published, readiness }) => ({ published, readiness })), ); }; const runWithLiveWatchers = (enrichment: Effect.Effect) => { From 19b576721f951e7ffa0e4c9168e14e70113d8bcb Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 16:33:16 +0000 Subject: [PATCH 17/28] fix(acp-registry): guard shared tools scans, interruptible fenced locks, and runtime reconciliation --- .../src/provider/AcpRegistryProbe.test.ts | 4 + docs/user/providers-acp.md | 4 +- .../src/server/AcpRegistrySupport.test.ts | 363 ++++++++++++- .../src/server/AcpRegistrySupport.ts | 440 +++++++++++---- .../src/server/auth.test.ts | 1 + .../src/server/driver.test.ts | 511 ++++++++++++++++++ .../src/server/driver.ts | 237 +++++--- 7 files changed, 1350 insertions(+), 210 deletions(-) diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 7d90942ebb74b..3bbd8a2732a41 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -366,6 +366,7 @@ describe("ACP Registry probe", () => { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -429,6 +430,7 @@ describe("ACP Registry probe", () => { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -500,6 +502,7 @@ await import(pathToFileURL(agentPath).href); search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -595,6 +598,7 @@ await import(pathToFileURL(agentPath).href); search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 7df448b0b71d1..573e8302d1ed8 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -55,8 +55,8 @@ T3 Code refreshes the Registry index in the background and automatically install prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while that agent is starting a session. If a newly published version of a T3-managed binary agent fails to download, verify, or unpack, T3 Code keeps running the newest previously installed version until -the update succeeds (agent versions installed by T3 Code releases before this fallback existed -cannot be used as fallback). Agents using **Executable override** keep running the configured executable—update those +the update succeeds (versions installed before T3 Code added this fallback can't be used for it). +Agents using **Executable override** keep running the configured executable—update those overrides directly on the server—while Registry refreshes can still pick up updated Registry metadata, arguments, and environment variables. Refreshing providers (in **Settings → Providers** on web and desktop, or **Refresh providers** in environment settings on mobile) requests a fresh diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 3798bbc279dba..5d0b1fa3a831c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Fiber from "effect/Fiber"; @@ -4014,8 +4015,49 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); - // 2b. An incomplete tools-directory scan during A -> B keeps disk registry.json on A; once - // the directory is readable again, the next refresh compares against disk A and records A. + // 2b. Non-directory files in the shared tools/ directory (e.g., tools/codex/active.json, + // tools/.DS_Store) must not break legacy baseline scanning or freeze disk registry.json. + const sharedToolsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-shared-tools-", + }); + const sharedRegistryDir = `${sharedToolsDir}/acp-registry`; + const sharedRegistryPath = `${sharedRegistryDir}/registry.json`; + const sharedBaselinesPath = `${sharedRegistryDir}/legacy-baselines.json`; + const sharedLegacyExe = `${sharedToolsDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(sharedLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(sharedLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(sharedLegacyExe, 0o755); + yield* fileSystem.makeDirectory(`${sharedToolsDir}/tools/codex`, { recursive: true }); + yield* fileSystem.writeFileString( + `${sharedToolsDir}/tools/codex/active.json`, + '{"version":"1.0.0"}', + ); + yield* fileSystem.writeFileString(`${sharedToolsDir}/tools/.DS_Store`, "finder"); + yield* fileSystem.makeDirectory(sharedRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + sharedRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + upstream = binaryAgent("1.0.0", archiveBUrl); + const sharedToolsResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: sharedToolsDir, + toolsDir: `${sharedToolsDir}/tools`, + registryUrl, + }); + yield* sharedToolsResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(sharedRegistryPath)).toContain(archiveBUrl); + expect(yield* fileSystem.readFileString(sharedBaselinesPath)).toContain(archiveAUrl); + const resolvedWithSharedTools = yield* sharedToolsResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedWithSharedTools.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 2c. An incomplete tools-directory scan during A -> B keeps disk registry.json on A AND + // blocks live resolution from launching legacy A as B even before the scan recovers; once + // readable again, the next refresh compares against disk A and records A. const scanDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-scan-error-", }); @@ -4050,6 +4092,49 @@ describe("AcpRegistrySupport", () => { expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveAUrl); expect(yield* fileSystem.exists(scanBaselinesPath)).toBe(false); + // Resolving BEFORE clearing the scan failure must install B instead of running legacy A. + const resolvedDuringScanFailure = yield* scanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringScanFailure.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // A transient I/O error reading registry.json during baseline discovery must also keep + // disk registry.json untouched rather than treating it as missing. + const regIoDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-reg-io-", + }); + const regIoRegistryDir = `${regIoDir}/acp-registry`; + const regIoRegistryPath = `${regIoRegistryDir}/registry.json`; + const regIoLegacyExe = `${regIoDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(regIoLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(regIoLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(regIoLegacyExe, 0o755); + yield* fileSystem.makeDirectory(regIoRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + regIoRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + const failRegistryReadFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === regIoRegistryPath + ? fileSystem.readFileString(regIoDir, encoding) + : fileSystem.readFileString(filePath, encoding), + }; + const regIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: regIoDir, + toolsDir: `${regIoDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failRegistryReadFs)); + yield* regIoResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(regIoRegistryPath)).toContain(archiveAUrl); + // Live resolution during an unreadable disk registry.json must also install B rather than + // launching the unverified legacy A executable. + const resolvedDuringRegIo = yield* regIoResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringRegIo.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + failToolsScan = false; yield* scanResolver.invalidateIndex(); yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4068,9 +4153,10 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); - // 3. A corrupt legacy-baselines.json is copied aside and rebuilt cleanly so disk registry - // updates do not freeze, unrecoverable legacy slots are marked unknown rather than trusted, - // and uninstallManagedBinary prunes removed agents from disk. + // 3. A corrupt legacy-baselines.json is copied aside and rebuilt cleanly without inferring + // provenance from an unverified cached registry index: even on a B -> C refresh after + // restart, the unreceipted slot is marked "unknown" so a later rollback to B installs B + // instead of executing legacy A as B. uninstallManagedBinary prunes removed agents. const corruptDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-corrupt-", }); @@ -4084,7 +4170,7 @@ describe("AcpRegistrySupport", () => { yield* fileSystem.makeDirectory(corruptRegistryDir, { recursive: true }); yield* fileSystem.writeFileString( corruptRegistryPath, - makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), ); yield* fileSystem.writeFileString(corruptBaselinesPath, "{not json"); @@ -4104,11 +4190,18 @@ describe("AcpRegistrySupport", () => { ) as Record; const exampleSlotKey = "example-agent\u00001.0.0\u0000linux-x86_64"; const otherSlotKey = "other-agent\u00001.0.0\u0000linux-x86_64"; - expect(rebuiltBaselines[exampleSlotKey]).toContain(archiveAUrl); + expect(rebuiltBaselines[exampleSlotKey]).toBe("unknown"); + + // Rolling back from C (2.0.0) to B (1.0.0) must install B instead of running legacy A as B. + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* corruptResolver.invalidateIndex(); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAfterRollback = yield* corruptResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAfterRollback.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); - // When legacy-baselines.json corrupts AFTER registry.json already moved to same-version B - // and the server restarts (comparing B vs B), rebuilding must mark the legacy slot unknown - // so resolve() installs B instead of running legacy A as B. + // Same check on B -> B after restart with a corrupt baseline file. const unrecoverableDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-unrecoverable-", }); @@ -4266,6 +4359,40 @@ describe("AcpRegistrySupport", () => { yield* Deferred.succeed(bGate.release, undefined); expect((yield* Fiber.join(resolveFiber)).reason).toBe("agent_not_found"); + // 1b. Multi-pass recheck retry: A fails checksum -> moves to B -> B fails checksum -> moves + // to valid C -> resolve() retries through B to C and succeeds with C. + upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const aGate2 = { + url: archiveV2AUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const bGate2 = { + url: archiveV2BUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + downloadGate = aGate2; + const multiRetryFiber = yield* removalResolver + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(aGate2.started); + upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + downloadGate = bGate2; + yield* Deferred.succeed(aGate2.release, undefined); + yield* Deferred.await(bGate2.started); + upstreamAgents = [binaryAgent("2.0.0", archivePlainUrl)]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(bGate2.release, undefined); + const multiRetried = yield* Fiber.join(multiRetryFiber); + expect(multiRetried.fallback).toBeUndefined(); + expect(multiRetried.agent?.version).toBe("2.0.0"); + // 2. Both archive extraction and listing timeouts map to archive_invalid (falling back when // a prior receipted version exists, and surfacing archive_invalid while releasing locks // when none exists). @@ -4338,7 +4465,7 @@ describe("AcpRegistrySupport", () => { yield* TestClock.adjust("5 minutes"); const fallbackOnTimeout = yield* Fiber.join(fallbackTimeoutFiber); expect(fallbackOnTimeout.fallback).toBe(true); - expect(fallbackOnTimeout.agent?.version).toBe("1.0.0"); + expect(fallbackOnTimeout.agent?.version).toBe("2.0.0"); const noFallbackDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-extract-timeout-", @@ -4473,7 +4600,7 @@ describe("AcpRegistrySupport", () => { ); it.effect( - "rejects reserved receipt command paths, ignores superseded broken primaries on inspect, and syncs receipt launch options for fallback", + "rejects reserved receipt command paths, ignores superseded broken primaries on inspect, persists launch options when receipt writes fail, and enforces interruptible token-owned locks", () => { const archiveAUrl = "https://registry.test/receipt-a.bin"; const archiveBUrl = "https://registry.test/receipt-b.bin"; @@ -4496,6 +4623,41 @@ describe("AcpRegistrySupport", () => { return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // Model POSIX mode bits in memory so Linux mode assertions work identically on Windows. + const modeOverrides = new Map(); + let failReceiptTempWrite = false; + let onStatPath: { + readonly matchPath: string; + readonly onHit: () => void; + } | null = null; + const posixModeFs: FileSystem.FileSystem = { + ...fileSystem, + chmod: (filePath, mode) => + Effect.sync(() => { + modeOverrides.set(filePath, mode); + }).pipe(Effect.andThen(fileSystem.chmod(filePath, mode).pipe(Effect.ignore))), + stat: (filePath) => + fileSystem.stat(filePath).pipe( + Effect.tap(() => + Effect.sync(() => { + if (onStatPath !== null && filePath === onStatPath.matchPath) { + onStatPath.onHit(); + } + }), + ), + Effect.map((info) => { + const override = modeOverrides.get(filePath); + return override === undefined + ? info + : { ...info, mode: (info.mode & ~0o777) | override }; + }), + ), + writeFileString: (filePath, data, options) => + failReceiptTempWrite && path.basename(filePath).startsWith(".t3-artifact.json.") + ? fileSystem.readFileString(path.dirname(filePath)).pipe(Effect.asVoid) + : fileSystem.writeFileString(filePath, data, options), + }; // 1. A raw binary declaring .t3-artifact.json as its command fails with archive_invalid // instead of letting the receipt overwrite the staged executable. @@ -4506,14 +4668,14 @@ describe("AcpRegistrySupport", () => { cacheDir: reservedDir, toolsDir: `${reservedDir}/tools`, registryUrl, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); const reservedError = yield* reservedResolver .resolve(settings(), "/workspace") .pipe(Effect.flip); expect(reservedError.reason).toBe("archive_invalid"); - // 2. A superseded primary executable that lost execute permission must not fail inspect() - // when the registry selects a different same-version artifact. + // 2. Updating args/env syncs the receipt; if writing into tools/ fails, updated launch + // options persist in registry cache storage so fallback still restores them across restarts. const supersededDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-superseded-inspect-", }); @@ -4527,13 +4689,11 @@ describe("AcpRegistrySupport", () => { cacheDir: supersededDir, toolsDir: `${supersededDir}/tools`, registryUrl, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); const installedA = yield* supersededResolver.resolve(settings(), "/workspace"); expect(installedA.spawn.args).toEqual(["--v1"]); expect(installedA.spawn.env?.STAGE).toBe("initial"); - // 3. Updating args/env on the same binary syncs the existing receipt so a later fallback - // launches with the last resolved args and env. upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -4547,36 +4707,179 @@ describe("AcpRegistrySupport", () => { expect(syncedA.spawn.args).toEqual(["--v1", "--updated"]); expect(syncedA.spawn.env?.STAGE).toBe("updated"); - upstream = makeBinary("2.0.0", { - archive: archiveFailUrl, + // Simulate a failed receipt write on a second args/env update, then restart and fail 2.0.0. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, cmd: "./bin/example-agent", + args: ["--v1", "--sidecar"], + env: { STAGE: "sidecar" }, }); yield* supersededResolver.invalidateIndex(); yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const fallbackA = yield* supersededResolver.resolve(settings(), "/workspace"); + const sidecarSyncedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(sidecarSyncedA.spawn.args).toEqual(["--v1", "--sidecar"]); + expect(sidecarSyncedA.spawn.env?.STAGE).toBe("sidecar"); + failReceiptTempWrite = false; + + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const restartedSuperseded = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: `${supersededDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackA = yield* restartedSuperseded.resolve(settings(), "/workspace"); expect(fallbackA.fallback).toBe(true); expect(fallbackA.agent?.version).toBe("1.0.0"); - expect(fallbackA.spawn.args).toEqual(["--v1", "--updated"]); - expect(fallbackA.spawn.env?.STAGE).toBe("updated"); + expect(fallbackA.spawn.args).toEqual(["--v1", "--sidecar"]); + expect(fallbackA.spawn.env?.STAGE).toBe("sidecar"); - // Now remove execute permission on primary A and swap same-version 1.0.0 to archive B: - // inspect() must stay ready so resolve() can install replacement B in a sibling slot. - yield* fileSystem.chmod(installedA.spawn.command, 0o644); + // Reverting upstream back to the receipt's earlier args/env after restart must prune/update + // the stale sidecar so a subsequent fallback does not resurrect the older sidecar options. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* restartedSuperseded.invalidateIndex(); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertedA = yield* restartedSuperseded.resolve(settings(), "/workspace"); + expect(revertedA.spawn.args).toEqual(["--v1", "--updated"]); + expect(revertedA.spawn.env?.STAGE).toBe("updated"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* restartedSuperseded.invalidateIndex(); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterRevert = yield* restartedSuperseded.resolve(settings(), "/workspace"); + expect(fallbackAfterRevert.fallback).toBe(true); + expect(fallbackAfterRevert.spawn.args).toEqual(["--v1", "--updated"]); + expect(fallbackAfterRevert.spawn.env?.STAGE).toBe("updated"); + + // 3. A superseded primary executable that lost execute permission must not fail inspect() + // when the registry selects a different same-version artifact. + yield* posixModeFs.chmod(installedA.spawn.command, 0o644); upstream = makeBinary("1.0.0", { archive: archiveBUrl, cmd: "./bin/example-agent", }); - yield* supersededResolver.invalidateIndex(); - yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect(yield* supersededResolver.inspect(settings())).toMatchObject({ + yield* restartedSuperseded.invalidateIndex(); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* restartedSuperseded.inspect(settings())).toMatchObject({ status: "ready", version: "1.0.0", }); - const installedB = yield* supersededResolver.resolve(settings(), "/workspace"); + const installedB = yield* restartedSuperseded.resolve(settings(), "/workspace"); expect(installedB.spawn.command).not.toBe(installedA.spawn.command); expect(yield* fileSystem.readFileString(installedB.spawn.command)).toBe( "#!/bin/sh\necho receipt-b\n", ); + + // 4. Waiting on a busy install lock is interruptible during sleep instead of blocking 30s. + const lockDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-lock-interrupt-", + }); + const versionDir = `${lockDir}/tools/example-agent/1.0.0`; + yield* fileSystem.makeDirectory(versionDir, { recursive: true }); + const lockFile = `${versionDir}/linux-x86_64.lock`; + yield* fileSystem.writeFileString(lockFile, "other-holder-token"); + const lockResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: lockDir, + toolsDir: `${lockDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const lockFirstStat = yield* Deferred.make(); + const lockSecondStat = yield* Deferred.make(); + let lockStatHits = 0; + onStatPath = { + matchPath: lockFile, + onHit: () => { + lockStatHits += 1; + if (lockStatHits === 1) { + Deferred.doneUnsafe(lockFirstStat, Exit.void); + } else if (lockStatHits === 2) { + Deferred.doneUnsafe(lockSecondStat, Exit.void); + } + }, + }; + const waitingPrepare = yield* lockResolver + .prepare({ agentId: "example-agent" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(lockFirstStat); + yield* TestClock.adjust("100 millis"); + yield* Deferred.await(lockSecondStat); + onStatPath = null; + expect(waitingPrepare.pollUnsafe()).toBeUndefined(); + yield* Fiber.interrupt(waitingPrepare); + // Interrupting while waiting must leave the other holder's lock intact. + expect(yield* fileSystem.readFileString(lockFile)).toBe("other-holder-token"); + + // 5. A stale legacy-baselines lock holder neither overwrites a newer holder's baselines + // nor deletes the newer holder's lock file on release. + const fenceDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-fence-", + }); + const fenceRegistryDir = `${fenceDir}/acp-registry`; + const fenceRegistryPath = `${fenceRegistryDir}/registry.json`; + const fenceBaselinesPath = `${fenceRegistryDir}/legacy-baselines.json`; + const fenceLockPath = `${fenceBaselinesPath}.lock`; + const fenceLegacyExe = `${fenceDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(fenceLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(fenceLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* posixModeFs.chmod(fenceLegacyExe, 0o755); + yield* fileSystem.makeDirectory(fenceRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + fenceRegistryPath, + makeRegistry(makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent" })), + ); + const holder1Entered = yield* Deferred.make(); + const releaseHolder1 = yield* Deferred.make(); + let gatedHolder1 = true; + let baselinesReadCount = 0; + const fencedFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => { + if (gatedHolder1 && filePath === fenceBaselinesPath) { + baselinesReadCount += 1; + if (baselinesReadCount === 2) { + gatedHolder1 = false; + return Deferred.succeed(holder1Entered, undefined).pipe( + Effect.andThen(Deferred.await(releaseHolder1)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + } + return posixModeFs.readFileString(filePath, encoding); + }, + }; + upstream = makeBinary("1.0.0", { archive: archiveBUrl, cmd: "./bin/example-agent" }); + const holder1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: fenceDir, + toolsDir: `${fenceDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, fencedFs)); + const holder1Refresh = yield* holder1 + .refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(holder1Entered); + // Simulate another holder taking over the stale lock and writing its own baseline map. + yield* fileSystem.writeFileString(fenceLockPath, "holder-2-token"); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value" }), + ); + yield* Deferred.succeed(releaseHolder1, undefined); + yield* Fiber.join(holder1Refresh); + expect(yield* fileSystem.readFileString(fenceLockPath)).toBe("holder-2-token"); + expect(JSON.parse(yield* fileSystem.readFileString(fenceBaselinesPath))).toEqual({ + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index f7f134d981f5d..9881a43c2ab27 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -671,7 +671,7 @@ export class AcpRegistryCatalog extends Context.Service< readonly maxAgeMs: number; readonly failureBackoffMs: number; }) => Effect.Effect; - readonly currentIndexRevision?: () => Effect.Effect; + readonly currentIndexRevision: () => Effect.Effect; readonly invalidateIndex: () => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, @@ -727,6 +727,7 @@ const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; const BINARY_LEGACY_BASELINES_FILENAME = "legacy-baselines.json"; +const BINARY_LAUNCH_OPTIONS_FILENAME = "binary-launch-options.json"; // Sentinel recorded for unrecoverable unreceipted slots when rebuilding a corrupt baselines file; // never equals binaryArtifactIdentityKey (which is always JSON) so the slot must be reinstalled. const LEGACY_BASELINE_UNKNOWN = "unknown"; @@ -745,6 +746,13 @@ type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt. const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( Schema.fromJsonString(AcpRegistryBinaryArtifactReceipt), ); +const AcpRegistryBinaryLaunchOptionsStore = Schema.Record( + Schema.String, + AcpRegistryBinaryArtifactReceipt, +); +const decodeBinaryLaunchOptionsStore = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryBinaryLaunchOptionsStore), +); const AcpRegistryLegacyBaselines = Schema.Record(Schema.String, Schema.String); const decodeLegacyBaselines = Schema.decodeUnknownOption( @@ -1037,6 +1045,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const registryDirectory = path.join(input.cacheDir, "acp-registry"); const registryCachePath = path.join(registryDirectory, "registry.json"); const legacyBaselinesPath = path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME); + const binaryLaunchOptionsPath = path.join(registryDirectory, BINARY_LAUNCH_OPTIONS_FILENAME); const installsDirectory = input.toolsDir; const agentInstallRoot = (agent: AcpRegistryAgent) => path.join(installsDirectory, agent.id, encodeURIComponent(agent.version)); @@ -1076,6 +1085,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); const registrySemaphore = yield* Semaphore.make(1); const legacyBaselinesSemaphore = yield* Semaphore.make(1); + const launchOptionsSemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. const installPermits = new Map(); const withInstallPermit = (agentId: string) => { @@ -1087,6 +1097,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // In-memory mirror of durable legacy baselines so disk write errors still keep a superseded // pre-receipt binary from matching a newly published artifact at the same version. const legacyBaselineBySlotKey = new Map(); + // True after an incomplete tools-directory scan or disk-index read error during baseline + // discovery; requires positive baseline provenance before reusing unreceipted legacy installs. + let legacyBaselineDiscoveryIncomplete = false; + // In-memory mirror of last-resolved binary launch options when updating .t3-artifact.json fails. + const syncedLaunchOptionsBySlotRoot = new Map(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -1352,15 +1367,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) { const retryCount = options?.retryCount ?? INSTALL_LOCK_RETRY_COUNT; const staleMs = options?.staleMs ?? INSTALL_LOCK_STALE_MS; + const token = yield* random.uuidV4(); for (let attempt = 0; attempt < retryCount; attempt += 1) { - const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( + const acquired = yield* fileSystem.writeFileString(lockPath, token, { flag: "wx" }).pipe( Effect.as(true), Effect.catchIf( (error) => isAlreadyExists(error), () => Effect.succeed(false), ), ); - if (acquired) return; + if (acquired) return token; const now = yield* Clock.currentTimeMillis; const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); const mtime = Option.flatMap(lockInfo, (info) => info.mtime); @@ -1368,7 +1384,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct yield* fileSystem.remove(lockPath, { force: true }); continue; } - yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); + // Keep the retry sleep interruptible inside acquireUseRelease so waiting on a busy lock + // never blocks provider refreshes, foreground preemption, or shutdown. + yield* Effect.interruptible(Effect.sleep(INSTALL_LOCK_RETRY_DELAY)); } return yield* new AcpRegistryError({ reason: "install_failed", @@ -1378,7 +1396,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const withFileLock = ( lockPath: string, - effect: Effect.Effect, + use: (isLockOwned: Effect.Effect) => Effect.Effect, options?: { readonly retryCount?: number; readonly staleMs?: number; @@ -1386,29 +1404,70 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) => Effect.acquireUseRelease( acquireFileLock(lockPath, options), - () => effect, - () => fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore), + (token) => + use( + fileSystem.readFileString(lockPath).pipe( + Effect.map((current) => current === token), + Effect.orElseSucceed(() => false), + ), + ), + (token) => + fileSystem.readFileString(lockPath).pipe( + Effect.flatMap((current) => + current === token ? fileSystem.remove(lockPath, { force: true }) : Effect.void, + ), + Effect.ignore, + ), ); - const writeLegacyBaselinesAtomically = (baselines: Readonly>) => + const writeJsonFileAtomically = (targetPath: string, value: unknown) => random.uuidV4().pipe( Effect.flatMap((id) => { - const temporaryPath = `${legacyBaselinesPath}.${process.pid}-${id}.tmp`; + const temporaryPath = `${targetPath}.${process.pid}-${id}.tmp`; return fileSystem .makeDirectory(registryDirectory, { recursive: true }) .pipe( - Effect.andThen(fileSystem.writeFileString(temporaryPath, JSON.stringify(baselines))), - Effect.andThen(fileSystem.rename(temporaryPath, legacyBaselinesPath)), + Effect.andThen(fileSystem.writeFileString(temporaryPath, JSON.stringify(value))), + Effect.andThen(fileSystem.rename(temporaryPath, targetPath)), Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)), ); }), ); - const withLegacyBaselinesLock = (effect: Effect.Effect) => + const writeLegacyBaselinesAtomically = (baselines: Readonly>) => + writeJsonFileAtomically(legacyBaselinesPath, baselines); + + const withLegacyBaselinesLock = ( + use: (isLockOwned: Effect.Effect) => Effect.Effect, + ) => legacyBaselinesSemaphore.withPermits(1)( fileSystem.makeDirectory(registryDirectory, { recursive: true }).pipe( Effect.andThen( - withFileLock(`${legacyBaselinesPath}.lock`, effect, { + withFileLock(`${legacyBaselinesPath}.lock`, use, { + retryCount: LEGACY_BASELINES_LOCK_RETRY_COUNT, + staleMs: LEGACY_BASELINES_LOCK_STALE_MS, + }), + ), + ), + ); + + const readBinaryLaunchOptionsFile = fileSystem.readFileString(binaryLaunchOptionsPath).pipe( + Effect.map((raw) => + Option.getOrElse( + decodeBinaryLaunchOptionsStore(raw), + (): Readonly> => ({}), + ), + ), + Effect.orElseSucceed((): Readonly> => ({})), + ); + + const withBinaryLaunchOptionsLock = ( + use: (isLockOwned: Effect.Effect) => Effect.Effect, + ) => + launchOptionsSemaphore.withPermits(1)( + fileSystem.makeDirectory(registryDirectory, { recursive: true }).pipe( + Effect.andThen( + withFileLock(`${binaryLaunchOptionsPath}.lock`, use, { retryCount: LEGACY_BASELINES_LOCK_RETRY_COUNT, staleMs: LEGACY_BASELINES_LOCK_STALE_MS, }), @@ -1422,6 +1481,25 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) { if (platformTarget === undefined) return true; const candidates = resolveAcpRegistryPlatformTargetCandidates(platformTarget); + const readDiskPreviousIndex = Effect.fn("AcpRegistryCatalog.readDiskPreviousIndex")( + function* () { + return yield* fileSystem.readFileString(registryCachePath).pipe( + Effect.flatMap((text) => + decodeRegistryText(text).pipe( + Effect.map((index) => ({ status: "ok" as const, index })), + Effect.orElseSucceed(() => ({ status: "missing" as const })), + ), + ), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" + ? ({ status: "missing" as const } as const) + : ({ status: "io_error" as const } as const), + ), + ), + ); + }, + ); const readDirectoryOrMissing = (directory: string) => fileSystem.readDirectory(directory).pipe( Effect.catchIf( @@ -1429,6 +1507,26 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct () => Effect.succeed>([]), ), ); + const listSubdirectories = Effect.fn("AcpRegistryCatalog.listSubdirectories")(function* ( + directory: string, + ) { + const entries = yield* readDirectoryOrMissing(directory); + const directories: Array = []; + for (const entry of entries) { + const statResult = yield* fileSystem.stat(path.join(directory, entry)).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + // Shared tools/ also holds non-directory files (e.g. tools/codex/active.json, .DS_Store). + if (statResult.status === "ok" && statResult.info.type === "Directory") { + directories.push(entry); + } + } + return directories; + }); const scanUnreceiptedLegacySlots = Effect.gen(function* () { const slots: Array<{ readonly agentId: string; @@ -1436,13 +1534,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly candidateTarget: AcpRegistryPlatformTarget; readonly slotKey: string; }> = []; - for (const agentId of yield* readDirectoryOrMissing(installsDirectory)) { + for (const agentId of yield* listSubdirectories(installsDirectory)) { const agentRoot = path.join(installsDirectory, agentId); - for (const encodedVersion of yield* readDirectoryOrMissing(agentRoot)) { + for (const encodedVersion of yield* listSubdirectories(agentRoot)) { const versionRoot = path.join(agentRoot, encodedVersion); for (const candidateTarget of candidates) { const installRoot = path.join(versionRoot, candidateTarget); - if (!(yield* fileSystem.exists(installRoot))) continue; + const installStat = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; if (yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME))) continue; slots.push({ @@ -1458,13 +1563,48 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); const scanResult = yield* Effect.result(scanUnreceiptedLegacySlots); if (Result.isFailure(scanResult)) { + legacyBaselineDiscoveryIncomplete = true; + // Record every diverging binary slot from the previous index in memory so live resolution + // cannot reuse a superseded legacy executable before the directory scan recovers. + const diskIndexResult = yield* readDiskPreviousIndex(); + const previousIndex = + diskIndexResult.status === "ok" ? diskIndexResult.index : inMemoryPrevious; + if (previousIndex !== undefined) { + const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); + for (const previousAgent of previousIndex.agents) { + const encodedVersion = encodeURIComponent(previousAgent.version); + for (const candidateTarget of candidates) { + const previousTarget = previousAgent.distribution.binary?.[candidateTarget]; + if (previousTarget === undefined) continue; + const slotKey = legacyBaselineSlotKey( + previousAgent.id, + encodedVersion, + candidateTarget, + ); + if (legacyBaselineBySlotKey.has(slotKey)) continue; + const previousKey = binaryArtifactIdentityKey(previousTarget); + const nextAgent = nextById.get(previousAgent.id); + const nextTarget = + nextAgent !== undefined && encodeURIComponent(nextAgent.version) === encodedVersion + ? nextAgent.distribution.binary?.[candidateTarget] + : undefined; + if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { + continue; + } + legacyBaselineBySlotKey.set(slotKey, previousKey); + } + } + } yield* Effect.logDebug( "Could not scan managed ACP binary directories for legacy baselines; keeping existing disk registry cache.", ); return false; } const unreceiptedLegacySlots = scanResult.success; - if (unreceiptedLegacySlots.length === 0) return true; + if (unreceiptedLegacySlots.length === 0) { + legacyBaselineDiscoveryIncomplete = false; + return true; + } const recordDivergingInMemory = Effect.fn("AcpRegistryCatalog.recordDivergingLegacyBaselines")( function* (existingBaselines: Readonly>) { @@ -1485,22 +1625,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } // Prefer the on-disk registry cache over in-memory state so a recovery refresh after a // previous skipped disk write still compares against the index persisted on disk. - const diskIndexResult = yield* fileSystem.readFileString(registryCachePath).pipe( - Effect.flatMap((text) => - decodeRegistryText(text).pipe( - Effect.map((index) => ({ status: "ok" as const, index })), - Effect.orElseSucceed(() => ({ status: "missing" as const })), - ), - ), - Effect.catch((error) => - Effect.succeed( - error.reason._tag === "NotFound" - ? ({ status: "missing" as const } as const) - : ({ status: "io_error" as const } as const), - ), - ), - ); + const diskIndexResult = yield* readDiskPreviousIndex(); if (diskIndexResult.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; return { newBaselines: {} as Record, hasUpdates: false, @@ -1566,6 +1693,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct for (const slot of unreceiptedLegacySlots) { legacyBaselineBySlotKey.set(slot.slotKey, initialDisk.baselines[slot.slotKey]!); } + legacyBaselineDiscoveryIncomplete = false; return true; } if (initialDisk.status === "io_error") { @@ -1575,7 +1703,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); } - return yield* withLegacyBaselinesLock( + return yield* withLegacyBaselinesLock((isLockOwned) => Effect.gen(function* () { const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); if (disk.status === "io_error") { @@ -1584,28 +1712,44 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct "Could not read ACP Registry legacy baselines; keeping existing disk registry cache.", ); } - const isCorrupt = disk.status === "corrupt"; - const baseBaselines: Readonly> = isCorrupt ? {} : disk.baselines; - const { newBaselines, hasUpdates, readError } = - yield* recordDivergingInMemory(baseBaselines); - if (readError) return false; - if (!hasUpdates && !isCorrupt) return true; - const mergedBaselines: Record = { ...baseBaselines, ...newBaselines }; - if (isCorrupt) { + let mergedBaselines: Record; + if (disk.status === "corrupt") { // Copy the corrupt bytes aside before atomically replacing legacy-baselines.json so there - // is no missing-file window, and mark any unrecoverable legacy slot as unknown so a - // rebuilt file never treats an unverified pre-receipt install as matching the new target. + // is no missing-file window. Never reconstruct provenance from the unverified cached + // registry index; preserve only baselines already verified in memory and mark others + // unknown so resolve() requires a fresh receipted install. yield* fileSystem .copyFile(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) .pipe(Effect.ignore); + mergedBaselines = {}; for (const slot of unreceiptedLegacySlots) { - if (mergedBaselines[slot.slotKey] === undefined) { - mergedBaselines[slot.slotKey] = LEGACY_BASELINE_UNKNOWN; - legacyBaselineBySlotKey.set(slot.slotKey, LEGACY_BASELINE_UNKNOWN); - } + const baseline = legacyBaselineBySlotKey.get(slot.slotKey) ?? LEGACY_BASELINE_UNKNOWN; + mergedBaselines[slot.slotKey] = baseline; + legacyBaselineBySlotKey.set(slot.slotKey, baseline); + } + } else { + const { newBaselines, hasUpdates, readError } = yield* recordDivergingInMemory( + disk.baselines, + ); + if (readError) return false; + if (!hasUpdates) { + legacyBaselineDiscoveryIncomplete = false; + return true; } + mergedBaselines = { ...disk.baselines, ...newBaselines }; + } + if (!(yield* isLockOwned)) { + yield* Effect.logDebug( + "Lost ACP Registry legacy baselines lock before writing; keeping existing disk registry cache.", + ); + return false; } return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( + Effect.tap(() => + Effect.sync(() => { + legacyBaselineDiscoveryIncomplete = false; + }), + ), Effect.as(true), Effect.catch(() => Effect.logDebug( @@ -2351,7 +2495,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const diskBaseline = diskResult.baselines[paths.slotKey]; if (diskBaseline === undefined) { - return true; + return !legacyBaselineDiscoveryIncomplete; } legacyBaselineBySlotKey.set(paths.slotKey, diskBaseline); return diskBaseline === currentKey; @@ -2409,24 +2553,80 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct target: typeof AcpRegistryBinaryTarget.Type, ) { if (slot.receipt === undefined) return; - const sameArgs = Equal.equals(slot.receipt.args ?? [], target.args ?? []); - const sameEnv = Equal.equals(slot.receipt.env ?? {}, target.env ?? {}); - if (sameArgs && sameEnv) return; + const memoryStored = syncedLaunchOptionsBySlotRoot.get(slot.root); + if ( + memoryStored !== undefined && + Equal.equals(memoryStored.args ?? [], target.args ?? []) && + Equal.equals(memoryStored.env ?? {}, target.env ?? []) + ) { + return; + } + const hasSidecar = + memoryStored === undefined && + (yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false))); + const diskStored = hasSidecar ? (yield* readBinaryLaunchOptionsFile)[slot.root] : undefined; + if ( + diskStored === undefined && + Equal.equals(slot.receipt.args ?? [], target.args ?? []) && + Equal.equals(slot.receipt.env ?? {}, target.env ?? []) + ) { + return; + } + const updatedReceipt: AcpRegistryBinaryArtifactReceipt = { + version: agent.version, + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), + ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), + }; + syncedLaunchOptionsBySlotRoot.set(slot.root, updatedReceipt); const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); - yield* random.uuidV4().pipe( - Effect.flatMap((id) => { - const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; - return fileSystem - .writeFileString(temporaryPath, encodeBinaryArtifactReceipt(agent, target)) - .pipe( - Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), - Effect.ensuring( - fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), - ), - ); - }), - Effect.ignore, + const receiptWrite = yield* Effect.result( + random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; + return fileSystem + .writeFileString(temporaryPath, encodeBinaryArtifactReceipt(agent, target)) + .pipe( + Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), + Effect.ensuring( + fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), + ), + ); + }), + ), ); + if (Result.isSuccess(receiptWrite)) { + // Keep the slot receipt authoritative by pruning any stale fallback sidecar entry. + if ( + yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false)) + ) { + yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const current = yield* readBinaryLaunchOptionsFile; + if (current[slot.root] === undefined) return; + if (!(yield* isLockOwned)) return; + const { [slot.root]: _removed, ...rest } = current; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest); + }), + ).pipe(Effect.ignore); + } + return; + } + // If updating the receipt inside tools/ failed (e.g., read-only install directory or file + // lock), persist the updated launch options in registry cache storage so fallback still + // restores the last-resolved args and env even across restarts. + yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const current = yield* readBinaryLaunchOptionsFile; + if (!(yield* isLockOwned)) return; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, { + ...current, + [slot.root]: updatedReceipt, + }); + }), + ).pipe(Effect.ignore); }, ); @@ -2483,8 +2683,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); const lockPath = `${installRoot}.lock`; - return yield* withFileLock( - lockPath, + return yield* withFileLock(lockPath, () => Effect.gen(function* () { const lockedSlot = yield* findMatchingBinarySlot(paths, target); if (Option.isSome(lockedSlot)) { @@ -3123,9 +3322,26 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.option, ); if (Option.isNone(validated)) continue; - const fallbackVersion = receipt.version ?? safeDecodeVersionDir(versionDir); - const fallbackArgs = receipt.args ?? []; - const fallbackEnv = receipt.env ?? {}; + const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir); + const diskOverride = + memoryOverride !== undefined + ? undefined + : (yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false))) + ? (yield* readBinaryLaunchOptionsFile)[dir] + : undefined; + const candidateOverride = memoryOverride ?? diskOverride; + const effectiveReceipt = + candidateOverride !== undefined && + candidateOverride.archive === receipt.archive && + candidateOverride.cmd === receipt.cmd && + (candidateOverride.sha256 ?? null) === (receipt.sha256 ?? null) + ? candidateOverride + : receipt; + const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); + const fallbackArgs = effectiveReceipt.args ?? []; + const fallbackEnv = effectiveReceipt.env ?? {}; const fallbackTarget: typeof AcpRegistryBinaryTarget.Type = { archive: receipt.archive, cmd: receipt.cmd, @@ -3440,6 +3656,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct legacyBaselineBySlotKey.delete(key); } } + const agentRootPrefix = `${agentRoot}${path.sep}`; + for (const slotRoot of syncedLaunchOptionsBySlotRoot.keys()) { + if (slotRoot === agentRoot || slotRoot.startsWith(agentRootPrefix)) { + syncedLaunchOptionsBySlotRoot.delete(slotRoot); + } + } } return { agentId: safeAgentId, removed }; }), @@ -3448,33 +3670,61 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .pipe( Effect.tap(({ agentId: removedAgentId, removed }) => removed - ? fileSystem.exists(legacyBaselinesPath).pipe( - Effect.orElseSucceed(() => false), - Effect.flatMap((hasBaselinesFile) => - hasBaselinesFile - ? withLegacyBaselinesLock( - Effect.gen(function* () { - const disk = yield* readLegacyBaselinesFile( - fileSystem, - legacyBaselinesPath, - ); - if (disk.status !== "ok") return; - const prefix = `${removedAgentId}\0`; - const remaining = Object.fromEntries( - Object.entries(disk.baselines).filter( - ([key]) => !key.startsWith(prefix), - ), - ); - if ( - Object.keys(remaining).length !== Object.keys(disk.baselines).length - ) { - yield* writeLegacyBaselinesAtomically(remaining); - } - }), - ).pipe(Effect.ignore) - : Effect.void, + ? Effect.all([ + fileSystem.exists(legacyBaselinesPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasBaselinesFile) => + hasBaselinesFile + ? withLegacyBaselinesLock((isLockOwned) => + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile( + fileSystem, + legacyBaselinesPath, + ); + if (disk.status !== "ok") return; + const prefix = `${removedAgentId}\0`; + const remaining = Object.fromEntries( + Object.entries(disk.baselines).filter( + ([key]) => !key.startsWith(prefix), + ), + ); + if ( + Object.keys(remaining).length !== Object.keys(disk.baselines).length + ) { + if (!(yield* isLockOwned)) return; + yield* writeLegacyBaselinesAtomically(remaining); + } + }), + ).pipe(Effect.ignore) + : Effect.void, + ), ), - ) + fileSystem.exists(binaryLaunchOptionsPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasLaunchOptionsFile) => + hasLaunchOptionsFile + ? withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const disk = yield* readBinaryLaunchOptionsFile; + const removedAgentRoot = path.join(installsDirectory, removedAgentId); + const removedPrefix = `${removedAgentRoot}${path.sep}`; + const remaining = Object.fromEntries( + Object.entries(disk).filter( + ([slotRoot]) => + slotRoot !== removedAgentRoot && + !slotRoot.startsWith(removedPrefix), + ), + ); + if (Object.keys(remaining).length !== Object.keys(disk).length) { + if (!(yield* isLockOwned)) return; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, remaining); + } + }), + ).pipe(Effect.ignore) + : Effect.void, + ), + ), + ]).pipe(Effect.asVoid) : Effect.void, ), Effect.catchTags({ diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 10d349b8bd8c5..343d9426643d6 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -55,6 +55,7 @@ const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { search: () => Effect.die("unused"), prepare: () => Effect.die("unused"), refreshIndex: () => Effect.die("unused"), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.die("unused"), 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 bbc564b4be551..722c4d6658f16 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -70,6 +70,7 @@ function catalogWithInspection( search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), refreshIndex: () => Effect.succeed(0), + currentIndexRevision: () => Effect.succeed(0), invalidateIndex: () => Effect.void, inspect: () => Effect.succeed(inspection), resolve: () => Effect.die("unused resolve"), @@ -2862,6 +2863,10 @@ describe("AcpRegistryDriver registry recovery", () => { readonly release: Deferred.Deferred; } | null = null; let onInspectCallback: (() => Effect.Effect) | null = null; + let onCommandHandled: { + readonly matchName: string; + readonly done: Deferred.Deferred; + } | null = null; let queuedStaleConfigGate: { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; @@ -2870,6 +2875,22 @@ describe("AcpRegistryDriver registry recovery", () => { const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = { ...baseCoordinator, + watchAvailableCommands: (instanceId, onUpdate) => + baseCoordinator.watchAvailableCommands(instanceId, (commands, meta) => + onUpdate(commands, meta).pipe( + Effect.tap(() => { + if ( + onCommandHandled !== null && + commands.slashCommands.some((cmd) => cmd.name === onCommandHandled!.matchName) + ) { + const handled = onCommandHandled; + onCommandHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), watchLiveConfiguration: (instanceId, onUpdate) => baseCoordinator.watchLiveConfiguration(instanceId, (configuration, meta) => { const activeGate = @@ -3496,11 +3517,15 @@ describe("AcpRegistryDriver registry recovery", () => { ); yield* instance.snapshot.refresh; yield* Deferred.await(v4ParkedGate.started); + const v4ParkedHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-parked-after-fail", done: v4ParkedHandled }; yield* coordinator.publishAvailableCommands( identity.instanceId, { slashCommands: [{ name: "v4-parked-after-fail" }], skills: [] }, v4Identity, ); + // Wait for the watcher to park v4Identity in pendingReconcileIdentity while the probe is still blocked. + yield* Deferred.await(v4ParkedHandled); yield* Deferred.succeed(v4ParkedGate.release, undefined); const reconciledFromParked = Option.getOrThrow(yield* Fiber.join(v4ReconciledFromParked)); expect(reconciledFromParked.version).toBe("4.0.0"); @@ -3548,4 +3573,490 @@ describe("AcpRegistryDriver registry recovery", () => { yield* Fiber.interrupt(disposedWatcher); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); + + it.effect( + "preserves foreground-only live runtimes on upgrade failure, stamps fallback retirements at the failed target revision, and drains events arriving during in-flight reconciliation", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-reconcile-edge-", + ); + + let remoteVersion = "1.0.0"; + let remoteExtraAgentVersion: string | undefined = undefined; + let failArchiveVersions = new Set(); + let failProbeSpawn = false; + let inspectCalls = 0; + let resolveGate: { + readonly matchVersion: string; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let inspectGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let onCommandHandled: { + readonly matchName: string; + readonly done: Deferred.Deferred; + } | null = null; + let onInspectCallback: (() => Effect.Effect) | null = null; + let onEnrichmentEnd: (() => void) | null = null; + const enrichmentTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + if (Exit.isSuccess(exit)) { + const cb = onEnrichmentEnd; + onEnrichmentEnd = null; + cb?.(); + } + }; + return inner; + }, + }; + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + watchAvailableCommands: (instanceId, onUpdate) => + baseCoordinator.watchAvailableCommands(instanceId, (commands, meta) => + onUpdate(commands, meta).pipe( + Effect.tap(() => { + if ( + onCommandHandled !== null && + commands.slashCommands.some((cmd) => cmd.name === onCommandHandled!.matchName) + ) { + const handled = onCommandHandled; + onCommandHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), + }; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + makeBinaryRegistry( + remoteVersion, + compatibleRegistryTarget, + remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : undefined, + ), + ), + ), + ); + } + const failDownload = Array.from(failArchiveVersions).some((version) => + request.url.includes(`-${version}.bin`), + ); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + failDownload + ? new Response("unavailable", { status: 503 }) + : new Response(`#!/bin/sh\necho ${remoteVersion}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + Effect.gen(function* () { + inspectCalls += 1; + const result = yield* realCatalog.inspect(settings, environment); + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + if (onInspectCallback !== null) { + yield* onInspectCallback(); + } + return result; + }), + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + if ( + environment?.MISE_OFFLINE === "1" && + resolveGate !== null && + resolved.agent?.version === resolveGate.matchVersion + ) { + const gate = resolveGate; + resolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + if (environment?.MISE_OFFLINE === "1" && failProbeSpawn) { + return yield* new AcpRegistrySupport.AcpRegistryError({ + reason: "install_failed", + detail: `Simulated probe install failure for ${resolved.agent?.version ?? "unknown"}.`, + }); + } + return { + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }; + + // 1. Foreground startup skips initial 1.0.0 probe while live 1.0.0 session publishes models + // and commands; when 2.0.0 later fails to probe, snapshot must stay on 1.0.0 (not 2.0.0). + const fgInstanceId = ProviderInstanceId.make("acpRegistry_fg_only_v1"); + const fgStarted = yield* Deferred.make(); + const releaseFg = yield* Deferred.make(); + const fgFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(fgStarted, undefined).pipe(Effect.andThen(Deferred.await(releaseFg))), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fgStarted); + + const fgInstance = yield* AcpRegistryDriver.create({ + instanceId: fgInstanceId, + displayName: "FG Only", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + const v1Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v1Inspection.status).toBe("ready"); + const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; + const fgLiveReady = yield* fgInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "fg-v1-a") && + snapshot.slashCommands.some((cmd) => cmd.name === "fg-v1-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fgInstance.snapshot.refresh; + yield* coordinator.publishLiveConfiguration( + fgInstanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-a", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-b", name: "fg-v1-b" }, + ], + }), + v1Identity, + ); + yield* coordinator.publishAvailableCommands( + fgInstanceId, + { slashCommands: [{ name: "fg-v1-cmd" }], skills: [] }, + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(fgLiveReady))).toBe(true); + + // End foreground startup, move index to failing 2.0.0, and verify 1.0.0 is preserved cleanly. + yield* Deferred.succeed(releaseFg, undefined); + yield* Fiber.join(fgFiber); + remoteVersion = "2.0.0"; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fgWarning = yield* fgInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fgInstance.snapshot.refresh; + const fgWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgWarning)); + expect(fgWarningSnapshot.version).toBe("1.0.0"); + expect(fgWarningSnapshot.message).toContain("2.0.0"); + expect(fgWarningSnapshot.models.map((model) => model.slug)).toEqual(["fg-v1-a", "fg-v1-b"]); + expect(fgWarningSnapshot.slashCommands).toEqual([{ name: "fg-v1-cmd" }]); + + // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed + // 2.0.0 probe publishes 2.0.0's failure snapshot directly without attaching 1.0.0 live state. + remoteVersion = "1.0.0"; + failProbeSpawn = false; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const coldFgStarted = yield* Deferred.make(); + const releaseColdFg = yield* Deferred.make(); + const coldFgFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(coldFgStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseColdFg)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldFgStarted); + const noAcceptId = ProviderInstanceId.make("acpRegistry_no_accepted_v1"); + const noAcceptInstance = yield* AcpRegistryDriver.create({ + instanceId: noAcceptId, + displayName: "No Accepted V1", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + const noAcceptColdEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptColdEnrichmentDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(noAcceptColdEnrichmentDone); + yield* Deferred.succeed(releaseColdFg, undefined); + yield* Fiber.join(coldFgFiber); + remoteVersion = "2.0.0"; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const noAcceptWarning = yield* noAcceptInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* noAcceptInstance.snapshot.refresh; + const noAcceptSnapshot = Option.getOrThrow(yield* Fiber.join(noAcceptWarning)); + expect(noAcceptSnapshot.version).toBe("2.0.0"); + expect(noAcceptSnapshot.message).toContain("2.0.0"); + expect(noAcceptSnapshot.slashCommands).toEqual([]); + + // 3. Fallback retirement stamps failedTarget's revision (v3), not a concurrently restored + // v4 revision, so a new v4 session reconciles immediately even if v4 restored mid-probe. + failProbeSpawn = false; + const fallbackRetireId = ProviderInstanceId.make("acpRegistry_fallback_retire_rev"); + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackRetireInstance = yield* AcpRegistryDriver.create({ + instanceId: fallbackRetireId, + displayName: "Fallback Retire Rev", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + const v2Ready = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fallbackRetireInstance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(v2Ready))).toBe(true); + const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v2Inspection.status).toBe("ready"); + const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; + + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v4Ready = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "4.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v4InitialDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4InitialDone, Exit.void); + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + expect(Option.isSome(yield* Fiber.join(v4Ready))).toBe(true); + yield* Deferred.await(v4InitialDone); + const v4Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v4Inspection.status).toBe("ready"); + const v4Identity = v4Inspection.status === "ready" ? v4Inspection.launchIdentity! : ""; + + // Move upstream to failing 3.0.0 while keeping disk cache on 4.0.0 and only 2.0.0 on disk: + // enrichment's index refresh discovers 3.0.0 (R3), fails download, and falls back to 2.0.0. + // Pause during 2.0.0 fallback resolve while another caller restores 4.0.0 at R4 > R3. + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "4.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "3.0.0"; + failArchiveVersions = new Set(["3.0.0"]); + yield* realCatalog.invalidateIndex(); + const v2FallbackGate = { + matchVersion: "2.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v2FallbackGate; + const v2FallbackPublished = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && Boolean(snapshot.message?.includes("3.0.0")), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fallbackEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackEnrichmentDone, Exit.void); + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(v2FallbackGate.started); + remoteVersion = "4.0.0"; + failArchiveVersions = new Set(); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(v2FallbackGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(v2FallbackPublished))).toBe(true); + yield* Deferred.await(fallbackEnrichmentDone); + + // Because v4 was retired at R3 (not R4), a new v4 live update at R4 reconciles immediately. + const v4Restored = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v4-restored-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v4RestoredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4RestoredEnrichmentDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-restored-cmd" }], skills: [] }, + v4Identity, + ); + expect(Option.isSome(yield* Fiber.join(v4Restored))).toBe(true); + yield* Deferred.await(v4RestoredEnrichmentDone); + + // 4. An event arriving while a reconciliation inspect for the same identity is in flight + // is parked and drained once the older inspection finishes, and unrelated revision bumps + // re-stamp retirement so subsequent late updates do not repeat catalog.inspect. + remoteExtraAgentVersion = "9.9.9"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const staleReconcileInspect = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = staleReconcileInspect; + // First retired v2 event at unrelated revision R5 triggers a coalesced inspect (paused on gate). + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-stale-at-r5" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(staleReconcileInspect.started); + // While inspect #1 (at R5 = 4.0.0) is in flight, roll catalog back to 2.0.0 at R6 and send a new v2 update. + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v2ParkedHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-during-reconcile", done: v2ParkedHandled }; + const v2DrainedReconciled = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v2-during-reconcile"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v2RestoredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v2RestoredEnrichmentDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-during-reconcile" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(v2ParkedHandled); + yield* Deferred.succeed(staleReconcileInspect.release, undefined); + expect(Option.isSome(yield* Fiber.join(v2DrainedReconciled))).toBe(true); + yield* Deferred.await(v2RestoredEnrichmentDone); + + // Verify re-stamping on an unrelated revision bump suppresses repeated inspects for retired v4. + remoteExtraAgentVersion = "10.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const firstRestampDone = yield* Deferred.make(); + onInspectCallback = () => Deferred.succeed(firstRestampDone, undefined).pipe(Effect.asVoid); + const inspectsBeforeRestamp = inspectCalls; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-1" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(firstRestampDone); + onInspectCallback = null; + expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + + // A second late v4 event at the same revision must NOT call catalog.inspect again, + // while a subsequent unrelated revision bump inspects once more (total +2, not +3). + const secondLateHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-late-2", done: secondLateHandled }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-2" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(secondLateHandled); + expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + + remoteExtraAgentVersion = "10.0.1"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const secondRestampDone = yield* Deferred.make(); + onInspectCallback = () => + Deferred.succeed(secondRestampDone, undefined).pipe(Effect.asVoid); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-3" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(secondRestampDone); + onInspectCallback = null; + expect(inspectCalls).toBe(inspectsBeforeRestamp + 2); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 84eb85882a43b..12d2012a87c46 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1266,7 +1266,7 @@ export const AcpRegistryDriver: ProviderDriver 0; - const currentCatalogIndexRevision = catalog.currentIndexRevision?.() ?? Effect.succeed(0); + const currentCatalogIndexRevision = catalog.currentIndexRevision(); const lastSeenIndexRevision = yield* Ref.make(0); const acknowledgeRevision = (revision: number) => Ref.update(lastSeenIndexRevision, (seen) => Math.max(seen, revision)); @@ -1431,7 +1431,7 @@ export const AcpRegistryDriver: ProviderDriver(null); + const reconcilingState = yield* Ref.make>(new Map()); const refreshTarget = yield* Deferred.make>(); const triggerSnapshotRefresh = Deferred.await(refreshTarget).pipe(Effect.flatten); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); @@ -1478,9 +1478,13 @@ export const AcpRegistryDriver: ProviderDriver(null); - const pendingReconcileIdentity = yield* Ref.make(null); - const maybeReconcileUnmatchedRuntime = (incomingIdentity: string | undefined) => { + const probeReconcileState = yield* Ref.make<{ + readonly inFlight: string | null; + readonly pending: string | null; + }>({ inFlight: null, pending: null }); + const maybeReconcileUnmatchedRuntime = ( + incomingIdentity: string | undefined, + ): Effect.Effect => { if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; return Effect.gen(function* () { const retiredAtRevision = (yield* Ref.get(retiredRuntimeIdentities)).get( @@ -1495,25 +1499,33 @@ export const AcpRegistryDriver: ProviderDriver - current === incomingIdentity - ? ([false, current] as const) - : ([true, incomingIdentity] as const), + const parkedOnProbe = yield* Ref.modify(probeReconcileState, (state) => + state.inFlight === incomingIdentity + ? ([true, { ...state, pending: incomingIdentity }] as const) + : ([false, state] as const), ); + if (parkedOnProbe) return; + const claimed = yield* Ref.modify(reconcilingState, (state) => { + const next = new Map(state); + if (state.has(incomingIdentity)) { + next.set(incomingIdentity, true); + return [false, next] as const; + } + next.set(incomingIdentity, false); + return [true, next] as const; + }); if (!claimed) return; yield* Effect.gen(function* () { const inspected = yield* Effect.result( catalog.inspect(readinessInput.settings, readinessInput.environment), ); + let matched = false; if ( Result.isSuccess(inspected) && inspected.success.status === "ready" && inspected.success.launchIdentity === incomingIdentity ) { + matched = true; yield* Ref.update(activeFallback, (current) => current?.targetLaunchIdentity === incomingIdentity ? null : current, ); @@ -1529,7 +1541,7 @@ export const AcpRegistryDriver: ProviderDriver { if (!retired.has(incomingIdentity)) return retired; @@ -1538,11 +1550,24 @@ export const AcpRegistryDriver: ProviderDriver { + if (!state.has(incomingIdentity)) return [false, state] as const; + const next = new Map(state); + const pending = next.get(incomingIdentity) === true; + next.delete(incomingIdentity); + return [pending, next] as const; + }); + if (!matched && replayPending) { + yield* maybeReconcileUnmatchedRuntime(incomingIdentity); + } }).pipe( - Effect.ensuring( - Ref.update(reconcilingRuntimeIdentity, (current) => - current === incomingIdentity ? null : current, - ), + Effect.onInterrupt(() => + Ref.update(reconcilingState, (state) => { + if (!state.has(incomingIdentity)) return state; + const next = new Map(state); + next.delete(incomingIdentity); + return next; + }), ), Effect.forkIn(driverScope), ); @@ -1594,7 +1619,11 @@ export const AcpRegistryDriver: ProviderDriver ({ + ...state, + inFlight: targetIdentity, + })).pipe( Effect.andThen(probeEffect), Effect.flatMap( Option.match({ @@ -1633,72 +1662,84 @@ export const AcpRegistryDriver: ProviderDriver { - const { message: _previousMessage, ...base } = lastRuntime.provider; - return { - ...base, - checkedAt: provider.checkedAt, - status: provider.status, - auth: - provider.auth.status === "unauthenticated" - ? provider.auth - : base.auth, - ...(provider.message !== undefined - ? { message: provider.message } - : {}), - }; - })() - : provider; - const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState( - preservedBase, - { - sessionRuntimeIdentity: previousIdentity, - requireMatchingRuntimeIdentity: false, - useLearnedModels: true, - persistLearnedModels: false, - }, - ); - const nextSnapshot = isUpgradeFailure - ? { - ...nextSnapshotRaw, - status: provider.status, - ...(provider.message !== undefined - ? { message: provider.message } - : {}), + if (lastRuntime !== null && lastRuntime.identity === previousIdentity) { + const { message: _previousMessage, ...base } = lastRuntime.provider; + const preservedBase: ServerProvider = { + ...base, + checkedAt: provider.checkedAt, + status: provider.status, + auth: + provider.auth.status === "unauthenticated" + ? provider.auth + : base.auth, + ...(provider.message !== undefined + ? { message: provider.message } + : {}), + }; + const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState( + preservedBase, + { + sessionRuntimeIdentity: previousIdentity, + requireMatchingRuntimeIdentity: false, + useLearnedModels: true, + persistLearnedModels: false, + }, + ); + const nextSnapshot = isUpgradeFailure + ? { + ...nextSnapshotRaw, + status: provider.status, + ...(provider.message !== undefined + ? { message: provider.message } + : {}), + } + : nextSnapshotRaw; + const published = yield* tryPublishSnapshot(nextSnapshot); + if (published) { + yield* Ref.set(expectedRuntimeIdentity, previousIdentity); + if (isUpgradeFailure) { + yield* Ref.set(failedUpgradeTarget, { + targetLaunchIdentity: failedTargetLaunchIdentity, + status: provider.status, + auth: provider.auth, + message: provider.message, + }); } - : nextSnapshotRaw; - const published = yield* tryPublishSnapshot(nextSnapshot); - if (published) { - yield* Ref.set(expectedRuntimeIdentity, previousIdentity); - if (isUpgradeFailure) { - yield* Ref.set(failedUpgradeTarget, { - targetLaunchIdentity: failedTargetLaunchIdentity, - status: provider.status, - auth: provider.auth, - message: provider.message, - }); } + return { + published, + readiness: published + ? { + snapshot: nextSnapshot, + launchIdentity: previousIdentity, + indexRevision, + probeFailed: true, + } + : null, + publishedIdentity: published ? previousIdentity : null, + }; } + // No accepted snapshot exists for previousIdentity; publish the failure + // snapshot directly without attaching previousIdentity's live state. + const published = yield* tryPublishSnapshot(provider); return { published, readiness: published ? { - snapshot: nextSnapshot, - launchIdentity: previousIdentity, + snapshot: provider, + launchIdentity, indexRevision, probeFailed: true, } : null, - publishedIdentity: published ? previousIdentity : null, + publishedIdentity: null, }; } const existingFallback = fallback ? yield* Ref.get(activeFallback) : null; @@ -1774,7 +1815,8 @@ export const AcpRegistryDriver: ProviderDriver { const next = new Map(retired); // Retire only a runtime that actually succeeded; a never-installed @@ -1839,18 +1881,23 @@ export const AcpRegistryDriver: ProviderDriver - current === targetIdentity ? null : current, + Ref.modify(probeReconcileState, (state) => + state.inFlight === targetIdentity + ? ([state.pending, { inFlight: null, pending: null }] as const) + : ([null, state] as const), + ).pipe( + Effect.tap((pending) => + Effect.sync(() => { + drainedPending = pending; + }), + ), + Effect.asVoid, ), ), Effect.tap(({ publishedIdentity }) => - Ref.getAndSet(pendingReconcileIdentity, null).pipe( - Effect.flatMap((pending) => - pending !== null && pending !== publishedIdentity - ? maybeReconcileUnmatchedRuntime(pending) - : Effect.void, - ), - ), + drainedPending !== null && drainedPending !== publishedIdentity + ? maybeReconcileUnmatchedRuntime(drainedPending) + : Effect.void, ), Effect.map(({ published, readiness }) => ({ published, readiness })), ); @@ -1876,13 +1923,26 @@ export const AcpRegistryDriver: ProviderDriver prev !== null && prev.identity === activeId ? { identity: prev.identity, provider: { ...prev.provider, slashCommands, skills }, } - : prev, + : prev === null + ? { + identity: activeId, + provider: { + ...currentClean, + status: current.enabled + ? ("ready" as const) + : ("disabled" as const), + slashCommands, + skills, + }, + } + : prev, ); } } @@ -1938,10 +1998,21 @@ export const AcpRegistryDriver: ProviderDriver prev !== null && prev.identity === activeId - ? { identity: prev.identity, provider: applied } - : prev, + ? { identity: prev.identity, provider: appliedClean } + : prev === null + ? { + identity: activeId, + provider: { + ...appliedClean, + status: current.enabled + ? ("ready" as const) + : ("disabled" as const), + }, + } + : prev, ); } const now = yield* Clock.currentTimeMillis; From 1d7ed7075e2ae2d8c5d43ca9ddfd04d990106acc Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 17:15:41 +0000 Subject: [PATCH 18/28] fix(acp-registry): version launch-option sidecars, scope legacy scans, and align failed-upgrade auth and watcher state --- .../src/server/AcpRegistrySupport.test.ts | 603 ++++++++++++++++-- .../src/server/AcpRegistrySupport.ts | 305 ++++++--- .../src/server/driver.test.ts | 308 +++++++-- .../src/server/driver.ts | 29 +- 4 files changed, 1032 insertions(+), 213 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 5d0b1fa3a831c..e3f0cc4d55c68 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1932,6 +1932,7 @@ describe("AcpRegistrySupport", () => { } | null = null; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-backoff-", }); @@ -2007,7 +2008,7 @@ describe("AcpRegistrySupport", () => { const coldInspectDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-inspect-coalesce-", }); - const coldCachePath = `${coldInspectDir}/acp-registry/registry.json`; + const coldCachePath = path.join(coldInspectDir, "acp-registry", "registry.json"); const missingColdCacheError = yield* fileSystem .readFileString(coldCachePath) .pipe(Effect.flip); @@ -2021,7 +2022,7 @@ describe("AcpRegistrySupport", () => { }; const coldInspectResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: coldInspectDir, - toolsDir: `${coldInspectDir}/tools`, + toolsDir: path.join(coldInspectDir, "tools"), registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, coldInspectFs)); const coldInspectGate = { @@ -2124,11 +2125,12 @@ describe("AcpRegistrySupport", () => { } | null = null; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-invalidate-race-", }); - const registryDirectory = `${cacheDir}/acp-registry`; - const registryCachePath = `${registryDirectory}/registry.json`; + const registryDirectory = path.join(cacheDir, "acp-registry"); + const registryCachePath = path.join(registryDirectory, "registry.json"); yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); @@ -2233,7 +2235,7 @@ describe("AcpRegistrySupport", () => { const coldAcceptedDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-cold-accept-", }); - const coldAcceptedCachePath = `${coldAcceptedDir}/acp-registry/registry.json`; + const coldAcceptedCachePath = path.join(coldAcceptedDir, "acp-registry", "registry.json"); const missingAcceptedCacheError = yield* fileSystem .readFileString(coldAcceptedCachePath) .pipe(Effect.flip); @@ -2246,7 +2248,7 @@ describe("AcpRegistrySupport", () => { }; const coldAcceptedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: coldAcceptedDir, - toolsDir: `${coldAcceptedDir}/tools`, + toolsDir: path.join(coldAcceptedDir, "tools"), registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, coldAcceptedFs)); const coldFetchGate = { @@ -3373,11 +3375,12 @@ describe("AcpRegistrySupport", () => { }); return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-disk-race-", }); - const registryDirectory = `${cacheDir}/acp-registry`; - const registryCachePath = `${registryDirectory}/registry.json`; + const registryDirectory = path.join(cacheDir, "acp-registry"); + const registryCachePath = path.join(registryDirectory, "registry.json"); yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); @@ -3962,10 +3965,18 @@ describe("AcpRegistrySupport", () => { const ioDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-io-", }); - const ioRegistryDir = `${ioDir}/acp-registry`; - const ioRegistryPath = `${ioRegistryDir}/registry.json`; - const ioBaselinesPath = `${ioRegistryDir}/legacy-baselines.json`; - const ioLegacyExe = `${ioDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const ioRegistryDir = path.join(ioDir, "acp-registry"); + const ioRegistryPath = path.join(ioRegistryDir, "registry.json"); + const ioBaselinesPath = path.join(ioRegistryDir, "legacy-baselines.json"); + const ioLegacyExe = path.join( + ioDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(ioLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(ioLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(ioLegacyExe, 0o755); @@ -3986,7 +3997,7 @@ describe("AcpRegistrySupport", () => { upstream = binaryAgent("1.0.0", archiveBUrl); const ioResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: ioDir, - toolsDir: `${ioDir}/tools`, + toolsDir: path.join(ioDir, "tools"), registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, flakyBaselinesFs)); yield* ioResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4004,7 +4015,7 @@ describe("AcpRegistrySupport", () => { // Restarting against the recovered disk files must install B instead of reusing legacy A. const restartedIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: ioDir, - toolsDir: `${ioDir}/tools`, + toolsDir: path.join(ioDir, "tools"), registryUrl, }); const resolvedAfterIoRecovery = yield* restartedIoResolver.resolve( @@ -4015,38 +4026,61 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); - // 2b. Non-directory files in the shared tools/ directory (e.g., tools/codex/active.json, - // tools/.DS_Store) must not break legacy baseline scanning or freeze disk registry.json. + // 2b. Non-directory files and unreadable unrelated tool directories in shared tools/ + // (e.g., tools/codex/active.json, tools/.DS_Store, tools/chrome-headless-shell, or a + // non-directory file at a candidate platform slot) must not break legacy baseline scanning. const sharedToolsDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-shared-tools-", }); - const sharedRegistryDir = `${sharedToolsDir}/acp-registry`; - const sharedRegistryPath = `${sharedRegistryDir}/registry.json`; - const sharedBaselinesPath = `${sharedRegistryDir}/legacy-baselines.json`; - const sharedLegacyExe = `${sharedToolsDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const sharedRegistryDir = path.join(sharedToolsDir, "acp-registry"); + const sharedRegistryPath = path.join(sharedRegistryDir, "registry.json"); + const sharedBaselinesPath = path.join(sharedRegistryDir, "legacy-baselines.json"); + const sharedToolsRoot = path.join(sharedToolsDir, "tools"); + const sharedLegacyExe = path.join( + sharedToolsRoot, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(sharedLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(sharedLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(sharedLegacyExe, 0o755); - yield* fileSystem.makeDirectory(`${sharedToolsDir}/tools/codex`, { recursive: true }); + // Place a regular file at a candidate installRoot slot to exercise the directory check. + const nonDirSlotDir = path.join(sharedToolsRoot, "example-agent", "0.9.0"); + yield* fileSystem.makeDirectory(nonDirSlotDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(nonDirSlotDir, "linux-x86_64"), "not-a-dir"); + yield* fileSystem.makeDirectory(path.join(sharedToolsRoot, "codex"), { recursive: true }); yield* fileSystem.writeFileString( - `${sharedToolsDir}/tools/codex/active.json`, + path.join(sharedToolsRoot, "codex", "active.json"), '{"version":"1.0.0"}', ); - yield* fileSystem.writeFileString(`${sharedToolsDir}/tools/.DS_Store`, "finder"); + yield* fileSystem.writeFileString(path.join(sharedToolsRoot, ".DS_Store"), "finder"); + const unreadableOtherTool = path.join(sharedToolsRoot, "chrome-headless-shell"); + yield* fileSystem.makeDirectory(unreadableOtherTool, { recursive: true }); yield* fileSystem.makeDirectory(sharedRegistryDir, { recursive: true }); yield* fileSystem.writeFileString( sharedRegistryPath, makeRegistry(binaryAgent("1.0.0", archiveAUrl)), ); + const sharedToolsFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === unreadableOtherTool + ? fileSystem.readDirectory(sharedLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; upstream = binaryAgent("1.0.0", archiveBUrl); const sharedToolsResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: sharedToolsDir, - toolsDir: `${sharedToolsDir}/tools`, + toolsDir: sharedToolsRoot, registryUrl, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, sharedToolsFs)); yield* sharedToolsResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); expect(yield* fileSystem.readFileString(sharedRegistryPath)).toContain(archiveBUrl); expect(yield* fileSystem.readFileString(sharedBaselinesPath)).toContain(archiveAUrl); + expect(yield* fileSystem.readFileString(sharedBaselinesPath)).not.toContain("0.9.0"); const resolvedWithSharedTools = yield* sharedToolsResolver.resolve( settings(), "/workspace", @@ -4057,15 +4091,22 @@ describe("AcpRegistrySupport", () => { // 2c. An incomplete tools-directory scan during A -> B keeps disk registry.json on A AND // blocks live resolution from launching legacy A as B even before the scan recovers; once - // readable again, the next refresh compares against disk A and records A. + // readable again, recovery persists A and clears the incomplete flag for eligible slots. const scanDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-scan-error-", }); - const scanRegistryDir = `${scanDir}/acp-registry`; - const scanRegistryPath = `${scanRegistryDir}/registry.json`; - const scanBaselinesPath = `${scanRegistryDir}/legacy-baselines.json`; - const scanToolsDir = `${scanDir}/tools`; - const scanLegacyExe = `${scanToolsDir}/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const scanRegistryDir = path.join(scanDir, "acp-registry"); + const scanRegistryPath = path.join(scanRegistryDir, "registry.json"); + const scanBaselinesPath = path.join(scanRegistryDir, "legacy-baselines.json"); + const scanToolsDir = path.join(scanDir, "tools"); + const scanAgentDir = path.join(scanToolsDir, "example-agent"); + const scanLegacyExe = path.join( + scanAgentDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(scanLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(scanLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(scanLegacyExe, 0o755); @@ -4078,7 +4119,7 @@ describe("AcpRegistrySupport", () => { const flakyScanFs: FileSystem.FileSystem = { ...fileSystem, readDirectory: (dirPath, options) => - failToolsScan && dirPath === scanToolsDir + failToolsScan && dirPath === scanAgentDir ? fileSystem.readDirectory(scanLegacyExe, options) : fileSystem.readDirectory(dirPath, options), }; @@ -4098,14 +4139,80 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); + // A failed scan after restart must NOT overwrite a durable legacy baseline with registry.json: + // with legacy A on disk, durable baseline A, and registry.json at B, failing a scan on + // B -> C and rolling back to B while still failing must install B, not run legacy A as B. + const durableScanDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-durable-scan-", + }); + const durableRegistryDir = path.join(durableScanDir, "acp-registry"); + const durableRegistryPath = path.join(durableRegistryDir, "registry.json"); + const durableBaselinesPath = path.join(durableRegistryDir, "legacy-baselines.json"); + const durableToolsDir = path.join(durableScanDir, "tools"); + const durableAgentDir = path.join(durableToolsDir, "example-agent"); + const durableLegacyExe = path.join( + durableAgentDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(durableLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(durableLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(durableLegacyExe, 0o755); + yield* fileSystem.makeDirectory(durableRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + durableRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), + ); + yield* fileSystem.writeFileString( + durableBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": JSON.stringify({ + archive: archiveAUrl, + cmd: "./bin/example-agent", + sha256: null, + }), + }), + ); + const failDurableScanFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === durableAgentDir + ? fileSystem.readDirectory(durableLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + const durableScanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: durableScanDir, + toolsDir: durableToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failDurableScanFs)); + upstream = binaryAgent("1.0.0", archiveCUrl); + yield* durableScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* durableScanResolver.invalidateIndex(); + yield* durableScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAgainstDurable = yield* durableScanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAgainstDurable.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + // A transient I/O error reading registry.json during baseline discovery must also keep // disk registry.json untouched rather than treating it as missing. const regIoDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-reg-io-", }); - const regIoRegistryDir = `${regIoDir}/acp-registry`; - const regIoRegistryPath = `${regIoRegistryDir}/registry.json`; - const regIoLegacyExe = `${regIoDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const regIoRegistryDir = path.join(regIoDir, "acp-registry"); + const regIoRegistryPath = path.join(regIoRegistryDir, "registry.json"); + const regIoLegacyExe = path.join( + regIoDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(regIoLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(regIoLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(regIoLegacyExe, 0o755); @@ -4123,7 +4230,7 @@ describe("AcpRegistrySupport", () => { }; const regIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: regIoDir, - toolsDir: `${regIoDir}/tools`, + toolsDir: path.join(regIoDir, "tools"), registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, failRegistryReadFs)); yield* regIoResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4140,11 +4247,32 @@ describe("AcpRegistrySupport", () => { yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveBUrl); expect(yield* fileSystem.readFileString(scanBaselinesPath)).toContain(archiveAUrl); + // Once the scan recovers and baselines persist, legacyBaselineDiscoveryIncomplete is reset + // so an eligible unreceipted legacy slot at a matching version can be reused cleanly. + const scanLegacyV2Exe = path.join( + scanAgentDir, + "2.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(scanLegacyV2Exe), { recursive: true }); + yield* fileSystem.writeFileString(scanLegacyV2Exe, "#!/bin/sh\necho legacy-v2\n"); + yield* fileSystem.chmod(scanLegacyV2Exe, 0o755); + upstream = binaryAgent("2.0.0", archiveCUrl); + yield* scanResolver.invalidateIndex(); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reusedAfterRecovery = yield* scanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(reusedAfterRecovery.spawn.command)).toBe( + "#!/bin/sh\necho legacy-v2\n", + ); + upstream = binaryAgent("1.0.0", archiveBUrl); const restartedScanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: scanDir, toolsDir: scanToolsDir, registryUrl, }); + yield* restartedScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const resolvedAfterScanRecovery = yield* restartedScanResolver.resolve( settings(), "/workspace", @@ -4240,9 +4368,46 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); - // Add another agent's baseline entry, uninstall example-agent, and verify only example-agent is pruned. + // Add another agent's baseline and launch-options sidecar entries, uninstall example-agent, + // and verify only example-agent is pruned from both stores. rebuiltBaselines[otherSlotKey] = "other-baseline"; yield* fileSystem.writeFileString(corruptBaselinesPath, JSON.stringify(rebuiltBaselines)); + const corruptSidecarPath = path.join(corruptRegistryDir, "binary-launch-options.json"); + const exampleSlotRoot = path.join( + corruptDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + ); + const otherSlotRoot = path.join( + corruptDir, + "tools", + "other-agent", + "1.0.0", + "linux-x86_64", + ); + yield* fileSystem.writeFileString( + corruptSidecarPath, + JSON.stringify({ + [exampleSlotRoot]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--old"], + launchOptionsRevision: 1, + }, + [otherSlotRoot]: { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--keep"], + launchOptionsRevision: 1, + }, + }), + ); expect(yield* corruptResolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual( { agentId: "example-agent", @@ -4254,6 +4419,11 @@ describe("AcpRegistrySupport", () => { ) as Record; expect(prunedBaselines[exampleSlotKey]).toBeUndefined(); expect(prunedBaselines[otherSlotKey]).toBe("other-baseline"); + const prunedSidecar = JSON.parse( + yield* fileSystem.readFileString(corruptSidecarPath), + ) as Record; + expect(prunedSidecar[exampleSlotRoot]).toBeUndefined(); + expect(prunedSidecar[otherSlotRoot]).toBeDefined(); }).pipe( Effect.scoped, Effect.provide( @@ -4627,6 +4797,9 @@ describe("AcpRegistrySupport", () => { // Model POSIX mode bits in memory so Linux mode assertions work identically on Windows. const modeOverrides = new Map(); let failReceiptTempWrite = false; + let failSidecarWrite = false; + let failSidecarRead = false; + let receiptRenameCount = 0; let onStatPath: { readonly matchPath: string; readonly onHit: () => void; @@ -4653,10 +4826,23 @@ describe("AcpRegistrySupport", () => { : { ...info, mode: (info.mode & ~0o777) | override }; }), ), + readFileString: (filePath, encoding) => + failSidecarRead && path.basename(filePath) === "binary-launch-options.json" + ? fileSystem.readFileString(path.dirname(filePath), encoding) + : fileSystem.readFileString(filePath, encoding), writeFileString: (filePath, data, options) => - failReceiptTempWrite && path.basename(filePath).startsWith(".t3-artifact.json.") + (failReceiptTempWrite && path.basename(filePath).startsWith(".t3-artifact.json.")) || + (failSidecarWrite && + path.basename(filePath).startsWith("binary-launch-options.json.") && + filePath.endsWith(".tmp")) ? fileSystem.readFileString(path.dirname(filePath)).pipe(Effect.asVoid) : fileSystem.writeFileString(filePath, data, options), + rename: (oldPath, newPath) => + Effect.sync(() => { + if (path.basename(newPath) === ".t3-artifact.json") { + receiptRenameCount += 1; + } + }).pipe(Effect.andThen(fileSystem.rename(oldPath, newPath))), }; // 1. A raw binary declaring .t3-artifact.json as its command fails with archive_invalid @@ -4674,11 +4860,37 @@ describe("AcpRegistrySupport", () => { .pipe(Effect.flip); expect(reservedError.reason).toBe("archive_invalid"); - // 2. Updating args/env syncs the receipt; if writing into tools/ fails, updated launch - // options persist in registry cache storage so fallback still restores them across restarts. + // 2. Unchanged no-env binaries skip receipt rewrites; updating args/env syncs the receipt; + // failed receipt writes persist in binary-launch-options.json across restarts without + // letting stale sidecar entries shadow newer receipts or dropping other slots on read errors. + const noEnvDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-no-env-skip-", + }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + }); + const noEnvResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: noEnvDir, + toolsDir: path.join(noEnvDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* noEnvResolver.resolve(settings(), "/workspace"); + receiptRenameCount = 0; + yield* noEnvResolver.resolve(settings(), "/workspace"); + yield* noEnvResolver.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + const supersededDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-superseded-inspect-", }); + const supersededToolsDir = path.join(supersededDir, "tools"); + const supersededSidecarPath = path.join( + supersededDir, + "acp-registry", + "binary-launch-options.json", + ); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -4687,7 +4899,7 @@ describe("AcpRegistrySupport", () => { }); const supersededResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: supersededDir, - toolsDir: `${supersededDir}/tools`, + toolsDir: supersededToolsDir, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); const installedA = yield* supersededResolver.resolve(settings(), "/workspace"); @@ -4707,7 +4919,8 @@ describe("AcpRegistrySupport", () => { expect(syncedA.spawn.args).toEqual(["--v1", "--updated"]); expect(syncedA.spawn.env?.STAGE).toBe("updated"); - // Simulate a failed receipt write on a second args/env update, then restart and fail 2.0.0. + // Failed receipt write persists --sidecar; reverting back to the receipt's --updated in the + // SAME process must update/clear the sidecar so fallback does not resurrect --sidecar. failReceiptTempWrite = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -4720,15 +4933,92 @@ describe("AcpRegistrySupport", () => { const sidecarSyncedA = yield* supersededResolver.resolve(settings(), "/workspace"); expect(sidecarSyncedA.spawn.args).toEqual(["--v1", "--sidecar"]); expect(sidecarSyncedA.spawn.env?.STAGE).toBe("sidecar"); + + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const sameProcessRevertFallback = yield* supersededResolver.resolve( + settings(), + "/workspace", + ); + expect(sameProcessRevertFallback.fallback).toBe(true); + expect(sameProcessRevertFallback.spawn.args).toEqual(["--v1", "--updated"]); + expect(sameProcessRevertFallback.spawn.env?.STAGE).toBe("updated"); + + // Write --sidecar to the sidecar again, restart, and verify fallback restores --sidecar. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar"], + env: { STAGE: "sidecar" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); failReceiptTempWrite = false; + // A transient read failure on binary-launch-options.json must leave existing sidecar + // entries intact instead of replacing the file with an empty/partial map. + const preserveSlotKey = path.join( + supersededToolsDir, + "other-agent", + "1.0.0", + "linux-x86_64", + ); + const sidecarBeforeIo = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + yield* fileSystem.writeFileString( + supersededSidecarPath, + JSON.stringify({ + ...sidecarBeforeIo, + [preserveSlotKey]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--preserve"], + launchOptionsRevision: 1, + }, + }), + ); + failReceiptTempWrite = true; + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar-io"], + env: { STAGE: "sidecar-io" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarRead = false; + const sidecarAfterIo = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + expect(sidecarAfterIo[preserveSlotKey]).toBeDefined(); + upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", }); const restartedSuperseded = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: supersededDir, - toolsDir: `${supersededDir}/tools`, + toolsDir: supersededToolsDir, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4738,8 +5028,9 @@ describe("AcpRegistrySupport", () => { expect(fallbackA.spawn.args).toEqual(["--v1", "--sidecar"]); expect(fallbackA.spawn.env?.STAGE).toBe("sidecar"); - // Reverting upstream back to the receipt's earlier args/env after restart must prune/update - // the stale sidecar so a subsequent fallback does not resurrect the older sidecar options. + // Reverting upstream back to the receipt's earlier args/env after restart prunes the + // sidecar and persists the new generation; verify with ANOTHER fresh catalog instance. + const exampleSlotRootSuperseded = path.dirname(path.dirname(installedA.spawn.command)); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -4751,32 +5042,110 @@ describe("AcpRegistrySupport", () => { const revertedA = yield* restartedSuperseded.resolve(settings(), "/workspace"); expect(revertedA.spawn.args).toEqual(["--v1", "--updated"]); expect(revertedA.spawn.env?.STAGE).toBe("updated"); + const sidecarAfterRevert = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + expect(sidecarAfterRevert[exampleSlotRootSuperseded]).toBeUndefined(); + expect(sidecarAfterRevert[preserveSlotKey]).toBeDefined(); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - yield* restartedSuperseded.invalidateIndex(); - yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const fallbackAfterRevert = yield* restartedSuperseded.resolve(settings(), "/workspace"); + const afterRevertCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterRevert = yield* afterRevertCatalog.resolve(settings(), "/workspace"); expect(fallbackAfterRevert.fallback).toBe(true); expect(fallbackAfterRevert.spawn.args).toEqual(["--v1", "--updated"]); expect(fallbackAfterRevert.spawn.env?.STAGE).toBe("updated"); + // A newer receipt write followed by a failed sidecar prune must still win over the older + // unpruned sidecar entry after restart. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--stale-sidecar"], + env: { STAGE: "stale-sidecar" }, + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* afterRevertCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--newer-receipt"], + env: { STAGE: "newer-receipt" }, + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* afterRevertCatalog.resolve(settings(), "/workspace"); + failSidecarWrite = false; + // Confirm the stale sidecar entry is still present on disk while the receipt has higher rev. + const unprunedSidecar = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record }>; + expect(unprunedSidecar[exampleSlotRootSuperseded]?.args).toEqual([ + "--v1", + "--stale-sidecar", + ]); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const newerReceiptCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* newerReceiptCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackNewerReceipt = yield* newerReceiptCatalog.resolve(settings(), "/workspace"); + expect(fallbackNewerReceipt.fallback).toBe(true); + expect(fallbackNewerReceipt.spawn.args).toEqual(["--v1", "--newer-receipt"]); + expect(fallbackNewerReceipt.spawn.env?.STAGE).toBe("newer-receipt"); + + // Uninstalling clears in-memory launch options too so reinstalling uses the new receipt. + expect( + yield* afterRevertCatalog.uninstallManagedBinary({ agentId: "example-agent" }), + ).toEqual({ agentId: "example-agent", removed: true }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-after-uninstall"], + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reinstalledA = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterReinstall = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + expect(fallbackAfterReinstall.fallback).toBe(true); + expect(fallbackAfterReinstall.spawn.args).toEqual(["--fresh-after-uninstall"]); + // 3. A superseded primary executable that lost execute permission must not fail inspect() // when the registry selects a different same-version artifact. - yield* posixModeFs.chmod(installedA.spawn.command, 0o644); + yield* posixModeFs.chmod(reinstalledA.spawn.command, 0o644); upstream = makeBinary("1.0.0", { archive: archiveBUrl, cmd: "./bin/example-agent", }); - yield* restartedSuperseded.invalidateIndex(); - yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect(yield* restartedSuperseded.inspect(settings())).toMatchObject({ + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* afterRevertCatalog.inspect(settings())).toMatchObject({ status: "ready", version: "1.0.0", }); - const installedB = yield* restartedSuperseded.resolve(settings(), "/workspace"); - expect(installedB.spawn.command).not.toBe(installedA.spawn.command); + const installedB = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + expect(installedB.spawn.command).not.toBe(reinstalledA.spawn.command); expect(yield* fileSystem.readFileString(installedB.spawn.command)).toBe( "#!/bin/sh\necho receipt-b\n", ); @@ -4785,13 +5154,13 @@ describe("AcpRegistrySupport", () => { const lockDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-lock-interrupt-", }); - const versionDir = `${lockDir}/tools/example-agent/1.0.0`; + const versionDir = path.join(lockDir, "tools", "example-agent", "1.0.0"); yield* fileSystem.makeDirectory(versionDir, { recursive: true }); - const lockFile = `${versionDir}/linux-x86_64.lock`; + const lockFile = path.join(versionDir, "linux-x86_64.lock"); yield* fileSystem.writeFileString(lockFile, "other-holder-token"); const lockResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: lockDir, - toolsDir: `${lockDir}/tools`, + toolsDir: path.join(lockDir, "tools"), registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); const lockFirstStat = yield* Deferred.make(); @@ -4820,16 +5189,26 @@ describe("AcpRegistrySupport", () => { // Interrupting while waiting must leave the other holder's lock intact. expect(yield* fileSystem.readFileString(lockFile)).toBe("other-holder-token"); - // 5. A stale legacy-baselines lock holder neither overwrites a newer holder's baselines - // nor deletes the newer holder's lock file on release. + // 5. A stale lock holder neither overwrites a newer holder's baselines or launch-options + // sidecar nor deletes the newer holder's lock file on release (for both refresh & uninstall). const fenceDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-fence-", }); - const fenceRegistryDir = `${fenceDir}/acp-registry`; - const fenceRegistryPath = `${fenceRegistryDir}/registry.json`; - const fenceBaselinesPath = `${fenceRegistryDir}/legacy-baselines.json`; + const fenceRegistryDir = path.join(fenceDir, "acp-registry"); + const fenceRegistryPath = path.join(fenceRegistryDir, "registry.json"); + const fenceBaselinesPath = path.join(fenceRegistryDir, "legacy-baselines.json"); const fenceLockPath = `${fenceBaselinesPath}.lock`; - const fenceLegacyExe = `${fenceDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const fenceSidecarPath = path.join(fenceRegistryDir, "binary-launch-options.json"); + const fenceSidecarLockPath = `${fenceSidecarPath}.lock`; + const fenceToolsDir = path.join(fenceDir, "tools"); + const fenceLegacyExe = path.join( + fenceToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(fenceLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(fenceLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* posixModeFs.chmod(fenceLegacyExe, 0o755); @@ -4842,6 +5221,14 @@ describe("AcpRegistrySupport", () => { const releaseHolder1 = yield* Deferred.make(); let gatedHolder1 = true; let baselinesReadCount = 0; + let sidecarFenceGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let uninstallFenceGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; const fencedFs: FileSystem.FileSystem = { ...posixModeFs, readFileString: (filePath, encoding) => { @@ -4855,13 +5242,29 @@ describe("AcpRegistrySupport", () => { ); } } + if (uninstallFenceGate !== null && filePath === fenceBaselinesPath) { + const gate = uninstallFenceGate; + uninstallFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + if (sidecarFenceGate !== null && filePath === fenceSidecarPath) { + const gate = sidecarFenceGate; + sidecarFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } return posixModeFs.readFileString(filePath, encoding); }, }; upstream = makeBinary("1.0.0", { archive: archiveBUrl, cmd: "./bin/example-agent" }); const holder1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: fenceDir, - toolsDir: `${fenceDir}/tools`, + toolsDir: fenceToolsDir, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, fencedFs)); const holder1Refresh = yield* holder1 @@ -4880,6 +5283,78 @@ describe("AcpRegistrySupport", () => { expect(JSON.parse(yield* fileSystem.readFileString(fenceBaselinesPath))).toEqual({ "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", }); + + // Sidecar lock-ownership fence: losing the sidecar lock before writing leaves holder-2 intact. + yield* fileSystem.remove(fenceLockPath, { force: true }); + yield* holder1.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--fenced-sidecar"], + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const sidecarHolder1Entered = yield* Deferred.make(); + const releaseSidecarHolder1 = yield* Deferred.make(); + sidecarFenceGate = { entered: sidecarHolder1Entered, release: releaseSidecarHolder1 }; + const fencedSidecarResolve = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(sidecarHolder1Entered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-2"); + yield* fileSystem.writeFileString( + fenceSidecarPath, + JSON.stringify({ + "keep-slot": { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/keep", + sha256: null, + args: ["--holder-2"], + launchOptionsRevision: 1, + }, + }), + ); + yield* Deferred.succeed(releaseSidecarHolder1, undefined); + yield* Fiber.join(fencedSidecarResolve); + failReceiptTempWrite = false; + expect(yield* fileSystem.readFileString(fenceSidecarLockPath)).toBe("sidecar-holder-2"); + expect( + Object.keys(JSON.parse(yield* fileSystem.readFileString(fenceSidecarPath)) as object), + ).toEqual(["keep-slot"]); + + // Uninstall baselines prune lock-ownership fence: losing the lock leaves holder-2 intact. + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": "stale-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }), + ); + const uninstallEntered = yield* Deferred.make(); + const releaseUninstall = yield* Deferred.make(); + uninstallFenceGate = { entered: uninstallEntered, release: releaseUninstall }; + const fencedUninstall = yield* holder1 + .uninstallManagedBinary({ agentId: "example-agent" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(uninstallEntered); + yield* fileSystem.writeFileString(fenceLockPath, "uninstall-holder-2"); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": "holder-2-new-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }), + ); + yield* Deferred.succeed(releaseUninstall, undefined); + yield* Fiber.join(fencedUninstall); + expect(yield* fileSystem.readFileString(fenceLockPath)).toBe("uninstall-holder-2"); + expect(JSON.parse(yield* fileSystem.readFileString(fenceBaselinesPath))).toEqual({ + "example-agent\u00001.0.0\u0000linux-x86_64": "holder-2-new-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 9881a43c2ab27..051e1d7bb8b06 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -741,6 +741,7 @@ const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ sha256: Schema.NullOr(Schema.String), args: Schema.optional(Schema.Array(Schema.String)), env: Schema.optional(Schema.Record(Schema.String, Schema.String)), + launchOptionsRevision: Schema.optional(Schema.Finite), }); type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt.Type; const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( @@ -754,6 +755,33 @@ const decodeBinaryLaunchOptionsStore = Schema.decodeUnknownOption( Schema.fromJsonString(AcpRegistryBinaryLaunchOptionsStore), ); +type BinaryLaunchOptionsReadResult = + | { + readonly status: "ok"; + readonly entries: Readonly>; + } + | { readonly status: "corrupt" } + | { readonly status: "io_error" }; + +function readBinaryLaunchOptionsFile( + fileSystem: FileSystem.FileSystem, + launchOptionsPath: string, +): Effect.Effect { + return fileSystem.readFileString(launchOptionsPath).pipe( + Effect.map((raw): BinaryLaunchOptionsReadResult => { + const decoded = decodeBinaryLaunchOptionsStore(raw); + return Option.isSome(decoded) + ? { status: "ok", entries: decoded.value } + : { status: "corrupt" }; + }), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" ? { status: "ok", entries: {} } : { status: "io_error" }, + ), + ), + ); +} + const AcpRegistryLegacyBaselines = Schema.Record(Schema.String, Schema.String); const decodeLegacyBaselines = Schema.decodeUnknownOption( Schema.fromJsonString(AcpRegistryLegacyBaselines), @@ -893,6 +921,7 @@ function binaryArtifactReceiptMatches( function encodeBinaryArtifactReceipt( agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type, + launchOptionsRevision?: number, ): string { return JSON.stringify({ version: agent.version, @@ -901,6 +930,7 @@ function encodeBinaryArtifactReceipt( sha256: target.sha256 ?? null, ...(target.args && target.args.length > 0 ? { args: target.args } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: target.env } : {}), + ...(launchOptionsRevision !== undefined ? { launchOptionsRevision } : {}), }); } @@ -1451,16 +1481,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); - const readBinaryLaunchOptionsFile = fileSystem.readFileString(binaryLaunchOptionsPath).pipe( - Effect.map((raw) => - Option.getOrElse( - decodeBinaryLaunchOptionsStore(raw), - (): Readonly> => ({}), - ), - ), - Effect.orElseSucceed((): Readonly> => ({})), - ); - const withBinaryLaunchOptionsLock = ( use: (isLockOwned: Effect.Effect) => Effect.Effect, ) => @@ -1527,74 +1547,105 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } return directories; }); - const scanUnreceiptedLegacySlots = Effect.gen(function* () { - const slots: Array<{ - readonly agentId: string; - readonly encodedVersion: string; - readonly candidateTarget: AcpRegistryPlatformTarget; - readonly slotKey: string; - }> = []; - for (const agentId of yield* listSubdirectories(installsDirectory)) { - const agentRoot = path.join(installsDirectory, agentId); - for (const encodedVersion of yield* listSubdirectories(agentRoot)) { - const versionRoot = path.join(agentRoot, encodedVersion); - for (const candidateTarget of candidates) { - const installRoot = path.join(versionRoot, candidateTarget); - const installStat = yield* fileSystem.stat(installRoot).pipe( + const scanUnreceiptedLegacySlots = Effect.fn("AcpRegistryCatalog.scanUnreceiptedLegacySlots")( + function* (agentIds: ReadonlyArray | undefined) { + const slots: Array<{ + readonly agentId: string; + readonly encodedVersion: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly slotKey: string; + }> = []; + const targetAgentIds = + agentIds === undefined ? yield* listSubdirectories(installsDirectory) : agentIds; + for (const agentId of targetAgentIds) { + const agentRoot = path.join(installsDirectory, agentId); + if (agentIds !== undefined) { + const agentStat = yield* fileSystem.stat(agentRoot).pipe( Effect.map((info) => ({ status: "ok" as const, info })), Effect.catchIf( (error) => error.reason._tag === "NotFound", () => Effect.succeed({ status: "missing" as const }), ), ); - if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; - if (yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME))) - continue; - slots.push({ - agentId, - encodedVersion, - candidateTarget, - slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), - }); + if (agentStat.status !== "ok" || agentStat.info.type !== "Directory") continue; } - } - } - return slots; - }); - const scanResult = yield* Effect.result(scanUnreceiptedLegacySlots); - if (Result.isFailure(scanResult)) { - legacyBaselineDiscoveryIncomplete = true; - // Record every diverging binary slot from the previous index in memory so live resolution - // cannot reuse a superseded legacy executable before the directory scan recovers. - const diskIndexResult = yield* readDiskPreviousIndex(); - const previousIndex = - diskIndexResult.status === "ok" ? diskIndexResult.index : inMemoryPrevious; - if (previousIndex !== undefined) { - const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); - for (const previousAgent of previousIndex.agents) { - const encodedVersion = encodeURIComponent(previousAgent.version); - for (const candidateTarget of candidates) { - const previousTarget = previousAgent.distribution.binary?.[candidateTarget]; - if (previousTarget === undefined) continue; - const slotKey = legacyBaselineSlotKey( - previousAgent.id, - encodedVersion, - candidateTarget, - ); - if (legacyBaselineBySlotKey.has(slotKey)) continue; - const previousKey = binaryArtifactIdentityKey(previousTarget); - const nextAgent = nextById.get(previousAgent.id); - const nextTarget = - nextAgent !== undefined && encodeURIComponent(nextAgent.version) === encodedVersion - ? nextAgent.distribution.binary?.[candidateTarget] - : undefined; - if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { - continue; + for (const encodedVersion of yield* listSubdirectories(agentRoot)) { + const versionRoot = path.join(agentRoot, encodedVersion); + for (const candidateTarget of candidates) { + const installRoot = path.join(versionRoot, candidateTarget); + const installStat = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; + if ( + yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + ) + continue; + slots.push({ + agentId, + encodedVersion, + candidateTarget, + slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), + }); } - legacyBaselineBySlotKey.set(slotKey, previousKey); } } - } + return slots; + }, + ); + + const installsStat = yield* fileSystem.stat(installsDirectory).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + Effect.orElseSucceed(() => ({ status: "io_error" as const })), + ); + if (installsStat.status === "missing") { + legacyBaselineDiscoveryIncomplete = false; + return true; + } + if (installsStat.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not inspect managed ACP binary directory for legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + + const initialDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + const initialDiskIndex = yield* readDiskPreviousIndex(); + if (initialDiskIndex.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not read cached ACP Registry index for legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + // Scope normal scans to ACP agent directories referenced by the previous/next index or + // in-memory baselines so unrelated entries in shared tools/ never block registry refreshes. + // Walk all of tools/ only when rebuilding a corrupt baselines file. + const scopedAgentIds = + initialDisk.status === "corrupt" + ? undefined + : Array.from( + new Set([ + ...nextIndex.agents.map((agent) => agent.id), + ...(initialDiskIndex.status === "ok" + ? initialDiskIndex.index.agents.map((agent) => agent.id) + : []), + ...(inMemoryPrevious?.agents.map((agent) => agent.id) ?? []), + ...Array.from(legacyBaselineBySlotKey.keys(), (key) => key.split("\0")[0] ?? ""), + ]), + ).filter((id) => id.length > 0); + const scanResult = yield* Effect.result(scanUnreceiptedLegacySlots(scopedAgentIds)); + if (Result.isFailure(scanResult)) { + legacyBaselineDiscoveryIncomplete = true; yield* Effect.logDebug( "Could not scan managed ACP binary directories for legacy baselines; keeping existing disk registry cache.", ); @@ -1685,7 +1736,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); - const initialDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); if ( initialDisk.status === "ok" && unreceiptedLegacySlots.every((slot) => initialDisk.baselines[slot.slotKey] !== undefined) @@ -1714,6 +1764,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } let mergedBaselines: Record; if (disk.status === "corrupt") { + const corruptScanSlots = + scopedAgentIds === undefined + ? unreceiptedLegacySlots + : yield* Effect.result(scanUnreceiptedLegacySlots(undefined)).pipe( + Effect.map((result) => (Result.isSuccess(result) ? result.success : null)), + ); + if (corruptScanSlots === null) { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not scan managed ACP binary directories while rebuilding corrupt legacy baselines; keeping existing disk registry cache.", + ); + return false; + } // Copy the corrupt bytes aside before atomically replacing legacy-baselines.json so there // is no missing-file window. Never reconstruct provenance from the unverified cached // registry index; preserve only baselines already verified in memory and mark others @@ -1722,7 +1785,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .copyFile(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) .pipe(Effect.ignore); mergedBaselines = {}; - for (const slot of unreceiptedLegacySlots) { + for (const slot of corruptScanSlots) { const baseline = legacyBaselineBySlotKey.get(slot.slotKey) ?? LEGACY_BASELINE_UNKNOWN; mergedBaselines[slot.slotKey] = baseline; legacyBaselineBySlotKey.set(slot.slotKey, baseline); @@ -2557,21 +2620,47 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if ( memoryStored !== undefined && Equal.equals(memoryStored.args ?? [], target.args ?? []) && - Equal.equals(memoryStored.env ?? {}, target.env ?? []) + Equal.equals(memoryStored.env ?? {}, target.env ?? {}) ) { return; } - const hasSidecar = - memoryStored === undefined && - (yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false))); - const diskStored = hasSidecar ? (yield* readBinaryLaunchOptionsFile)[slot.root] : undefined; - if ( - diskStored === undefined && + const hasSidecar = yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false)); + const diskResult = hasSidecar + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); + const diskStored = diskResult.status === "ok" ? diskResult.entries[slot.root] : undefined; + const receiptRev = slot.receipt.launchOptionsRevision ?? 0; + const diskRev = diskStored?.launchOptionsRevision ?? 0; + const memoryRev = memoryStored?.launchOptionsRevision ?? 0; + const receiptMatchesTarget = Equal.equals(slot.receipt.args ?? [], target.args ?? []) && - Equal.equals(slot.receipt.env ?? {}, target.env ?? []) - ) { - return; + Equal.equals(slot.receipt.env ?? {}, target.env ?? {}); + if (memoryStored === undefined && receiptMatchesTarget) { + if (diskStored === undefined) return; + if (diskRev <= receiptRev) { + // Prune an older sidecar left behind by a prior cleanup failure without rewriting receipt. + yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const current = yield* readBinaryLaunchOptionsFile( + fileSystem, + binaryLaunchOptionsPath, + ); + if (current.status !== "ok") return; + const existing = current.entries[slot.root]; + if (existing === undefined || (existing.launchOptionsRevision ?? 0) > receiptRev) { + return; + } + if (!(yield* isLockOwned)) return; + const { [slot.root]: _removed, ...rest } = current.entries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest); + }), + ).pipe(Effect.ignore); + return; + } } + const nextRevision = Math.max(receiptRev, diskRev, memoryRev) + 1; const updatedReceipt: AcpRegistryBinaryArtifactReceipt = { version: agent.version, archive: target.archive, @@ -2579,6 +2668,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct sha256: target.sha256 ?? null, ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), + launchOptionsRevision: nextRevision, }; syncedLaunchOptionsBySlotRoot.set(slot.root, updatedReceipt); const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); @@ -2587,7 +2677,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.flatMap((id) => { const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; return fileSystem - .writeFileString(temporaryPath, encodeBinaryArtifactReceipt(agent, target)) + .writeFileString( + temporaryPath, + encodeBinaryArtifactReceipt(agent, target, nextRevision), + ) .pipe( Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), Effect.ensuring( @@ -2598,16 +2691,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); if (Result.isSuccess(receiptWrite)) { - // Keep the slot receipt authoritative by pruning any stale fallback sidecar entry. + // Keep the slot receipt authoritative by pruning any older fallback sidecar entry. if ( yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false)) ) { yield* withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { - const current = yield* readBinaryLaunchOptionsFile; - if (current[slot.root] === undefined) return; + const current = yield* readBinaryLaunchOptionsFile( + fileSystem, + binaryLaunchOptionsPath, + ); + if (current.status !== "ok") return; + const existing = current.entries[slot.root]; + if (existing === undefined || (existing.launchOptionsRevision ?? 0) > nextRevision) { + return; + } if (!(yield* isLockOwned)) return; - const { [slot.root]: _removed, ...rest } = current; + const { [slot.root]: _removed, ...rest } = current.entries; yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest); }), ).pipe(Effect.ignore); @@ -2619,10 +2719,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // restores the last-resolved args and env even across restarts. yield* withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { - const current = yield* readBinaryLaunchOptionsFile; + const current = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); + if (current.status !== "ok") return; + const existing = current.entries[slot.root]; + if (existing !== undefined && (existing.launchOptionsRevision ?? 0) > nextRevision) { + return; + } if (!(yield* isLockOwned)) return; yield* writeJsonFileAtomically(binaryLaunchOptionsPath, { - ...current, + ...current.entries, [slot.root]: updatedReceipt, }); }), @@ -3323,20 +3428,24 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); if (Option.isNone(validated)) continue; const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir); - const diskOverride = + const diskOverrideResult = memoryOverride !== undefined - ? undefined + ? ({ status: "ok", entries: {} } as const) : (yield* fileSystem .exists(binaryLaunchOptionsPath) .pipe(Effect.orElseSucceed(() => false))) - ? (yield* readBinaryLaunchOptionsFile)[dir] - : undefined; + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); + const diskOverride = + diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; const candidateOverride = memoryOverride ?? diskOverride; const effectiveReceipt = candidateOverride !== undefined && candidateOverride.archive === receipt.archive && candidateOverride.cmd === receipt.cmd && - (candidateOverride.sha256 ?? null) === (receipt.sha256 ?? null) + (candidateOverride.sha256 ?? null) === (receipt.sha256 ?? null) && + (candidateOverride.launchOptionsRevision ?? 0) > + (receipt.launchOptionsRevision ?? 0) ? candidateOverride : receipt; const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); @@ -3705,17 +3814,23 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct hasLaunchOptionsFile ? withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { - const disk = yield* readBinaryLaunchOptionsFile; + const disk = yield* readBinaryLaunchOptionsFile( + fileSystem, + binaryLaunchOptionsPath, + ); + if (disk.status !== "ok") return; const removedAgentRoot = path.join(installsDirectory, removedAgentId); const removedPrefix = `${removedAgentRoot}${path.sep}`; const remaining = Object.fromEntries( - Object.entries(disk).filter( + Object.entries(disk.entries).filter( ([slotRoot]) => slotRoot !== removedAgentRoot && !slotRoot.startsWith(removedPrefix), ), ); - if (Object.keys(remaining).length !== Object.keys(disk).length) { + if ( + Object.keys(remaining).length !== Object.keys(disk.entries).length + ) { if (!(yield* isLockOwned)) return; yield* writeJsonFileAtomically(binaryLaunchOptionsPath, remaining); } diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 722c4d6658f16..1880c38dc3085 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3584,12 +3584,42 @@ describe("AcpRegistryDriver registry recovery", () => { const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( "acp-driver-reconcile-edge-", ); + const authFailAgentPath = path.join(directory, "auth-fail-agent.mjs"); + yield* fileSystem.writeFileString( + authFailAgentPath, + ` +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: [{ id: "api-key", name: "API key", type: "env_var", vars: [{ name: "API_KEY" }] }], + agentInfo: { name: "fake", version: "2.0.0" }, + }, + }); + } else if (method === "session/new") { + send({ id, error: { code: -32000, message: "Authentication required" } }); + } else { + send({ id, result: {} }); + } +}); +`, + ); let remoteVersion = "1.0.0"; let remoteExtraAgentVersion: string | undefined = undefined; let failArchiveVersions = new Set(); let failProbeSpawn = false; + let failProbeAuth = false; + let defectNextInspect = false; let inspectCalls = 0; + let recordedInspectRevisions: Array | null = null; let resolveGate: { readonly matchVersion: string; readonly started: Deferred.Deferred; @@ -3603,19 +3633,28 @@ describe("AcpRegistryDriver registry recovery", () => { readonly matchName: string; readonly done: Deferred.Deferred; } | null = null; - let onInspectCallback: (() => Effect.Effect) | null = null; let onEnrichmentEnd: (() => void) | null = null; + let onReconcileEnd: ((exit: Exit.Exit) => void) | null = null; const enrichmentTracer: Tracer.Tracer = { span(options) { const inner = Tracer.nativeTracer.span(options); - if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + if ( + options.name !== "AcpRegistryDriver.publishEnrichment" && + options.name !== "AcpRegistryDriver.reconcileUnmatchedRuntime" + ) { + return inner; + } const origEnd = inner.end.bind(inner); inner.end = (endTime, exit) => { origEnd(endTime, exit); - if (Exit.isSuccess(exit)) { + if (options.name === "AcpRegistryDriver.publishEnrichment" && Exit.isSuccess(exit)) { const cb = onEnrichmentEnd; onEnrichmentEnd = null; cb?.(); + } else if (options.name === "AcpRegistryDriver.reconcileUnmatchedRuntime") { + const cb = onReconcileEnd; + onReconcileEnd = null; + cb?.(exit); } }; return inner; @@ -3686,16 +3725,22 @@ describe("AcpRegistryDriver registry recovery", () => { inspect: (settings, environment) => Effect.gen(function* () { inspectCalls += 1; + if (defectNextInspect) { + defectNextInspect = false; + return yield* Effect.die("simulated reconcile inspect defect"); + } const result = yield* realCatalog.inspect(settings, environment); + if (recordedInspectRevisions !== null) { + recordedInspectRevisions.push( + "indexRevision" in result ? result.indexRevision : undefined, + ); + } if (inspectGate !== null) { const gate = inspectGate; inspectGate = null; yield* Deferred.succeed(gate.started, undefined); yield* Deferred.await(gate.release); } - if (onInspectCallback !== null) { - yield* onInspectCallback(); - } return result; }), resolve: (settings, cwd, environment) => @@ -3719,14 +3764,22 @@ describe("AcpRegistryDriver registry recovery", () => { } return { ...resolved, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + spawn: { + command: process.execPath, + args: + environment?.MISE_OFFLINE === "1" && failProbeAuth + ? [authFailAgentPath] + : [agentPath, modelsPath], + }, }; }), }; - // 1. Foreground startup skips initial 1.0.0 probe while live 1.0.0 session publishes models - // and commands; when 2.0.0 later fails to probe, snapshot must stay on 1.0.0 (not 2.0.0). - const fgInstanceId = ProviderInstanceId.make("acpRegistry_fg_only_v1"); + // 1. Foreground startup skips initial 1.0.0 probe while live 1.0.0 sessions publish config + // only OR commands only; when 2.0.0 later fails (including authentication_failed), each + // snapshot retains 1.0.0 without copying 2.0.0's unauthenticated state onto 1.0.0. + const fgConfigOnlyId = ProviderInstanceId.make("acpRegistry_fg_config_only_v1"); + const fgCmdOnlyId = ProviderInstanceId.make("acpRegistry_fg_cmd_only_v1"); const fgStarted = yield* Deferred.make(); const releaseFg = yield* Deferred.make(); const fgFiber = yield* coordinator @@ -3737,9 +3790,22 @@ describe("AcpRegistryDriver registry recovery", () => { .pipe(Effect.forkScoped({ startImmediately: true })); yield* Deferred.await(fgStarted); - const fgInstance = yield* AcpRegistryDriver.create({ - instanceId: fgInstanceId, - displayName: "FG Only", + const fgConfigInstance = yield* AcpRegistryDriver.create({ + instanceId: fgConfigOnlyId, + displayName: "FG Config Only", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + const fgCmdInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCmdOnlyId, + displayName: "FG Cmd Only", enabled: true, environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], config: decodeSettings({ agentId: "test-agent" }), @@ -3753,19 +3819,28 @@ describe("AcpRegistryDriver registry recovery", () => { const v1Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); expect(v1Inspection.status).toBe("ready"); const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; - const fgLiveReady = yield* fgInstance.snapshot.streamChanges.pipe( + const fgConfigLiveReady = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "fg-v1-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgCmdLiveReady = yield* fgCmdInstance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.version === "1.0.0" && - snapshot.models.some((model) => model.slug === "fg-v1-a") && snapshot.slashCommands.some((cmd) => cmd.name === "fg-v1-cmd"), ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* fgInstance.snapshot.refresh; + yield* fgConfigInstance.snapshot.refresh; + yield* fgCmdInstance.snapshot.refresh; yield* coordinator.publishLiveConfiguration( - fgInstanceId, + fgConfigOnlyId, normalizeAcpRegistryLiveConfiguration([], undefined, { currentModelId: "fg-v1-a", availableModels: [ @@ -3776,33 +3851,89 @@ describe("AcpRegistryDriver registry recovery", () => { v1Identity, ); yield* coordinator.publishAvailableCommands( - fgInstanceId, + fgCmdOnlyId, { slashCommands: [{ name: "fg-v1-cmd" }], skills: [] }, v1Identity, ); - expect(Option.isSome(yield* Fiber.join(fgLiveReady))).toBe(true); + expect(Option.isSome(yield* Fiber.join(fgConfigLiveReady))).toBe(true); + expect(Option.isSome(yield* Fiber.join(fgCmdLiveReady))).toBe(true); - // End foreground startup, move index to failing 2.0.0, and verify 1.0.0 is preserved cleanly. + // End foreground startup, move index to 2.0.0 failing with authentication_failed, and + // verify both 1.0.0 snapshots stay on 1.0.0 without copying 2.0.0's unauthenticated auth. yield* Deferred.succeed(releaseFg, undefined); yield* Fiber.join(fgFiber); remoteVersion = "2.0.0"; - failProbeSpawn = true; + failProbeAuth = true; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const fgWarning = yield* fgInstance.snapshot.streamChanges.pipe( + const fgConfigWarning = yield* fgConfigInstance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.status === "warning"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* fgInstance.snapshot.refresh; - const fgWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgWarning)); - expect(fgWarningSnapshot.version).toBe("1.0.0"); - expect(fgWarningSnapshot.message).toContain("2.0.0"); - expect(fgWarningSnapshot.models.map((model) => model.slug)).toEqual(["fg-v1-a", "fg-v1-b"]); - expect(fgWarningSnapshot.slashCommands).toEqual([{ name: "fg-v1-cmd" }]); + const fgCmdWarning = yield* fgCmdInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fgConfigInstance.snapshot.refresh; + yield* fgCmdInstance.snapshot.refresh; + const fgConfigWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgConfigWarning)); + expect(fgConfigWarningSnapshot.version).toBe("1.0.0"); + expect(fgConfigWarningSnapshot.auth.status).toBe("unknown"); + expect(fgConfigWarningSnapshot.message).toContain("API key"); + expect(fgConfigWarningSnapshot.models.map((model) => model.slug)).toEqual([ + "fg-v1-a", + "fg-v1-b", + ]); + const fgCmdWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgCmdWarning)); + expect(fgCmdWarningSnapshot.version).toBe("1.0.0"); + expect(fgCmdWarningSnapshot.auth.status).toBe("unknown"); + expect(fgCmdWarningSnapshot.slashCommands).toEqual([{ name: "fg-v1-cmd" }]); + + // A live config update while retaining 1.0.0 under an upgrade failure must not bake the + // transient upgrade warning message into lastSuccessfulRuntime: when 1.0.0 is rolled back + // to and probed again, the old 2.0.0 warning message is gone. + const fgConfigUpdatedDuringWarn = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-c")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-c", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-c", name: "fg-v1-c" }, + ], + }), + v1Identity, + ); + const warnedWithC = Option.getOrThrow(yield* Fiber.join(fgConfigUpdatedDuringWarn)); + expect(warnedWithC.message).toContain("API key"); + // Another refresh while 2.0.0 still fails must keep 1.0.0's auth non-unauthenticated. + const secondAuthRefresh = yield* fgConfigInstance.snapshot.refresh; + expect(secondAuthRefresh.version).toBe("1.0.0"); + expect(secondAuthRefresh.auth.status).toBe("unknown"); + // Now make 2.0.0 fail with a different install_failed message and verify the earlier + // auth warning message did not leak into lastSuccessfulRuntime. + failProbeAuth = false; + failProbeSpawn = true; + const fgSwitchedWarning = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => Boolean(snapshot.message?.includes("2.0.0"))), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fgConfigInstance.snapshot.refresh; + const fgSwitchedSnapshot = Option.getOrThrow(yield* Fiber.join(fgSwitchedWarning)); + expect(fgSwitchedSnapshot.version).toBe("1.0.0"); + expect(fgSwitchedSnapshot.message).not.toContain("API key"); + expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-c"); // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed - // 2.0.0 probe publishes 2.0.0's failure snapshot directly without attaching 1.0.0 live state. + // 2.0.0 probe publishes 2.0.0's failure snapshot without attaching 1.0.0 live state AND + // aligns watcher identities to 2.0.0 so subsequent 1.0.0 updates cannot land on it. remoteVersion = "1.0.0"; failProbeSpawn = false; yield* realCatalog.invalidateIndex(); @@ -3844,16 +3975,66 @@ describe("AcpRegistryDriver registry recovery", () => { failProbeSpawn = true; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const noAcceptV2Gate = { + matchVersion: "2.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = noAcceptV2Gate; const noAcceptWarning = yield* noAcceptInstance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.status === "warning"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* noAcceptInstance.snapshot.refresh; + const noAcceptFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptFailDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(noAcceptV2Gate.started); + // Seed 1.0.0 commands into coordinator while 2.0.0's probe is in flight (rejected by the + // watcher, so lastSuccessfulRuntime stays null) to prove the failed 2.0.0 publish never + // attaches 1.0.0 live state onto 2.0.0's failure snapshot. + const v1DuringV2Handled = yield* Deferred.make(); + onCommandHandled = { matchName: "v1-during-v2-fail", done: v1DuringV2Handled }; + yield* coordinator.publishAvailableCommands( + noAcceptId, + { slashCommands: [{ name: "v1-during-v2-fail" }], skills: [] }, + v1Identity, + ); + yield* Deferred.await(v1DuringV2Handled); + yield* Deferred.succeed(noAcceptV2Gate.release, undefined); const noAcceptSnapshot = Option.getOrThrow(yield* Fiber.join(noAcceptWarning)); + yield* Deferred.await(noAcceptFailDone); expect(noAcceptSnapshot.version).toBe("2.0.0"); expect(noAcceptSnapshot.message).toContain("2.0.0"); expect(noAcceptSnapshot.slashCommands).toEqual([]); + // A subsequent 1.0.0 update must NOT land on 2.0.0's failure snapshot. + const lateV1AfterFailHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v1-after-v2-fail", done: lateV1AfterFailHandled }; + yield* coordinator.publishAvailableCommands( + noAcceptId, + { slashCommands: [{ name: "v1-after-v2-fail" }], skills: [] }, + v1Identity, + ); + yield* Deferred.await(lateV1AfterFailHandled); + const noAcceptAfterLateV1 = yield* noAcceptInstance.snapshot.getSnapshot; + expect(noAcceptAfterLateV1.version).toBe("2.0.0"); + expect(noAcceptAfterLateV1.slashCommands).toEqual([]); + // Once 2.0.0 succeeds, noAcceptInstance adopts 2.0.0 cleanly. + failProbeSpawn = false; + const noAcceptV2Adopted = yield* noAcceptInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* noAcceptInstance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(noAcceptV2Adopted))).toBe(true); // 3. Fallback retirement stamps failedTarget's revision (v3), not a concurrently restored // v4 revision, so a new v4 session reconciles immediately even if v4 restored mid-probe. @@ -4015,24 +4196,26 @@ describe("AcpRegistryDriver registry recovery", () => { expect(Option.isSome(yield* Fiber.join(v2DrainedReconciled))).toBe(true); yield* Deferred.await(v2RestoredEnrichmentDone); - // Verify re-stamping on an unrelated revision bump suppresses repeated inspects for retired v4. + // Verify re-stamping on an unrelated revision bump suppresses repeated inspects for retired v4, + // waiting for the full reconciliation span (including retirement stamping and claim release) + // before sending the second same-revision event and before advancing to the next revision. remoteExtraAgentVersion = "10.0.0"; yield* realCatalog.invalidateIndex(); - yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const firstRestampDone = yield* Deferred.make(); - onInspectCallback = () => Deferred.succeed(firstRestampDone, undefined).pipe(Effect.asVoid); + const r7 = yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + recordedInspectRevisions = []; + const firstRestampSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(firstRestampSpanDone, Exit.void); const inspectsBeforeRestamp = inspectCalls; yield* coordinator.publishAvailableCommands( fallbackRetireId, { slashCommands: [{ name: "v4-late-1" }], skills: [] }, v4Identity, ); - yield* Deferred.await(firstRestampDone); - onInspectCallback = null; + yield* Deferred.await(firstRestampSpanDone); expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + expect(recordedInspectRevisions).toEqual([r7]); - // A second late v4 event at the same revision must NOT call catalog.inspect again, - // while a subsequent unrelated revision bump inspects once more (total +2, not +3). + // A second late v4 event at the same revision R7 must NOT trigger another reconcile inspect. const secondLateHandled = yield* Deferred.make(); onCommandHandled = { matchName: "v4-late-2", done: secondLateHandled }; yield* coordinator.publishAvailableCommands( @@ -4042,21 +4225,58 @@ describe("AcpRegistryDriver registry recovery", () => { ); yield* Deferred.await(secondLateHandled); expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + expect(recordedInspectRevisions).toEqual([r7]); + // Advancing to a new unrelated revision R8 triggers exactly one more inspect (total [r7, r8]). remoteExtraAgentVersion = "10.0.1"; yield* realCatalog.invalidateIndex(); - yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const secondRestampDone = yield* Deferred.make(); - onInspectCallback = () => - Deferred.succeed(secondRestampDone, undefined).pipe(Effect.asVoid); + const r8 = yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const secondRestampSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(secondRestampSpanDone, Exit.void); yield* coordinator.publishAvailableCommands( fallbackRetireId, { slashCommands: [{ name: "v4-late-3" }], skills: [] }, v4Identity, ); - yield* Deferred.await(secondRestampDone); - onInspectCallback = null; + yield* Deferred.await(secondRestampSpanDone); expect(inspectCalls).toBe(inspectsBeforeRestamp + 2); + expect(recordedInspectRevisions).toEqual([r7, r8]); + recordedInspectRevisions = null; + + // A defect inside reconciliation must still release the reconcilingState claim (Effect.onError) + // so a subsequent event for the same identity reconciles cleanly once the catalog recovers. + remoteExtraAgentVersion = "10.0.2"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + defectNextInspect = true; + const defectSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(defectSpanDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-defect-probe" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(defectSpanDone); + + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v4RecoveredAfterDefect = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v4-after-defect"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-after-defect" }], skills: [] }, + v4Identity, + ); + expect(Option.isSome(yield* Fiber.join(v4RecoveredAfterDefect))).toBe(true); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 12d2012a87c46..9e5bb94372e6b 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -611,7 +611,6 @@ interface ActiveFallbackState { interface FailedUpgradeTargetState { readonly targetLaunchIdentity: string | null; readonly status: ServerProvider["status"]; - readonly auth: ServerProvider["auth"]; readonly message: string | undefined; } @@ -1153,10 +1152,6 @@ export const AcpRegistryDriver: ProviderDriver { if (!retired.has(incomingIdentity)) return retired; const next = new Map(retired); - next.set(incomingIdentity, stampRevision); + next.set( + incomingIdentity, + Math.max(retired.get(incomingIdentity) ?? 0, stampRevision), + ); return next; }); } @@ -1561,7 +1559,7 @@ export const AcpRegistryDriver: ProviderDriver + Effect.onError(() => Ref.update(reconcilingState, (state) => { if (!state.has(incomingIdentity)) return state; const next = new Map(state); @@ -1569,6 +1567,7 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 18:03:43 +0000 Subject: [PATCH 19/28] fix(acp-registry): track probed runtime auth failures, harden sidecar persistence, and replay defected reconciles --- .../src/server/AcpRegistrySupport.test.ts | 408 +++++++++++++++++- .../src/server/AcpRegistrySupport.ts | 405 ++++++++++------- .../src/server/driver.test.ts | 253 ++++++++--- .../src/server/driver.ts | 55 ++- .../provider-acp-registry/src/server/probe.ts | 30 +- 5 files changed, 913 insertions(+), 238 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index e3f0cc4d55c68..dd924d1ad5973 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -3896,6 +3896,7 @@ describe("AcpRegistrySupport", () => { version, }); let upstream = binaryAgent("1.2.3", archiveAUrl); + let upstreamEmpty = false; let archiveRequestsDuringLockedSlot = 0; let countArchiveRequests = false; @@ -4242,6 +4243,94 @@ describe("AcpRegistrySupport", () => { "#!/bin/sh\necho archive-b\n", ); + // A transient stat I/O error on tools/ itself must keep disk registry.json on A and + // block live resolution from launching unverified legacy A. + const statIoDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stat-io-", + }); + const statIoRegistryDir = path.join(statIoDir, "acp-registry"); + const statIoRegistryPath = path.join(statIoRegistryDir, "registry.json"); + const statIoToolsDir = path.join(statIoDir, "tools"); + const statIoLegacyExe = path.join( + statIoToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(statIoLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(statIoLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(statIoLegacyExe, 0o755); + yield* fileSystem.makeDirectory(statIoRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + statIoRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + const failToolsStatFs: FileSystem.FileSystem = { + ...fileSystem, + stat: (filePath) => + filePath === statIoToolsDir + ? fileSystem + .readFileString(statIoToolsDir) + .pipe(Effect.andThen(fileSystem.stat(filePath))) + : fileSystem.stat(filePath), + }; + const statIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: statIoDir, + toolsDir: statIoToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failToolsStatFs)); + yield* statIoResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(statIoRegistryPath)).toContain(archiveAUrl); + const resolvedDuringStatIo = yield* statIoResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringStatIo.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Removing an agent present in the initial disk registry.json must still record its + // legacy baseline on the first refresh after restart so a later re-add at the same + // version with a different archive installs B instead of executing legacy A. + const removedAgentDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-removed-baseline-", + }); + const removedRegistryDir = path.join(removedAgentDir, "acp-registry"); + const removedRegistryPath = path.join(removedRegistryDir, "registry.json"); + const removedBaselinesPath = path.join(removedRegistryDir, "legacy-baselines.json"); + const removedToolsDir = path.join(removedAgentDir, "tools"); + const removedLegacyExe = path.join( + removedToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(removedLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(removedLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(removedLegacyExe, 0o755); + yield* fileSystem.makeDirectory(removedRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + removedRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + upstreamEmpty = true; + const removedAgentResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removedAgentDir, + toolsDir: removedToolsDir, + registryUrl, + }); + yield* removedAgentResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(removedBaselinesPath)).toContain(archiveAUrl); + upstreamEmpty = false; + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* removedAgentResolver.invalidateIndex(); + yield* removedAgentResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAfterReadd = yield* removedAgentResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAfterReadd.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + failToolsScan = false; yield* scanResolver.invalidateIndex(); yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4288,26 +4377,43 @@ describe("AcpRegistrySupport", () => { const corruptDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-baseline-corrupt-", }); - const corruptRegistryDir = `${corruptDir}/acp-registry`; - const corruptRegistryPath = `${corruptRegistryDir}/registry.json`; - const corruptBaselinesPath = `${corruptRegistryDir}/legacy-baselines.json`; - const corruptLegacyExe = `${corruptDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + const corruptRegistryDir = path.join(corruptDir, "acp-registry"); + const corruptRegistryPath = path.join(corruptRegistryDir, "registry.json"); + const corruptBaselinesPath = path.join(corruptRegistryDir, "legacy-baselines.json"); + const corruptToolsDir = path.join(corruptDir, "tools"); + const corruptLegacyExe = path.join( + corruptToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + const corruptUnreadableOtherTool = path.join(corruptToolsDir, "chrome-headless-shell"); yield* fileSystem.makeDirectory(path.dirname(corruptLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(corruptLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(corruptLegacyExe, 0o755); + yield* fileSystem.makeDirectory(corruptUnreadableOtherTool, { recursive: true }); yield* fileSystem.makeDirectory(corruptRegistryDir, { recursive: true }); yield* fileSystem.writeFileString( corruptRegistryPath, makeRegistry(binaryAgent("1.0.0", archiveBUrl)), ); yield* fileSystem.writeFileString(corruptBaselinesPath, "{not json"); + const corruptToolsFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === corruptUnreadableOtherTool + ? fileSystem.readDirectory(corruptLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; upstream = binaryAgent("2.0.0", archiveCUrl); const corruptResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: corruptDir, - toolsDir: `${corruptDir}/tools`, + toolsDir: corruptToolsDir, registryUrl, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, corruptToolsFs)); yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); expect(yield* fileSystem.readFileString(`${corruptBaselinesPath}.corrupt`)).toBe( "{not json", @@ -4430,7 +4536,14 @@ describe("AcpRegistrySupport", () => { layerResolver((request) => { if (request.url === registryUrl) { return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(upstream))), + HttpClientResponse.fromWeb( + request, + new Response( + upstreamEmpty + ? JSON.stringify({ version: "1.0.0", agents: [] }) + : makeRegistry(upstream), + ), + ), ); } if (countArchiveRequests) { @@ -4881,6 +4994,20 @@ describe("AcpRegistrySupport", () => { yield* noEnvResolver.resolve(settings(), "/workspace"); yield* noEnvResolver.resolve(settings(), "/workspace"); expect(receiptRenameCount).toBe(0); + // After populating syncedLaunchOptionsBySlotRoot for a no-env binary, subsequent resolves + // with the same args and omitted env must hit the memory fast path without rewriting. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--v2"], + }); + yield* noEnvResolver.invalidateIndex(); + yield* noEnvResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* noEnvResolver.resolve(settings(), "/workspace"); + receiptRenameCount = 0; + yield* noEnvResolver.resolve(settings(), "/workspace"); + yield* noEnvResolver.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); const supersededDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-superseded-inspect-", @@ -5028,6 +5155,141 @@ describe("AcpRegistrySupport", () => { expect(fallbackA.spawn.args).toEqual(["--v1", "--sidecar"]); expect(fallbackA.spawn.env?.STAGE).toBe("sidecar"); + // After storage recovers, re-resolving the SAME --sidecar-io options on supersededResolver + // (which only held them in memory when both receipt and sidecar writes failed) must retry + // persistence so a fresh catalog restores --sidecar-io on fallback. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar-io"], + env: { STAGE: "sidecar-io" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const recoveredIoCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackRecoveredIo = yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + expect(fallbackRecoveredIo.fallback).toBe(true); + expect(fallbackRecoveredIo.spawn.args).toEqual(["--v1", "--sidecar-io"]); + expect(fallbackRecoveredIo.spawn.env?.STAGE).toBe("sidecar-io"); + + // A second catalog writing a newer sidecar revision must win over catalog A's older + // in-memory cached launch options during fallback AND must invalidate catalog A's skip path. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-b"], + env: { STAGE: "cat-b" }, + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackSeesCatB = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(fallbackSeesCatB.fallback).toBe(true); + expect(fallbackSeesCatB.spawn.args).toEqual(["--v1", "--cat-b"]); + expect(fallbackSeesCatB.spawn.env?.STAGE).toBe("cat-b"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackSeesNewerCatA = yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + expect(fallbackSeesNewerCatA.fallback).toBe(true); + expect(fallbackSeesNewerCatA.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackSeesNewerCatA.spawn.env?.STAGE).toBe("cat-a"); + + // A corrupt binary-launch-options.json is copied aside and repaired cleanly on write. + yield* fileSystem.writeFileString(supersededSidecarPath, "{corrupt-sidecar"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--repaired-sidecar"], + env: { STAGE: "repaired" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + expect(yield* fileSystem.readFileString(`${supersededSidecarPath}.corrupt`)).toBe( + "{corrupt-sidecar", + ); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const repairedSidecarCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* repairedSidecarCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackRepairedSidecar = yield* repairedSidecarCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackRepairedSidecar.fallback).toBe(true); + expect(fallbackRepairedSidecar.spawn.args).toEqual(["--v1", "--repaired-sidecar"]); + expect(fallbackRepairedSidecar.spawn.env?.STAGE).toBe("repaired"); + // Restore preserveSlotKey before the revert check below. + const repairedSidecarEntries = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + yield* fileSystem.writeFileString( + supersededSidecarPath, + JSON.stringify({ + ...repairedSidecarEntries, + [preserveSlotKey]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--preserve"], + launchOptionsRevision: 1, + }, + }), + ); + // Reverting upstream back to the receipt's earlier args/env after restart prunes the // sidecar and persists the new generation; verify with ANOTHER fresh catalog instance. const exampleSlotRootSuperseded = path.dirname(path.dirname(installedA.spawn.command)); @@ -5131,6 +5393,138 @@ describe("AcpRegistrySupport", () => { expect(fallbackAfterReinstall.fallback).toBe(true); expect(fallbackAfterReinstall.spawn.args).toEqual(["--fresh-after-uninstall"]); + // Reinstalling a broken slot in place must supersede/prune stale in-memory and sidecar + // launch options at that slot root so fallback uses the fresh install's options both + // in-process and after restart. + const inPlaceDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-inplace-reinstall-", + }); + const inPlaceToolsDir = path.join(inPlaceDir, "tools"); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--b1"], + }); + const inPlaceCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: inPlaceDir, + toolsDir: inPlaceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* inPlaceCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a1"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const inPlaceSlotA = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a2"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + // Break slot A's executable, then resolve A with new args --a3 so it reinstalls in place. + yield* fileSystem.remove(inPlaceSlotA.spawn.command, { force: true }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a3"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reinstalledInPlace = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + expect(reinstalledInPlace.spawn.command).toBe(inPlaceSlotA.spawn.command); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const inProcessFallbackA3 = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + expect(inProcessFallbackA3.fallback).toBe(true); + expect(inProcessFallbackA3.spawn.args).toEqual(["--a3"]); + const restartedInPlaceCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: inPlaceDir, + toolsDir: inPlaceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* restartedInPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const restartedFallbackA3 = yield* restartedInPlaceCatalog.resolve( + settings(), + "/workspace", + ); + expect(restartedFallbackA3.fallback).toBe(true); + expect(restartedFallbackA3.spawn.args).toEqual(["--a3"]); + + // A concurrent higher revision already written to the sidecar must never be pruned or + // overwritten by a lower-revision sync (verified on the receipt-matches-target prune path). + const inPlaceSidecarPath = path.join( + inPlaceDir, + "acp-registry", + "binary-launch-options.json", + ); + const inPlaceSlotARoot = path.dirname(path.dirname(inPlaceSlotA.spawn.command)); + yield* fileSystem.writeFileString( + inPlaceSidecarPath, + JSON.stringify({ + [inPlaceSlotARoot]: { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--concurrent-rev-999"], + launchOptionsRevision: 999, + }, + }), + ); + // Gate right after the initial sidecar read is skipped: even with a stale rev-0 sidecar + // check, a concurrent rev-999 write before the locked prune must survive intact. + let injectConcurrentHighRev = true; + const concurrentHighRevFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => + filePath === inPlaceSidecarPath && injectConcurrentHighRev + ? Effect.sync(() => { + injectConcurrentHighRev = false; + }).pipe( + Effect.as( + JSON.stringify({ + [inPlaceSlotARoot]: { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--old-rev-1"], + launchOptionsRevision: 1, + }, + }), + ), + ) + : posixModeFs.readFileString(filePath, encoding), + }; + const concurrentRevCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: inPlaceDir, + toolsDir: inPlaceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, concurrentHighRevFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a3"], + }); + yield* concurrentRevCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* concurrentRevCatalog.resolve(settings(), "/workspace"); + const sidecarAfterHighRevGuard = JSON.parse( + yield* fileSystem.readFileString(inPlaceSidecarPath), + ) as Record }>; + expect(sidecarAfterHighRevGuard[inPlaceSlotARoot]?.args).toEqual(["--concurrent-rev-999"]); + // 3. A superseded primary executable that lost execute permission must not fail inspect() // when the registry selects a different same-version artifact. yield* posixModeFs.chmod(reinstalledA.spawn.command, 0o644); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 051e1d7bb8b06..6d7d922fae1f9 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1131,7 +1131,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // discovery; requires positive baseline provenance before reusing unreceipted legacy installs. let legacyBaselineDiscoveryIncomplete = false; // In-memory mirror of last-resolved binary launch options when updating .t3-artifact.json fails. - const syncedLaunchOptionsBySlotRoot = new Map(); + const syncedLaunchOptionsBySlotRoot = new Map< + string, + { readonly receipt: AcpRegistryBinaryArtifactReceipt; readonly persisted: boolean } + >(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -1495,6 +1498,38 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); + // Returns true when the desired state is durably persisted on disk (or already superseded by a + // newer revision), false on transient I/O errors or lock loss (leaving disk untouched). + // Corrupt sidecar files are copied aside and repaired cleanly once the lock is verified. + const updateBinaryLaunchOptionsStore = Effect.fn( + "AcpRegistryCatalog.updateBinaryLaunchOptionsStore", + )(function* ( + mutate: ( + entries: Readonly>, + ) => Readonly> | null, + ) { + return yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const current = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); + if (current.status === "io_error") return false; + const isCorrupt = current.status === "corrupt"; + const baseEntries = isCorrupt ? {} : current.entries; + const nextEntries = mutate(baseEntries); + if (nextEntries === null && !isCorrupt) return true; + if (!(yield* isLockOwned)) return false; + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + return yield* writeJsonFileAtomically(binaryLaunchOptionsPath, nextEntries ?? {}).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + }), + ).pipe(Effect.orElseSucceed(() => false)); + }); + const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( inMemoryPrevious: AcpRegistryIndex | undefined, nextIndex: AcpRegistryIndex, @@ -1547,51 +1582,69 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } return directories; }); + const scanAgentLegacySlots = Effect.fn("AcpRegistryCatalog.scanAgentLegacySlots")(function* ( + agentId: string, + ) { + const slots: Array<{ + readonly agentId: string; + readonly encodedVersion: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly slotKey: string; + }> = []; + const agentRoot = path.join(installsDirectory, agentId); + const agentStat = yield* fileSystem.stat(agentRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (agentStat.status !== "ok" || agentStat.info.type !== "Directory") return slots; + for (const encodedVersion of yield* listSubdirectories(agentRoot)) { + const versionRoot = path.join(agentRoot, encodedVersion); + for (const candidateTarget of candidates) { + const installRoot = path.join(versionRoot, candidateTarget); + const installStat = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; + if (yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME))) + continue; + slots.push({ + agentId, + encodedVersion, + candidateTarget, + slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), + }); + } + } + return slots; + }); const scanUnreceiptedLegacySlots = Effect.fn("AcpRegistryCatalog.scanUnreceiptedLegacySlots")( - function* (agentIds: ReadonlyArray | undefined) { + function* (requiredAgentIds: ReadonlyArray, includeExtraDirectories: boolean) { const slots: Array<{ readonly agentId: string; readonly encodedVersion: string; readonly candidateTarget: AcpRegistryPlatformTarget; readonly slotKey: string; }> = []; - const targetAgentIds = - agentIds === undefined ? yield* listSubdirectories(installsDirectory) : agentIds; - for (const agentId of targetAgentIds) { - const agentRoot = path.join(installsDirectory, agentId); - if (agentIds !== undefined) { - const agentStat = yield* fileSystem.stat(agentRoot).pipe( - Effect.map((info) => ({ status: "ok" as const, info })), - Effect.catchIf( - (error) => error.reason._tag === "NotFound", - () => Effect.succeed({ status: "missing" as const }), - ), + for (const agentId of requiredAgentIds) { + slots.push(...(yield* scanAgentLegacySlots(agentId))); + } + if (includeExtraDirectories) { + // On corrupt-baselines rebuild, also discover readable removed-agent slots while letting + // unreadable unrelated tool directories (e.g. tools/chrome-headless-shell) be skipped. + const requiredSet = new Set(requiredAgentIds); + for (const entry of yield* listSubdirectories(installsDirectory)) { + if (requiredSet.has(entry)) continue; + const extraSlots = yield* scanAgentLegacySlots(entry).pipe( + Effect.orElseSucceed(() => []), ); - if (agentStat.status !== "ok" || agentStat.info.type !== "Directory") continue; - } - for (const encodedVersion of yield* listSubdirectories(agentRoot)) { - const versionRoot = path.join(agentRoot, encodedVersion); - for (const candidateTarget of candidates) { - const installRoot = path.join(versionRoot, candidateTarget); - const installStat = yield* fileSystem.stat(installRoot).pipe( - Effect.map((info) => ({ status: "ok" as const, info })), - Effect.catchIf( - (error) => error.reason._tag === "NotFound", - () => Effect.succeed({ status: "missing" as const }), - ), - ); - if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; - if ( - yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) - ) - continue; - slots.push({ - agentId, - encodedVersion, - candidateTarget, - slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), - }); - } + slots.push(...extraSlots); } } return slots; @@ -1629,21 +1682,21 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } // Scope normal scans to ACP agent directories referenced by the previous/next index or // in-memory baselines so unrelated entries in shared tools/ never block registry refreshes. - // Walk all of tools/ only when rebuilding a corrupt baselines file. - const scopedAgentIds = - initialDisk.status === "corrupt" - ? undefined - : Array.from( - new Set([ - ...nextIndex.agents.map((agent) => agent.id), - ...(initialDiskIndex.status === "ok" - ? initialDiskIndex.index.agents.map((agent) => agent.id) - : []), - ...(inMemoryPrevious?.agents.map((agent) => agent.id) ?? []), - ...Array.from(legacyBaselineBySlotKey.keys(), (key) => key.split("\0")[0] ?? ""), - ]), - ).filter((id) => id.length > 0); - const scanResult = yield* Effect.result(scanUnreceiptedLegacySlots(scopedAgentIds)); + // Include extra directories (best-effort) only when rebuilding a corrupt baselines file. + const requiredAgentIds = Array.from( + new Set([ + ...nextIndex.agents.map((agent) => agent.id), + ...(initialDiskIndex.status === "ok" + ? initialDiskIndex.index.agents.map((agent) => agent.id) + : []), + ...(inMemoryPrevious?.agents.map((agent) => agent.id) ?? []), + ...Array.from(legacyBaselineBySlotKey.keys(), (key) => key.split("\0")[0] ?? ""), + ]), + ).filter((id) => id.length > 0); + const initialIncludedExtraDirs = initialDisk.status === "corrupt"; + const scanResult = yield* Effect.result( + scanUnreceiptedLegacySlots(requiredAgentIds, initialIncludedExtraDirs), + ); if (Result.isFailure(scanResult)) { legacyBaselineDiscoveryIncomplete = true; yield* Effect.logDebug( @@ -1764,12 +1817,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } let mergedBaselines: Record; if (disk.status === "corrupt") { - const corruptScanSlots = - scopedAgentIds === undefined - ? unreceiptedLegacySlots - : yield* Effect.result(scanUnreceiptedLegacySlots(undefined)).pipe( - Effect.map((result) => (Result.isSuccess(result) ? result.success : null)), - ); + const corruptScanSlots = initialIncludedExtraDirs + ? unreceiptedLegacySlots + : yield* Effect.result(scanUnreceiptedLegacySlots(requiredAgentIds, true)).pipe( + Effect.map((result) => (Result.isSuccess(result) ? result.success : null)), + ); if (corruptScanSlots === null) { legacyBaselineDiscoveryIncomplete = true; yield* Effect.logDebug( @@ -2617,13 +2669,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ) { if (slot.receipt === undefined) return; const memoryStored = syncedLaunchOptionsBySlotRoot.get(slot.root); - if ( - memoryStored !== undefined && - Equal.equals(memoryStored.args ?? [], target.args ?? []) && - Equal.equals(memoryStored.env ?? {}, target.env ?? {}) - ) { - return; - } const hasSidecar = yield* fileSystem .exists(binaryLaunchOptionsPath) .pipe(Effect.orElseSucceed(() => false)); @@ -2633,30 +2678,37 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const diskStored = diskResult.status === "ok" ? diskResult.entries[slot.root] : undefined; const receiptRev = slot.receipt.launchOptionsRevision ?? 0; const diskRev = diskStored?.launchOptionsRevision ?? 0; - const memoryRev = memoryStored?.launchOptionsRevision ?? 0; + const memoryRev = memoryStored?.receipt.launchOptionsRevision ?? 0; + if ( + memoryStored !== undefined && + memoryStored.persisted && + diskResult.status !== "corrupt" && + receiptRev <= memoryRev && + diskRev <= memoryRev && + Equal.equals(memoryStored.receipt.args ?? [], target.args ?? []) && + Equal.equals(memoryStored.receipt.env ?? {}, target.env ?? {}) + ) { + return; + } const receiptMatchesTarget = Equal.equals(slot.receipt.args ?? [], target.args ?? []) && Equal.equals(slot.receipt.env ?? {}, target.env ?? {}); if (memoryStored === undefined && receiptMatchesTarget) { + if (diskResult.status === "corrupt") { + yield* updateBinaryLaunchOptionsStore(() => null); + return; + } if (diskStored === undefined) return; if (diskRev <= receiptRev) { // Prune an older sidecar left behind by a prior cleanup failure without rewriting receipt. - yield* withBinaryLaunchOptionsLock((isLockOwned) => - Effect.gen(function* () { - const current = yield* readBinaryLaunchOptionsFile( - fileSystem, - binaryLaunchOptionsPath, - ); - if (current.status !== "ok") return; - const existing = current.entries[slot.root]; - if (existing === undefined || (existing.launchOptionsRevision ?? 0) > receiptRev) { - return; - } - if (!(yield* isLockOwned)) return; - const { [slot.root]: _removed, ...rest } = current.entries; - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest); - }), - ).pipe(Effect.ignore); + yield* updateBinaryLaunchOptionsStore((entries) => { + const existing = entries[slot.root]; + if (existing === undefined || (existing.launchOptionsRevision ?? 0) > receiptRev) { + return null; + } + const { [slot.root]: _removed, ...rest } = entries; + return rest; + }); return; } } @@ -2670,7 +2722,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), launchOptionsRevision: nextRevision, }; - syncedLaunchOptionsBySlotRoot.set(slot.root, updatedReceipt); + syncedLaunchOptionsBySlotRoot.set(slot.root, { + receipt: updatedReceipt, + persisted: false, + }); const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); const receiptWrite = yield* Effect.result( random.uuidV4().pipe( @@ -2691,47 +2746,44 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); if (Result.isSuccess(receiptWrite)) { + syncedLaunchOptionsBySlotRoot.set(slot.root, { + receipt: updatedReceipt, + persisted: true, + }); // Keep the slot receipt authoritative by pruning any older fallback sidecar entry. if ( yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false)) ) { - yield* withBinaryLaunchOptionsLock((isLockOwned) => - Effect.gen(function* () { - const current = yield* readBinaryLaunchOptionsFile( - fileSystem, - binaryLaunchOptionsPath, - ); - if (current.status !== "ok") return; - const existing = current.entries[slot.root]; - if (existing === undefined || (existing.launchOptionsRevision ?? 0) > nextRevision) { - return; - } - if (!(yield* isLockOwned)) return; - const { [slot.root]: _removed, ...rest } = current.entries; - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest); - }), - ).pipe(Effect.ignore); + yield* updateBinaryLaunchOptionsStore((entries) => { + const existing = entries[slot.root]; + if (existing === undefined || (existing.launchOptionsRevision ?? 0) > nextRevision) { + return null; + } + const { [slot.root]: _removed, ...rest } = entries; + return rest; + }); } return; } // If updating the receipt inside tools/ failed (e.g., read-only install directory or file // lock), persist the updated launch options in registry cache storage so fallback still // restores the last-resolved args and env even across restarts. - yield* withBinaryLaunchOptionsLock((isLockOwned) => - Effect.gen(function* () { - const current = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); - if (current.status !== "ok") return; - const existing = current.entries[slot.root]; - if (existing !== undefined && (existing.launchOptionsRevision ?? 0) > nextRevision) { - return; - } - if (!(yield* isLockOwned)) return; - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, { - ...current.entries, - [slot.root]: updatedReceipt, - }); - }), - ).pipe(Effect.ignore); + const sidecarPersisted = yield* updateBinaryLaunchOptionsStore((entries) => { + const existing = entries[slot.root]; + if (existing !== undefined && (existing.launchOptionsRevision ?? 0) > nextRevision) { + return null; + } + return { + ...entries, + [slot.root]: updatedReceipt, + }; + }); + if (sidecarPersisted) { + syncedLaunchOptionsBySlotRoot.set(slot.root, { + receipt: updatedReceipt, + persisted: true, + }); + } }, ); @@ -2963,10 +3015,26 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); + // Supersede any stale launch-options sidecar/memory entry left from an earlier broken + // install at destinationRoot so fallback never resurrects old options over the new receipt. + const priorMemoryRev = + syncedLaunchOptionsBySlotRoot.get(destinationRoot)?.receipt.launchOptionsRevision ?? 0; + const priorSidecarExists = yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false)); + const priorSidecarResult = priorSidecarExists + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); + const priorDiskRev = + priorSidecarResult.status === "ok" + ? (priorSidecarResult.entries[destinationRoot]?.launchOptionsRevision ?? 0) + : 0; + const maxPriorRev = Math.max(priorMemoryRev, priorDiskRev); + const freshLaunchOptionsRevision = maxPriorRev > 0 ? maxPriorRev + 1 : undefined; yield* fileSystem .writeFileString( path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), - encodeBinaryArtifactReceipt(agent, target), + encodeBinaryArtifactReceipt(agent, target, freshLaunchOptionsRevision), { flag: "wx" }, ) .pipe( @@ -2997,8 +3065,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return validated.value; } } + let promotedFreshSlot = false; const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), + Effect.tap(() => + Effect.sync(() => { + promotedFreshSlot = true; + }), + ), Effect.catch((renameError) => findMatchingBinarySlot(paths, target).pipe( Effect.flatMap( @@ -3011,6 +3085,25 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ), ); + if (promotedFreshSlot) { + syncedLaunchOptionsBySlotRoot.delete(destinationRoot); + if ( + priorSidecarExists || + (yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false))) + ) { + const promotedRev = freshLaunchOptionsRevision ?? 0; + yield* updateBinaryLaunchOptionsStore((entries) => { + const existing = entries[destinationRoot]; + if (existing === undefined || (existing.launchOptionsRevision ?? 0) > promotedRev) { + return null; + } + const { [destinationRoot]: _removed, ...rest } = entries; + return rest; + }); + } + } return promotedPath; }).pipe(Effect.scoped), ).pipe( @@ -3427,27 +3520,31 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.option, ); if (Option.isNone(validated)) continue; - const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir); - const diskOverrideResult = - memoryOverride !== undefined - ? ({ status: "ok", entries: {} } as const) - : (yield* fileSystem - .exists(binaryLaunchOptionsPath) - .pipe(Effect.orElseSucceed(() => false))) - ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) - : ({ status: "ok", entries: {} } as const); + const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir)?.receipt; + const diskOverrideResult = (yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false))) + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); const diskOverride = diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; - const candidateOverride = memoryOverride ?? diskOverride; - const effectiveReceipt = - candidateOverride !== undefined && - candidateOverride.archive === receipt.archive && - candidateOverride.cmd === receipt.cmd && - (candidateOverride.sha256 ?? null) === (receipt.sha256 ?? null) && - (candidateOverride.launchOptionsRevision ?? 0) > - (receipt.launchOptionsRevision ?? 0) - ? candidateOverride - : receipt; + const matchesReceiptArtifact = ( + candidate: AcpRegistryBinaryArtifactReceipt | undefined, + ): candidate is AcpRegistryBinaryArtifactReceipt => + candidate !== undefined && + candidate.archive === receipt.archive && + candidate.cmd === receipt.cmd && + (candidate.sha256 ?? null) === (receipt.sha256 ?? null); + let effectiveReceipt = receipt; + for (const candidate of [diskOverride, memoryOverride]) { + if ( + matchesReceiptArtifact(candidate) && + (candidate.launchOptionsRevision ?? 0) > + (effectiveReceipt.launchOptionsRevision ?? 0) + ) { + effectiveReceipt = candidate; + } + } const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); const fallbackArgs = effectiveReceipt.args ?? []; const fallbackEnv = effectiveReceipt.env ?? {}; @@ -3812,30 +3909,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.orElseSucceed(() => false), Effect.flatMap((hasLaunchOptionsFile) => hasLaunchOptionsFile - ? withBinaryLaunchOptionsLock((isLockOwned) => - Effect.gen(function* () { - const disk = yield* readBinaryLaunchOptionsFile( - fileSystem, - binaryLaunchOptionsPath, - ); - if (disk.status !== "ok") return; - const removedAgentRoot = path.join(installsDirectory, removedAgentId); - const removedPrefix = `${removedAgentRoot}${path.sep}`; - const remaining = Object.fromEntries( - Object.entries(disk.entries).filter( - ([slotRoot]) => - slotRoot !== removedAgentRoot && - !slotRoot.startsWith(removedPrefix), - ), - ); - if ( - Object.keys(remaining).length !== Object.keys(disk.entries).length - ) { - if (!(yield* isLockOwned)) return; - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, remaining); - } - }), - ).pipe(Effect.ignore) + ? updateBinaryLaunchOptionsStore((entries) => { + const removedAgentRoot = path.join(installsDirectory, removedAgentId); + const removedPrefix = `${removedAgentRoot}${path.sep}`; + const remaining = Object.fromEntries( + Object.entries(entries).filter( + ([slotRoot]) => + slotRoot !== removedAgentRoot && + !slotRoot.startsWith(removedPrefix), + ), + ); + return Object.keys(remaining).length !== Object.keys(entries).length + ? remaining + : null; + }).pipe(Effect.asVoid) : Effect.void, ), ), diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 1880c38dc3085..e44df8f718d12 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3617,8 +3617,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { let failArchiveVersions = new Set(); let failProbeSpawn = false; let failProbeAuth = false; - let defectNextInspect = false; + let defectInspectCount = 0; let inspectCalls = 0; + let onRefreshIndex: (() => Effect.Effect) | null = null; + let onBeforeProbeResolve: (() => Effect.Effect) | null = null; let recordedInspectRevisions: Array | null = null; let resolveGate: { readonly matchVersion: string; @@ -3722,11 +3724,26 @@ createInterface({ input: process.stdin }).on("line", (line) => { ); const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { ...realCatalog, + refreshIndex: (options) => + Effect.gen(function* () { + if (onRefreshIndex !== null) { + const hook = onRefreshIndex; + onRefreshIndex = null; + yield* hook(); + } + return yield* realCatalog.refreshIndex(options); + }), inspect: (settings, environment) => Effect.gen(function* () { inspectCalls += 1; - if (defectNextInspect) { - defectNextInspect = false; + if (defectInspectCount > 0) { + defectInspectCount -= 1; + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } return yield* Effect.die("simulated reconcile inspect defect"); } const result = yield* realCatalog.inspect(settings, environment); @@ -3745,6 +3762,11 @@ createInterface({ input: process.stdin }).on("line", (line) => { }), resolve: (settings, cwd, environment) => Effect.gen(function* () { + if (environment?.MISE_OFFLINE === "1" && onBeforeProbeResolve !== null) { + const hook = onBeforeProbeResolve; + onBeforeProbeResolve = null; + yield* hook(); + } const resolved = yield* realCatalog.resolve(settings, cwd, environment); if ( environment?.MISE_OFFLINE === "1" && @@ -3876,9 +3898,18 @@ createInterface({ input: process.stdin }).on("line", (line) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* fgConfigInstance.snapshot.refresh; - yield* fgCmdInstance.snapshot.refresh; + const fgConfigWarningDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgConfigWarningDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); const fgConfigWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgConfigWarning)); + yield* Deferred.await(fgConfigWarningDone); + const fgCmdWarningDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdWarningDone, Exit.void); + yield* fgCmdInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); expect(fgConfigWarningSnapshot.version).toBe("1.0.0"); expect(fgConfigWarningSnapshot.auth.status).toBe("unknown"); expect(fgConfigWarningSnapshot.message).toContain("API key"); @@ -3887,6 +3918,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { "fg-v1-b", ]); const fgCmdWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgCmdWarning)); + yield* Deferred.await(fgCmdWarningDone); expect(fgCmdWarningSnapshot.version).toBe("1.0.0"); expect(fgCmdWarningSnapshot.auth.status).toBe("unknown"); expect(fgCmdWarningSnapshot.slashCommands).toEqual([{ name: "fg-v1-cmd" }]); @@ -3912,10 +3944,72 @@ createInterface({ input: process.stdin }).on("line", (line) => { ); const warnedWithC = Option.getOrThrow(yield* Fiber.join(fgConfigUpdatedDuringWarn)); expect(warnedWithC.message).toContain("API key"); - // Another refresh while 2.0.0 still fails must keep 1.0.0's auth non-unauthenticated. - const secondAuthRefresh = yield* fgConfigInstance.snapshot.refresh; - expect(secondAuthRefresh.version).toBe("1.0.0"); - expect(secondAuthRefresh.auth.status).toBe("unknown"); + // Another refresh while 2.0.0 still fails must publish 1.0.0 with non-unauthenticated auth + // and the auth warning once the second probe's enrichment actually completes. + const secondAuthEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(secondAuthEnrichmentDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(secondAuthEnrichmentDone); + const secondAuthPublished = yield* fgConfigInstance.snapshot.getSnapshot; + expect(secondAuthPublished.version).toBe("1.0.0"); + expect(secondAuthPublished.status).toBe("warning"); + expect(secondAuthPublished.auth.status).toBe("unknown"); + expect(secondAuthPublished.message).toContain("API key"); + + // Post-resolution authentication_failed uses the ACTUALLY RESOLVED runtime identity: + // (a) inspect reads 1.0.0, resolve refreshes/launches 2.0.0 which fails auth -> retained + // 1.0.0 stays auth.status === "unknown" (not marked unauthenticated). + remoteVersion = "1.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + // Ensure 1.0.0 has a valid receipted install on disk for fallback check (b) below. + yield* realCatalog.resolve(decodeSettings({ agentId: "test-agent" }), directory); + onBeforeProbeResolve = () => { + remoteVersion = "2.0.0"; + return realCatalog + .invalidateIndex() + .pipe( + Effect.andThen(realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 })), + Effect.ignore, + ); + }; + const mismatchUpgradeDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(mismatchUpgradeDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(mismatchUpgradeDone); + const mismatchUpgradeSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(mismatchUpgradeSnapshot.version).toBe("1.0.0"); + expect(mismatchUpgradeSnapshot.status).toBe("warning"); + expect(mismatchUpgradeSnapshot.auth.status).toBe("unknown"); + expect(mismatchUpgradeSnapshot.message).toContain("API key"); + + // (b) inspect reads 2.0.0, resolve falls back to installed 1.0.0 (503 on 2.0.0), and + // 1.0.0 fails auth -> 1.0.0's OWN auth.status becomes "unauthenticated". + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "2.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "2.0.0"; + failArchiveVersions = new Set(["2.0.0"]); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAuthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackAuthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackAuthDone); + const fallbackAuthSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(fallbackAuthSnapshot.version).toBe("1.0.0"); + expect(fallbackAuthSnapshot.status).toBe("warning"); + expect(fallbackAuthSnapshot.auth.status).toBe("unauthenticated"); + expect(fallbackAuthSnapshot.message).toContain("API key"); + failArchiveVersions = new Set(); + // Now make 2.0.0 fail with a different install_failed message and verify the earlier // auth warning message did not leak into lastSuccessfulRuntime. failProbeAuth = false; @@ -3925,21 +4019,28 @@ createInterface({ input: process.stdin }).on("line", (line) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* fgConfigInstance.snapshot.refresh; + const fgSwitchedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgSwitchedDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); const fgSwitchedSnapshot = Option.getOrThrow(yield* Fiber.join(fgSwitchedWarning)); + yield* Deferred.await(fgSwitchedDone); expect(fgSwitchedSnapshot.version).toBe("1.0.0"); expect(fgSwitchedSnapshot.message).not.toContain("API key"); expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-c"); // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed - // 2.0.0 probe publishes 2.0.0's failure snapshot without attaching 1.0.0 live state AND - // aligns watcher identities to 2.0.0 so subsequent 1.0.0 updates cannot land on it. + // 2.0.0 probe discovered via recheck (with expectedRuntimeIdentity still on 1.0.0!) publishes + // 2.0.0's failure snapshot without attaching 1.0.0 live state AND aligns watcher identities + // to 2.0.0 so subsequent 1.0.0 updates cannot land on it. remoteVersion = "1.0.0"; failProbeSpawn = false; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const coldFgStarted = yield* Deferred.make(); const releaseColdFg = yield* Deferred.make(); + const coldFgDone = yield* Deferred.make(); const coldFgFiber = yield* coordinator .withForegroundStartup( "test-agent", @@ -3947,7 +4048,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { Effect.andThen(Deferred.await(releaseColdFg)), ), ) - .pipe(Effect.forkScoped({ startImmediately: true })); + .pipe( + Effect.ensuring(Deferred.succeed(coldFgDone, undefined)), + Effect.forkScoped({ startImmediately: true }), + ); yield* Deferred.await(coldFgStarted); const noAcceptId = ProviderInstanceId.make("acpRegistry_no_accepted_v1"); const noAcceptInstance = yield* AcpRegistryDriver.create({ @@ -3969,18 +4073,16 @@ createInterface({ input: process.stdin }).on("line", (line) => { Effect.provideService(Tracer.Tracer, enrichmentTracer), ); yield* Deferred.await(noAcceptColdEnrichmentDone); - yield* Deferred.succeed(releaseColdFg, undefined); - yield* Fiber.join(coldFgFiber); + // Keep disk registry.json on 1.0.0 and keep coldFgFiber held during initialProbe so + // checkProvider sees 1.0.0 (expectedRuntimeIdentity === v1Identity), initialProbe skips, + // and publishEnrichment's refreshIndex releases coldFgFiber and discovers failing 2.0.0. remoteVersion = "2.0.0"; failProbeSpawn = true; yield* realCatalog.invalidateIndex(); - yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const noAcceptV2Gate = { - matchVersion: "2.0.0", - started: yield* Deferred.make(), - release: yield* Deferred.make(), - }; - resolveGate = noAcceptV2Gate; + onRefreshIndex = () => + Deferred.succeed(releaseColdFg, undefined).pipe( + Effect.andThen(Deferred.await(coldFgDone)), + ); const noAcceptWarning = yield* noAcceptInstance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => snapshot.status === "warning"), Stream.runHead, @@ -3991,25 +4093,14 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* noAcceptInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), ); - yield* Deferred.await(noAcceptV2Gate.started); - // Seed 1.0.0 commands into coordinator while 2.0.0's probe is in flight (rejected by the - // watcher, so lastSuccessfulRuntime stays null) to prove the failed 2.0.0 publish never - // attaches 1.0.0 live state onto 2.0.0's failure snapshot. - const v1DuringV2Handled = yield* Deferred.make(); - onCommandHandled = { matchName: "v1-during-v2-fail", done: v1DuringV2Handled }; - yield* coordinator.publishAvailableCommands( - noAcceptId, - { slashCommands: [{ name: "v1-during-v2-fail" }], skills: [] }, - v1Identity, - ); - yield* Deferred.await(v1DuringV2Handled); - yield* Deferred.succeed(noAcceptV2Gate.release, undefined); const noAcceptSnapshot = Option.getOrThrow(yield* Fiber.join(noAcceptWarning)); yield* Deferred.await(noAcceptFailDone); + yield* Fiber.join(coldFgFiber); expect(noAcceptSnapshot.version).toBe("2.0.0"); expect(noAcceptSnapshot.message).toContain("2.0.0"); expect(noAcceptSnapshot.slashCommands).toEqual([]); - // A subsequent 1.0.0 update must NOT land on 2.0.0's failure snapshot. + // A subsequent 1.0.0 update must NOT land on 2.0.0's failure snapshot (requires + // runProbeAndPublish to have updated expectedRuntimeIdentity from v1Identity to v2Identity). const lateV1AfterFailHandled = yield* Deferred.make(); onCommandHandled = { matchName: "v1-after-v2-fail", done: lateV1AfterFailHandled }; yield* coordinator.publishAvailableCommands( @@ -4033,8 +4124,13 @@ createInterface({ input: process.stdin }).on("line", (line) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); - yield* noAcceptInstance.snapshot.refresh; + const noAcceptV2AdoptedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptV2AdoptedDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); expect(Option.isSome(yield* Fiber.join(noAcceptV2Adopted))).toBe(true); + yield* Deferred.await(noAcceptV2AdoptedDone); // 3. Fallback retirement stamps failedTarget's revision (v3), not a concurrently restored // v4 revision, so a new v4 session reconciles immediately even if v4 restored mid-probe. @@ -4064,8 +4160,11 @@ createInterface({ input: process.stdin }).on("line", (line) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const v2ReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v2ReadyDone, Exit.void); yield* fallbackRetireInstance.snapshot.refresh; expect(Option.isSome(yield* Fiber.join(v2Ready))).toBe(true); + yield* Deferred.await(v2ReadyDone); const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); expect(v2Inspection.status).toBe("ready"); const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; @@ -4243,40 +4342,98 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(recordedInspectRevisions).toEqual([r7, r8]); recordedInspectRevisions = null; - // A defect inside reconciliation must still release the reconcilingState claim (Effect.onError) - // so a subsequent event for the same identity reconciles cleanly once the catalog recovers. + // A defect inside reconciliation releases the reconcilingState claim AND replays a parked + // pending event for the same identity once without needing a third event. remoteExtraAgentVersion = "10.0.2"; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - defectNextInspect = true; - const defectSpanDone = yield* Deferred.make(); - onReconcileEnd = () => Deferred.doneUnsafe(defectSpanDone, Exit.void); + const defectInspectGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = defectInspectGate; + defectInspectCount = 1; yield* coordinator.publishAvailableCommands( fallbackRetireId, { slashCommands: [{ name: "v4-defect-probe" }], skills: [] }, v4Identity, ); - yield* Deferred.await(defectSpanDone); - + yield* Deferred.await(defectInspectGate.started); + // While the defecting reconcile is in flight, restore 4.0.0 and park a second v4 event. remoteVersion = "4.0.0"; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const v4RecoveredAfterDefect = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + const parkedDuringDefectHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-parked-on-defect", done: parkedDuringDefectHandled }; + const v4RecoveredByReplay = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.version === "4.0.0" && snapshot.nativeSessions !== undefined && - snapshot.slashCommands.some((cmd) => cmd.name === "v4-after-defect"), + snapshot.slashCommands.some((cmd) => cmd.name === "v4-parked-on-defect"), ), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const v4RecoveredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4RecoveredEnrichmentDone, Exit.void); yield* coordinator.publishAvailableCommands( fallbackRetireId, - { slashCommands: [{ name: "v4-after-defect" }], skills: [] }, + { slashCommands: [{ name: "v4-parked-on-defect" }], skills: [] }, v4Identity, ); - expect(Option.isSome(yield* Fiber.join(v4RecoveredAfterDefect))).toBe(true); + yield* Deferred.await(parkedDuringDefectHandled); + yield* Deferred.succeed(defectInspectGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(v4RecoveredByReplay))).toBe(true); + yield* Deferred.await(v4RecoveredEnrichmentDone); + + // Defect replay is bounded to one retry so a parked event arriving during the replay's + // own defect cannot loop forever (while still releasing reconcilingState cleanly). + remoteExtraAgentVersion = "10.0.3"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const boundedGate1 = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const boundedGate2 = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = boundedGate1; + defectInspectCount = 2; + const inspectsBeforeBounded = inspectCalls; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-bounded-defect-1" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(boundedGate1.started); + const boundedParked1 = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-bounded-defect-2", done: boundedParked1 }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-bounded-defect-2" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(boundedParked1); + inspectGate = boundedGate2; + yield* Deferred.succeed(boundedGate1.release, undefined); + yield* Deferred.await(boundedGate2.started); + // Park another v2 event during the replay defect; bounded replay must NOT launch a 3rd inspect. + const boundedParked2 = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-bounded-defect-3", done: boundedParked2 }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-bounded-defect-3" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(boundedParked2); + const boundedSecondSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(boundedSecondSpanDone, Exit.void); + yield* Deferred.succeed(boundedGate2.release, undefined); + yield* Deferred.await(boundedSecondSpanDone); + expect(inspectCalls).toBe(inspectsBeforeBounded + 2); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 9e5bb94372e6b..abc61dfb516a8 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -12,6 +12,7 @@ import { import { AcpRegistrySettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; +import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Digest from "effect/crypto/Digest"; @@ -52,6 +53,7 @@ import { import { type AcpRegistryAvailableCommands, type AcpRegistryConfigurationProbe, + type AcpRegistryConfigurationProbeResolved, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, deleteAcpRegistrySession, @@ -708,26 +710,47 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( cacheable: false, }; } + const resolvedDuringProbeRef = yield* Ref.make( + undefined, + ); const probed = yield* Effect.result( probeConfiguration({ instanceId: input.instanceId, settings: input.settings, cwd: input.cwd, environment: providerProbeEnvironment(input.environment), + onResolved: (resolved) => Ref.set(resolvedDuringProbeRef, resolved), }), ); if (Result.isFailure(probed)) { + const resolvedDuringProbe = yield* Ref.get(resolvedDuringProbeRef); + const failedInspection: AcpRegistrySupport.AcpRegistryInspection = + resolvedDuringProbe === undefined || input.settings.source === "local" + ? inspected.success + : { + ...inspected.success, + version: + input.settings.commandPath.trim().length > 0 + ? null + : (resolvedDuringProbe.agent?.version ?? inspected.success.version), + ...(resolvedDuringProbe.launchIdentity === undefined + ? {} + : { launchIdentity: resolvedDuringProbe.launchIdentity }), + }; + const failedLaunchIdentity = + resolvedDuringProbe?.launchIdentity ?? inspected.success.launchIdentity ?? null; + const failedIndexRevision = resolvedDuringProbe?.indexRevision ?? inspectedIndexRevision; return { provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, - inspection: inspected.success, + inspection: failedInspection, probeError: probed.failure, }), - launchIdentity: null, - indexRevision: inspectedIndexRevision, + launchIdentity: failedLaunchIdentity, + indexRevision: failedIndexRevision, cacheable: false, - failedTargetLaunchIdentity: inspected.success.launchIdentity ?? null, + failedTargetLaunchIdentity: failedLaunchIdentity, probeFailed: true, }; } @@ -1479,6 +1502,7 @@ export const AcpRegistryDriver: ProviderDriver({ inFlight: null, pending: null }); const maybeReconcileUnmatchedRuntime = ( incomingIdentity: string | undefined, + allowDefectReplay = true, ): Effect.Effect => { if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; return Effect.gen(function* () { @@ -1559,13 +1583,22 @@ export const AcpRegistryDriver: ProviderDriver - Ref.update(reconcilingState, (state) => { - if (!state.has(incomingIdentity)) return state; + Effect.onError((cause) => + Ref.modify(reconcilingState, (state) => { + if (!state.has(incomingIdentity)) return [false, state] as const; const next = new Map(state); + const pending = next.get(incomingIdentity) === true; next.delete(incomingIdentity); - return next; - }), + return [pending, next] as const; + }).pipe( + Effect.flatMap((replayPending) => + // Replay a parked update once after an unexpected defect (not scope + // interruption), bounding replay so repeated defects cannot loop. + replayPending && allowDefectReplay && !Cause.hasInterruptsOnly(cause) + ? maybeReconcileUnmatchedRuntime(incomingIdentity, false) + : Effect.void, + ), + ), ), Effect.withSpan("AcpRegistryDriver.reconcileUnmatchedRuntime"), Effect.forkIn(driverScope), @@ -1691,7 +1724,9 @@ export const AcpRegistryDriver: ProviderDriver Effect.Effect; } type AcpRegistryManagementInput = AcpRegistryConfigurationProbeInput; @@ -461,6 +462,19 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo const resolved = yield* catalog .resolve(input.settings, input.cwd, input.environment) .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)); + const resolvedMetadata: AcpRegistryConfigurationProbeResolved = { + ...(resolved.agent === undefined ? {} : { agent: resolved.agent }), + distribution: resolved.distribution, + ...(resolved.launchIdentity === undefined + ? {} + : { launchIdentity: resolved.launchIdentity }), + ...(resolved.indexRevision === undefined ? {} : { indexRevision: resolved.indexRevision }), + ...(resolved.fallback ? { fallback: true } : {}), + ...(resolved.failedTarget === undefined ? {} : { failedTarget: resolved.failedTarget }), + }; + if (input.onResolved !== undefined) { + yield* input.onResolved(resolvedMetadata); + } return yield* Effect.gen(function* () { const spawn = yield* isolateDeepSeekProbeHistory( input.settings.commandPath, @@ -615,6 +629,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo return { resolved, + resolvedMetadata, started, commands: yield* Ref.get(commandsRef), liveConfiguration, @@ -650,20 +665,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: result.commands.slashCommands, skills: result.commands.skills, - resolved: { - ...(result.resolved.agent === undefined ? {} : { agent: result.resolved.agent }), - distribution: result.resolved.distribution, - ...(result.resolved.launchIdentity === undefined - ? {} - : { launchIdentity: result.resolved.launchIdentity }), - ...(result.resolved.indexRevision === undefined - ? {} - : { indexRevision: result.resolved.indexRevision }), - ...(result.resolved.fallback ? { fallback: true } : {}), - ...(result.resolved.failedTarget === undefined - ? {} - : { failedTarget: result.resolved.failedTarget }), - }, + resolved: result.resolvedMetadata, }; }, ); From 58228c5a76cc3d44574b5448097c2822a17b97f7 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 18:47:15 +0000 Subject: [PATCH 20/28] fix(acp-registry): stamp receipt installId, coordinate sidecar syncs, persist unscanned baseline markers, and separate fallback failure targets --- .../src/server/AcpRegistrySupport.test.ts | 529 ++++++++++++++++-- .../src/server/AcpRegistrySupport.ts | 453 ++++++++------- .../src/server/driver.test.ts | 209 +++++-- .../src/server/driver.ts | 91 ++- 4 files changed, 966 insertions(+), 316 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index dd924d1ad5973..ef7ba9891c5ab 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -3896,6 +3896,7 @@ describe("AcpRegistrySupport", () => { version, }); let upstream = binaryAgent("1.2.3", archiveAUrl); + let extraUpstreamAgents: ReadonlyArray = []; let upstreamEmpty = false; let archiveRequestsDuringLockedSlot = 0; let countArchiveRequests = false; @@ -4390,9 +4391,38 @@ describe("AcpRegistrySupport", () => { "example-agent", ); const corruptUnreadableOtherTool = path.join(corruptToolsDir, "chrome-headless-shell"); + const corruptReadableRemovedExe = path.join( + corruptToolsDir, + "removed-readable-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + const corruptUnreadableRemovedDir = path.join(corruptToolsDir, "removed-unreadable-agent"); + const corruptUnreadableRemovedExe = path.join( + corruptUnreadableRemovedDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); yield* fileSystem.makeDirectory(path.dirname(corruptLegacyExe), { recursive: true }); yield* fileSystem.writeFileString(corruptLegacyExe, "#!/bin/sh\necho legacy-a\n"); yield* fileSystem.chmod(corruptLegacyExe, 0o755); + yield* fileSystem.makeDirectory(path.dirname(corruptReadableRemovedExe), { + recursive: true, + }); + yield* fileSystem.writeFileString(corruptReadableRemovedExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(corruptReadableRemovedExe, 0o755); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableRemovedExe), { + recursive: true, + }); + yield* fileSystem.writeFileString( + corruptUnreadableRemovedExe, + "#!/bin/sh\necho legacy-a\n", + ); + yield* fileSystem.chmod(corruptUnreadableRemovedExe, 0o755); yield* fileSystem.makeDirectory(corruptUnreadableOtherTool, { recursive: true }); yield* fileSystem.makeDirectory(corruptRegistryDir, { recursive: true }); yield* fileSystem.writeFileString( @@ -4400,10 +4430,12 @@ describe("AcpRegistrySupport", () => { makeRegistry(binaryAgent("1.0.0", archiveBUrl)), ); yield* fileSystem.writeFileString(corruptBaselinesPath, "{not json"); + let failRemovedUnreadable = true; const corruptToolsFs: FileSystem.FileSystem = { ...fileSystem, readDirectory: (dirPath, options) => - dirPath === corruptUnreadableOtherTool + dirPath === corruptUnreadableOtherTool || + (failRemovedUnreadable && dirPath === corruptUnreadableRemovedDir) ? fileSystem.readDirectory(corruptLegacyExe, options) : fileSystem.readDirectory(dirPath, options), }; @@ -4425,6 +4457,36 @@ describe("AcpRegistrySupport", () => { const exampleSlotKey = "example-agent\u00001.0.0\u0000linux-x86_64"; const otherSlotKey = "other-agent\u00001.0.0\u0000linux-x86_64"; expect(rebuiltBaselines[exampleSlotKey]).toBe("unknown"); + // Readable removed-agent slots are discovered and marked unknown; unreadable extra + // directories get an agent-level unknown sentinel so neither blocks recovery nor loses + // unknown provenance if the directory becomes readable and the agent is later re-added. + expect(rebuiltBaselines["removed-readable-agent\u00001.0.0\u0000linux-x86_64"]).toBe( + "unknown", + ); + expect(rebuiltBaselines["removed-unreadable-agent\u0000*"]).toBe("unknown"); + expect(rebuiltBaselines["chrome-headless-shell\u0000*"]).toBe("unknown"); + + // Make removed-unreadable-agent readable again, re-add it at 1.0.0 archive B, restart + // (keeping chrome-headless-shell unreadable to prove normal refreshes ignore it), and + // verify resolve() installs archive B instead of running old receipt-less legacy-a. + failRemovedUnreadable = false; + extraUpstreamAgents = [ + { ...binaryAgent("1.0.0", archiveBUrl), id: "removed-unreadable-agent" }, + ]; + const restartedCorruptResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: corruptDir, + toolsDir: corruptToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, corruptToolsFs)); + yield* restartedCorruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedReaddedUnreadable = yield* restartedCorruptResolver.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedReaddedUnreadable.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + extraUpstreamAgents = []; // Rolling back from C (2.0.0) to B (1.0.0) must install B instead of running legacy A as B. upstream = binaryAgent("1.0.0", archiveBUrl); @@ -4541,7 +4603,12 @@ describe("AcpRegistrySupport", () => { new Response( upstreamEmpty ? JSON.stringify({ version: "1.0.0", agents: [] }) - : makeRegistry(upstream), + : extraUpstreamAgents.length > 0 + ? JSON.stringify({ + version: "1.0.0", + agents: [upstream, ...extraUpstreamAgents], + }) + : makeRegistry(upstream), ), ), ); @@ -5238,6 +5305,100 @@ describe("AcpRegistrySupport", () => { expect(fallbackSeesNewerCatA.spawn.args).toEqual(["--v1", "--cat-a"]); expect(fallbackSeesNewerCatA.spawn.env?.STAGE).toBe("cat-a"); + // If the sidecar cache file disappears (e.g. cache directory cleared), resolving the + // same --cat-a options on supersededResolver must re-persist them instead of trusting memory. + yield* fileSystem.remove(supersededSidecarPath, { force: true }); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterCacheWipeCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterCacheWipeCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterCacheWipe = yield* afterCacheWipeCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackAfterCacheWipe.fallback).toBe(true); + expect(fallbackAfterCacheWipe.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackAfterCacheWipe.spawn.env?.STAGE).toBe("cat-a"); + + // A concurrent higher RECEIPT revision written by another catalog must also invalidate + // supersededResolver's memory cache when upstream returns to --cat-a. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--receipt-cat-b"], + env: { STAGE: "receipt-cat-b" }, + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterReceiptBumpCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterReceiptBumpCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterReceiptBump = yield* afterReceiptBumpCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackAfterReceiptBump.fallback).toBe(true); + expect(fallbackAfterReceiptBump.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackAfterReceiptBump.spawn.env?.STAGE).toBe("cat-a"); + + // Restore --updated to the receipt before testing corrupt-sidecar repair on both the + // matching-receipt path and the failed-receipt-write path. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + yield* fileSystem.writeFileString(supersededSidecarPath, "{corrupt-match"); + const repairOnMatchCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* repairOnMatchCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* repairOnMatchCatalog.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(`${supersededSidecarPath}.corrupt`)).toBe( + "{corrupt-match", + ); + expect(JSON.parse(yield* fileSystem.readFileString(supersededSidecarPath))).toEqual({}); + // A corrupt binary-launch-options.json is copied aside and repaired cleanly on write. yield* fileSystem.writeFileString(supersededSidecarPath, "{corrupt-sidecar"); failReceiptTempWrite = true; @@ -5292,7 +5453,12 @@ describe("AcpRegistrySupport", () => { // Reverting upstream back to the receipt's earlier args/env after restart prunes the // sidecar and persists the new generation; verify with ANOTHER fresh catalog instance. - const exampleSlotRootSuperseded = path.dirname(path.dirname(installedA.spawn.command)); + const exampleSlotRootSuperseded = path.join( + supersededToolsDir, + "example-agent", + "1.0.0", + path.basename(path.dirname(path.dirname(installedA.spawn.command))), + ); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -5429,8 +5595,11 @@ describe("AcpRegistrySupport", () => { yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* inPlaceCatalog.resolve(settings(), "/workspace"); failReceiptTempWrite = false; - // Break slot A's executable, then resolve A with new args --a3 so it reinstalls in place. + // Break slot A's executable, then resolve A with new args --a3 while sidecar reads fail + // so it reinstalls in place without being able to read or prune binary-launch-options.json; + // the fresh installId must still beat the old sidecar/memory --a2 entry in-process & restart. yield* fileSystem.remove(inPlaceSlotA.spawn.command, { force: true }); + failSidecarRead = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -5439,6 +5608,7 @@ describe("AcpRegistrySupport", () => { yield* inPlaceCatalog.invalidateIndex(); yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const reinstalledInPlace = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failSidecarRead = false; expect(reinstalledInPlace.spawn.command).toBe(inPlaceSlotA.spawn.command); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -5462,68 +5632,311 @@ describe("AcpRegistrySupport", () => { expect(restartedFallbackA3.fallback).toBe(true); expect(restartedFallbackA3.spawn.args).toEqual(["--a3"]); - // A concurrent higher revision already written to the sidecar must never be pruned or - // overwritten by a lower-revision sync (verified on the receipt-matches-target prune path). - const inPlaceSidecarPath = path.join( - inPlaceDir, - "acp-registry", - "binary-launch-options.json", - ); - const inPlaceSlotARoot = path.dirname(path.dirname(inPlaceSlotA.spawn.command)); - yield* fileSystem.writeFileString( - inPlaceSidecarPath, - JSON.stringify({ - [inPlaceSlotARoot]: { - version: "1.0.0", - archive: archiveAUrl, - cmd: "./bin/example-agent", - sha256: null, - args: ["--concurrent-rev-999"], - launchOptionsRevision: 999, - }, - }), + // Reinstalling a different artifact at the same primary path via another catalog must not + // let catalog A's cached memory entry for the old artifact skip updating the new receipt. + const swapPrimaryDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-swap-primary-", + }); + const swapPrimaryToolsDir = path.join(swapPrimaryDir, "tools"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + }); + const swapCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const swapCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* swapCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--shared-opt"], + }); + yield* swapCatA.invalidateIndex(); + yield* swapCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatA.resolve(settings(), "/workspace"); + // Catalog B uninstalls artifact A and installs artifact B with --other-opt at the same primary path. + yield* swapCatB.uninstallManagedBinary({ agentId: "example-agent" }); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--other-opt"], + }); + yield* swapCatB.invalidateIndex(); + yield* swapCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatB.resolve(settings(), "/workspace"); + // Catalog A now resolves artifact B with --shared-opt (matching its stale memory entry for A). + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--shared-opt"], + }); + yield* swapCatA.invalidateIndex(); + yield* swapCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const swapVerifyCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* swapVerifyCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const swapFallback = yield* swapVerifyCatalog.resolve(settings(), "/workspace"); + expect(swapFallback.fallback).toBe(true); + expect(swapFallback.spawn.args).toEqual(["--shared-opt"]); + + // Concurrent launch-option syncs on the same slot serialize revision allocation under the + // sidecar lock so a receipt write (rev 1) followed by a sidecar write gets rev 2 and wins, + // fallback reads the sidecar before receipts so concurrent receipt+prune never restores an + // older receipt, and uninstall prunes the sidecar before releasing the agent permit. + const coordDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-coord-sync-", + }); + const coordToolsDir = path.join(coordDir, "tools"); + const coordSidecarPath = path.join(coordDir, "acp-registry", "binary-launch-options.json"); + const coordSidecarLockPath = `${coordSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const coordSeed = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const coordInitial = yield* coordSeed.resolve(settings(), "/workspace"); + const coordSlotRoot = path.join( + coordToolsDir, + "example-agent", + "1.0.0", + path.basename(path.dirname(path.dirname(coordInitial.spawn.command))), ); - // Gate right after the initial sidecar read is skipped: even with a stale rev-0 sidecar - // check, a concurrent rev-999 write before the locked prune must survive intact. - let injectConcurrentHighRev = true; - const concurrentHighRevFs: FileSystem.FileSystem = { + const coordReceiptPath = path.join(coordSlotRoot, ".t3-artifact.json"); + + // (a) Catalog 1 pauses during its rev-1 receipt write while Catalog 2 starts with --c2 + // (whose receipt write fails); Catalog 2 waits on the sidecar lock, reads rev-1 receipt, + // and writes sidecar rev 2 (--c2) so fallback selects --c2 over rev-1 --c1. + const cat1WriteStarted = yield* Deferred.make(); + const releaseCat1Write = yield* Deferred.make(); + const cat2LockWaited = yield* Deferred.make(); + let gateCat1Receipt = true; + const coordCat1Fs: FileSystem.FileSystem = { ...posixModeFs, - readFileString: (filePath, encoding) => - filePath === inPlaceSidecarPath && injectConcurrentHighRev - ? Effect.sync(() => { - injectConcurrentHighRev = false; - }).pipe( - Effect.as( - JSON.stringify({ - [inPlaceSlotARoot]: { - version: "1.0.0", - archive: archiveAUrl, - cmd: "./bin/example-agent", - sha256: null, - args: ["--old-rev-1"], - launchOptionsRevision: 1, - }, - }), - ), - ) - : posixModeFs.readFileString(filePath, encoding), + writeFileString: (filePath, data, options) => { + if (gateCat1Receipt && path.basename(filePath).startsWith(".t3-artifact.json.")) { + gateCat1Receipt = false; + return Deferred.succeed(cat1WriteStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseCat1Write)), + Effect.andThen(posixModeFs.writeFileString(filePath, data, options)), + ); + } + return posixModeFs.writeFileString(filePath, data, options); + }, }; - const concurrentRevCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: inPlaceDir, - toolsDir: inPlaceToolsDir, + const coordCat2Fs: FileSystem.FileSystem = { + ...posixModeFs, + stat: (filePath) => + posixModeFs + .stat(filePath) + .pipe( + Effect.tap(() => + filePath === coordSidecarLockPath + ? Deferred.succeed(cat2LockWaited, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + writeFileString: (filePath, data, options) => + path.basename(filePath).startsWith(".t3-artifact.json.") + ? fileSystem.readFileString(path.dirname(filePath)).pipe(Effect.asVoid) + : posixModeFs.writeFileString(filePath, data, options), + }; + const coordCat1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordCat1Fs)); + const coordCat2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, registryUrl, - }).pipe(Effect.provideService(FileSystem.FileSystem, concurrentHighRevFs)); + }).pipe(Effect.provideService(FileSystem.FileSystem, coordCat2Fs)); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", - args: ["--a3"], + args: ["--c1"], }); - yield* concurrentRevCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - yield* concurrentRevCatalog.resolve(settings(), "/workspace"); - const sidecarAfterHighRevGuard = JSON.parse( - yield* fileSystem.readFileString(inPlaceSidecarPath), - ) as Record }>; - expect(sidecarAfterHighRevGuard[inPlaceSlotARoot]?.args).toEqual(["--concurrent-rev-999"]); + yield* coordCat1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--c2"], + }); + yield* coordCat2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const cat1Fiber = yield* coordCat1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(cat1WriteStarted); + const cat2Fiber = yield* coordCat2 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(cat2LockWaited); + yield* Deferred.succeed(releaseCat1Write, undefined); + yield* Fiber.join(cat1Fiber); + yield* TestClock.adjust("100 millis"); + yield* Fiber.join(cat2Fiber); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const coordVerify = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* coordVerify.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const coordFallbackC2 = yield* coordVerify.resolve(settings(), "/workspace"); + expect(coordFallbackC2.fallback).toBe(true); + expect(coordFallbackC2.spawn.args).toEqual(["--c2"]); + + // (b) Fallback reads the sidecar BEFORE receipts: pausing fallback right before it reads + // .t3-artifact.json while another writer publishes rev-3 --c3 to the receipt and prunes + // the sidecar must still yield --c3 (never the older rev-1 receipt). + const fbReceiptGateStarted = yield* Deferred.make(); + const releaseFbReceiptGate = yield* Deferred.make(); + let fbSawSidecar = false; + let gateFbReceipt = true; + const coordFallbackFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => { + if (filePath === coordSidecarPath) { + fbSawSidecar = true; + } + if (gateFbReceipt && fbSawSidecar && filePath === coordReceiptPath) { + gateFbReceipt = false; + return Deferred.succeed(fbReceiptGateStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFbReceiptGate)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + return posixModeFs.readFileString(filePath, encoding); + }, + }; + const coordFallbackReader = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordFallbackFs)); + yield* coordFallbackReader.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fbReaderFiber = yield* coordFallbackReader + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fbReceiptGateStarted); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--c3"], + }); + yield* coordSeed.invalidateIndex(); + yield* coordSeed.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* coordSeed.resolve(settings(), "/workspace"); + yield* Deferred.succeed(releaseFbReceiptGate, undefined); + const coordFallbackC3 = yield* Fiber.join(fbReaderFiber); + expect(coordFallbackC3.fallback).toBe(true); + expect(coordFallbackC3.spawn.args).toEqual(["--c3"]); + + // (c) Uninstall finishes sidecar cleanup before releasing the agent permit so a concurrent + // reinstall cannot have its new sidecar entry pruned by the old uninstall. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pre-uninstall"], + }); + yield* coordSeed.invalidateIndex(); + yield* coordSeed.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* coordSeed.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + const uninstallPruneStarted = yield* Deferred.make(); + const releaseUninstallPrune = yield* Deferred.make(); + let gateUninstallSidecar = true; + const coordUninstallFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => { + if (gateUninstallSidecar && filePath === coordSidecarPath) { + gateUninstallSidecar = false; + return Deferred.succeed(uninstallPruneStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseUninstallPrune)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + return posixModeFs.readFileString(filePath, encoding); + }, + }; + const coordPermitCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordUninstallFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-uninstall"], + }); + yield* coordPermitCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const uninstallFiber = yield* coordPermitCatalog + .uninstallManagedBinary({ agentId: "example-agent" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(uninstallPruneStarted); + // Start reinstall on the same catalog while uninstall is paused inside its sidecar prune; + // reinstall must wait on the agent permit until uninstall completes its prune. + const reinstallFiber = yield* coordPermitCatalog + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(reinstallFiber.pollUnsafe()).toBeUndefined(); + yield* Deferred.succeed(releaseUninstallPrune, undefined); + expect(yield* Fiber.join(uninstallFiber)).toEqual({ + agentId: "example-agent", + removed: true, + }); + const reinstalledAfterPermit = yield* Fiber.join(reinstallFiber); + expect(reinstalledAfterPermit.spawn.args).toEqual(["--after-uninstall"]); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-uninstall-sidecar"], + }); + yield* coordPermitCatalog.invalidateIndex(); + yield* coordPermitCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* coordPermitCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterUninstallVerify = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterUninstallVerify.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterPermitUninstall = yield* afterUninstallVerify.resolve( + settings(), + "/workspace", + ); + expect(fallbackAfterPermitUninstall.fallback).toBe(true); + expect(fallbackAfterPermitUninstall.spawn.args).toEqual(["--after-uninstall-sidecar"]); // 3. A superseded primary executable that lost execute permission must not fail inspect() // when the registry selects a different same-version artifact. diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 6d7d922fae1f9..85484f94957e2 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -742,6 +742,7 @@ const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ args: Schema.optional(Schema.Array(Schema.String)), env: Schema.optional(Schema.Record(Schema.String, Schema.String)), launchOptionsRevision: Schema.optional(Schema.Finite), + installId: Schema.optional(Schema.String), }); type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt.Type; const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( @@ -800,6 +801,10 @@ function legacyBaselineSlotKey( return `${agentId}\0${encodedVersion}\0${candidateTarget}`; } +function legacyBaselineAgentUnknownKey(agentId: string): string { + return `${agentId}\0*`; +} + function readLegacyBaselinesFile( fileSystem: FileSystem.FileSystem, baselinesPath: string, @@ -918,10 +923,36 @@ function binaryArtifactReceiptMatches( ); } +function receiptMatchesInstall( + candidate: AcpRegistryBinaryArtifactReceipt | undefined, + receipt: AcpRegistryBinaryArtifactReceipt, +): candidate is AcpRegistryBinaryArtifactReceipt { + return ( + candidate !== undefined && + candidate.archive === receipt.archive && + candidate.cmd === receipt.cmd && + (candidate.sha256 ?? null) === (receipt.sha256 ?? null) && + (candidate.installId ?? null) === (receipt.installId ?? null) + ); +} + +function receiptMatchesLaunchOptions( + receipt: AcpRegistryBinaryArtifactReceipt, + target: typeof AcpRegistryBinaryTarget.Type, +): boolean { + return ( + Equal.equals(receipt.args ?? [], target.args ?? []) && + Equal.equals(receipt.env ?? {}, target.env ?? {}) + ); +} + function encodeBinaryArtifactReceipt( agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type, - launchOptionsRevision?: number, + options?: { + readonly launchOptionsRevision?: number; + readonly installId?: string; + }, ): string { return JSON.stringify({ version: agent.version, @@ -930,7 +961,10 @@ function encodeBinaryArtifactReceipt( sha256: target.sha256 ?? null, ...(target.args && target.args.length > 0 ? { args: target.args } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: target.env } : {}), - ...(launchOptionsRevision !== undefined ? { launchOptionsRevision } : {}), + ...(options?.launchOptionsRevision !== undefined + ? { launchOptionsRevision: options.launchOptionsRevision } + : {}), + ...(options?.installId !== undefined ? { installId: options.installId } : {}), }); } @@ -1131,10 +1165,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // discovery; requires positive baseline provenance before reusing unreceipted legacy installs. let legacyBaselineDiscoveryIncomplete = false; // In-memory mirror of last-resolved binary launch options when updating .t3-artifact.json fails. - const syncedLaunchOptionsBySlotRoot = new Map< - string, - { readonly receipt: AcpRegistryBinaryArtifactReceipt; readonly persisted: boolean } - >(); + const syncedLaunchOptionsBySlotRoot = new Map(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -1632,22 +1663,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct readonly candidateTarget: AcpRegistryPlatformTarget; readonly slotKey: string; }> = []; + const unscannedExtraAgents: Array = []; for (const agentId of requiredAgentIds) { slots.push(...(yield* scanAgentLegacySlots(agentId))); } if (includeExtraDirectories) { - // On corrupt-baselines rebuild, also discover readable removed-agent slots while letting - // unreadable unrelated tool directories (e.g. tools/chrome-headless-shell) be skipped. + // On corrupt-baselines rebuild, also discover readable removed-agent slots and record + // an agent-level unknown sentinel for unreadable extra directories (such as unrelated + // tools or temporarily unreadable removed agents) so normal refreshes stay isolated + // without losing unknown provenance if a removed agent is later re-added. const requiredSet = new Set(requiredAgentIds); for (const entry of yield* listSubdirectories(installsDirectory)) { if (requiredSet.has(entry)) continue; - const extraSlots = yield* scanAgentLegacySlots(entry).pipe( - Effect.orElseSucceed(() => []), - ); - slots.push(...extraSlots); + const extraResult = yield* Effect.result(scanAgentLegacySlots(entry)); + if (Result.isSuccess(extraResult)) { + slots.push(...extraResult.success); + } else { + unscannedExtraAgents.push(entry); + } } } - return slots; + return { slots, unscannedExtraAgents }; }, ); @@ -1690,7 +1726,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ? initialDiskIndex.index.agents.map((agent) => agent.id) : []), ...(inMemoryPrevious?.agents.map((agent) => agent.id) ?? []), - ...Array.from(legacyBaselineBySlotKey.keys(), (key) => key.split("\0")[0] ?? ""), + ...Array.from(legacyBaselineBySlotKey.keys()) + .filter((key) => !key.endsWith("\0*")) + .map((key) => key.split("\0")[0] ?? ""), ]), ).filter((id) => id.length > 0); const initialIncludedExtraDirs = initialDisk.status === "corrupt"; @@ -1704,8 +1742,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); return false; } - const unreceiptedLegacySlots = scanResult.success; - if (unreceiptedLegacySlots.length === 0) { + const { slots: unreceiptedLegacySlots, unscannedExtraAgents } = scanResult.success; + if (unreceiptedLegacySlots.length === 0 && unscannedExtraAgents.length === 0) { legacyBaselineDiscoveryIncomplete = false; return true; } @@ -1747,6 +1785,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const newBaselines: Record = {}; let hasUpdates = false; for (const slot of unpersistedSlots) { + const agentUnknownKey = legacyBaselineAgentUnknownKey(slot.agentId); + if ( + existingBaselines[agentUnknownKey] === LEGACY_BASELINE_UNKNOWN || + legacyBaselineBySlotKey.get(agentUnknownKey) === LEGACY_BASELINE_UNKNOWN + ) { + legacyBaselineBySlotKey.set(slot.slotKey, LEGACY_BASELINE_UNKNOWN); + newBaselines[slot.slotKey] = LEGACY_BASELINE_UNKNOWN; + hasUpdates = true; + continue; + } const existingInMemory = legacyBaselineBySlotKey.get(slot.slotKey); if (existingInMemory !== undefined) { newBaselines[slot.slotKey] = existingInMemory; @@ -1817,12 +1865,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } let mergedBaselines: Record; if (disk.status === "corrupt") { - const corruptScanSlots = initialIncludedExtraDirs - ? unreceiptedLegacySlots + const corruptScan = initialIncludedExtraDirs + ? { slots: unreceiptedLegacySlots, unscannedExtraAgents } : yield* Effect.result(scanUnreceiptedLegacySlots(requiredAgentIds, true)).pipe( Effect.map((result) => (Result.isSuccess(result) ? result.success : null)), ); - if (corruptScanSlots === null) { + if (corruptScan === null) { legacyBaselineDiscoveryIncomplete = true; yield* Effect.logDebug( "Could not scan managed ACP binary directories while rebuilding corrupt legacy baselines; keeping existing disk registry cache.", @@ -1837,11 +1885,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .copyFile(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) .pipe(Effect.ignore); mergedBaselines = {}; - for (const slot of corruptScanSlots) { + for (const slot of corruptScan.slots) { const baseline = legacyBaselineBySlotKey.get(slot.slotKey) ?? LEGACY_BASELINE_UNKNOWN; mergedBaselines[slot.slotKey] = baseline; legacyBaselineBySlotKey.set(slot.slotKey, baseline); } + for (const unscannedAgentId of corruptScan.unscannedExtraAgents) { + const unknownKey = legacyBaselineAgentUnknownKey(unscannedAgentId); + mergedBaselines[unknownKey] = LEGACY_BASELINE_UNKNOWN; + legacyBaselineBySlotKey.set(unknownKey, LEGACY_BASELINE_UNKNOWN); + } } else { const { newBaselines, hasUpdates, readError } = yield* recordDivergingInMemory( disk.baselines, @@ -2600,16 +2653,24 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } } const currentKey = binaryArtifactIdentityKey(target); + const agentUnknownKey = legacyBaselineAgentUnknownKey(paths.slotKey.split("\0")[0] ?? ""); const memoryBaseline = legacyBaselineBySlotKey.get(paths.slotKey); if (memoryBaseline !== undefined) { return memoryBaseline === currentKey; } + if (legacyBaselineBySlotKey.get(agentUnknownKey) === LEGACY_BASELINE_UNKNOWN) { + return false; + } const diskResult = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); if (diskResult.status !== "ok") { return false; } const diskBaseline = diskResult.baselines[paths.slotKey]; if (diskBaseline === undefined) { + if (diskResult.baselines[agentUnknownKey] === LEGACY_BASELINE_UNKNOWN) { + legacyBaselineBySlotKey.set(agentUnknownKey, LEGACY_BASELINE_UNKNOWN); + return false; + } return !legacyBaselineDiscoveryIncomplete; } legacyBaselineBySlotKey.set(paths.slotKey, diskBaseline); @@ -2668,122 +2729,179 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct target: typeof AcpRegistryBinaryTarget.Type, ) { if (slot.receipt === undefined) return; - const memoryStored = syncedLaunchOptionsBySlotRoot.get(slot.root); + const initialReceipt = slot.receipt; const hasSidecar = yield* fileSystem .exists(binaryLaunchOptionsPath) .pipe(Effect.orElseSucceed(() => false)); - const diskResult = hasSidecar - ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) - : ({ status: "ok", entries: {} } as const); - const diskStored = diskResult.status === "ok" ? diskResult.entries[slot.root] : undefined; - const receiptRev = slot.receipt.launchOptionsRevision ?? 0; - const diskRev = diskStored?.launchOptionsRevision ?? 0; - const memoryRev = memoryStored?.receipt.launchOptionsRevision ?? 0; - if ( - memoryStored !== undefined && - memoryStored.persisted && - diskResult.status !== "corrupt" && - receiptRev <= memoryRev && - diskRev <= memoryRev && - Equal.equals(memoryStored.receipt.args ?? [], target.args ?? []) && - Equal.equals(memoryStored.receipt.env ?? {}, target.env ?? {}) - ) { - return; - } - const receiptMatchesTarget = - Equal.equals(slot.receipt.args ?? [], target.args ?? []) && - Equal.equals(slot.receipt.env ?? {}, target.env ?? {}); - if (memoryStored === undefined && receiptMatchesTarget) { - if (diskResult.status === "corrupt") { - yield* updateBinaryLaunchOptionsStore(() => null); + const memoryEntry = syncedLaunchOptionsBySlotRoot.get(slot.root); + const memoryStored = receiptMatchesInstall(memoryEntry, initialReceipt) + ? memoryEntry + : undefined; + const receiptRev = initialReceipt.launchOptionsRevision ?? 0; + const memoryRev = memoryStored?.launchOptionsRevision ?? 0; + if (!hasSidecar) { + if (receiptMatchesLaunchOptions(initialReceipt, target) && memoryRev <= receiptRev) { return; } - if (diskStored === undefined) return; - if (diskRev <= receiptRev) { - // Prune an older sidecar left behind by a prior cleanup failure without rewriting receipt. - yield* updateBinaryLaunchOptionsStore((entries) => { - const existing = entries[slot.root]; - if (existing === undefined || (existing.launchOptionsRevision ?? 0) > receiptRev) { - return null; + } else { + const diskResult = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); + if (diskResult.status === "ok") { + const diskStored = diskResult.entries[slot.root]; + const diskMatches = receiptMatchesInstall(diskStored, initialReceipt); + const diskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + const durableRev = Math.max(receiptRev, diskRev); + if (memoryRev <= durableRev) { + if (diskStored === undefined && receiptMatchesLaunchOptions(initialReceipt, target)) { + return; } - const { [slot.root]: _removed, ...rest } = entries; - return rest; - }); - return; + if ( + diskMatches && + diskRev > receiptRev && + receiptMatchesLaunchOptions(diskStored, target) + ) { + return; + } + } } } - const nextRevision = Math.max(receiptRev, diskRev, memoryRev) + 1; - const updatedReceipt: AcpRegistryBinaryArtifactReceipt = { + + const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); + const buildUpdatedReceipt = ( + baseReceipt: AcpRegistryBinaryArtifactReceipt, + revision: number, + ): AcpRegistryBinaryArtifactReceipt => ({ version: agent.version, archive: target.archive, cmd: target.cmd, sha256: target.sha256 ?? null, ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), - launchOptionsRevision: nextRevision, - }; - syncedLaunchOptionsBySlotRoot.set(slot.root, { - receipt: updatedReceipt, - persisted: false, + launchOptionsRevision: revision, + ...(baseReceipt.installId !== undefined ? { installId: baseReceipt.installId } : {}), }); - const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); - const receiptWrite = yield* Effect.result( - random.uuidV4().pipe( - Effect.flatMap((id) => { - const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; - return fileSystem - .writeFileString( - temporaryPath, - encodeBinaryArtifactReceipt(agent, target, nextRevision), - ) - .pipe( - Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), - Effect.ensuring( - fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), - ), - ); + yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const rawFreshReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); + const decodedFreshReceipt = Option.flatMap(rawFreshReceipt, decodeBinaryArtifactReceipt); + if ( + Option.isNone(decodedFreshReceipt) || + !receiptMatchesInstall(decodedFreshReceipt.value, initialReceipt) + ) { + return; + } + const freshReceipt = decodedFreshReceipt.value; + const freshReceiptRev = freshReceipt.launchOptionsRevision ?? 0; + const diskResult = yield* readBinaryLaunchOptionsFile( + fileSystem, + binaryLaunchOptionsPath, + ); + const isCorrupt = diskResult.status === "corrupt"; + const diskEntries = diskResult.status === "ok" ? diskResult.entries : {}; + const diskStored = diskResult.status === "ok" ? diskEntries[slot.root] : undefined; + const diskMatches = receiptMatchesInstall(diskStored, freshReceipt); + const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + if (receiptMatchesLaunchOptions(freshReceipt, target)) { + if (isCorrupt) { + if (!(yield* isLockOwned)) return; + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, {}).pipe(Effect.ignore); + syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); + return; + } + if (diskResult.status === "ok") { + if (diskStored === undefined) { + syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); + return; + } + if (!diskMatches || freshDiskRev <= freshReceiptRev) { + if (!(yield* isLockOwned)) return; + const { [slot.root]: _removed, ...rest } = diskEntries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); + syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); + return; + } + } + } + if ( + diskResult.status === "ok" && + diskMatches && + freshDiskRev > freshReceiptRev && + receiptMatchesLaunchOptions(diskStored, target) + ) { + syncedLaunchOptionsBySlotRoot.set(slot.root, diskStored); + return; + } + const rawMemory = syncedLaunchOptionsBySlotRoot.get(slot.root); + const freshMemoryRev = receiptMatchesInstall(rawMemory, freshReceipt) + ? (rawMemory.launchOptionsRevision ?? 0) + : 0; + const nextRevision = Math.max(freshReceiptRev, freshDiskRev, freshMemoryRev) + 1; + const updatedReceipt = buildUpdatedReceipt(freshReceipt, nextRevision); + syncedLaunchOptionsBySlotRoot.set(slot.root, updatedReceipt); + if (!(yield* isLockOwned)) return; + const receiptWrite = yield* Effect.result( + random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; + return fileSystem + .writeFileString( + temporaryPath, + encodeBinaryArtifactReceipt(agent, target, { + launchOptionsRevision: nextRevision, + ...(freshReceipt.installId !== undefined + ? { installId: freshReceipt.installId } + : {}), + }), + ) + .pipe( + Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), + Effect.ensuring( + fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), + ), + ); + }), + ), + ); + if (Result.isSuccess(receiptWrite)) { + if (isCorrupt || (diskResult.status === "ok" && diskStored !== undefined)) { + if (!(yield* isLockOwned)) return; + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + const { [slot.root]: _removed, ...rest } = diskEntries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); + } + return; + } + // If updating the receipt inside tools/ failed (e.g., read-only install directory or file + // lock), persist the updated launch options in registry cache storage so fallback still + // restores the last-resolved args and env even across restarts. + if (diskResult.status === "io_error") return; + if (!(yield* isLockOwned)) return; + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, { + ...diskEntries, + [slot.root]: updatedReceipt, + }).pipe(Effect.ignore); + }), + ).pipe( + Effect.catch(() => + Effect.sync(() => { + syncedLaunchOptionsBySlotRoot.set( + slot.root, + buildUpdatedReceipt(initialReceipt, Math.max(receiptRev, memoryRev) + 1), + ); }), ), ); - if (Result.isSuccess(receiptWrite)) { - syncedLaunchOptionsBySlotRoot.set(slot.root, { - receipt: updatedReceipt, - persisted: true, - }); - // Keep the slot receipt authoritative by pruning any older fallback sidecar entry. - if ( - yield* fileSystem.exists(binaryLaunchOptionsPath).pipe(Effect.orElseSucceed(() => false)) - ) { - yield* updateBinaryLaunchOptionsStore((entries) => { - const existing = entries[slot.root]; - if (existing === undefined || (existing.launchOptionsRevision ?? 0) > nextRevision) { - return null; - } - const { [slot.root]: _removed, ...rest } = entries; - return rest; - }); - } - return; - } - // If updating the receipt inside tools/ failed (e.g., read-only install directory or file - // lock), persist the updated launch options in registry cache storage so fallback still - // restores the last-resolved args and env even across restarts. - const sidecarPersisted = yield* updateBinaryLaunchOptionsStore((entries) => { - const existing = entries[slot.root]; - if (existing !== undefined && (existing.launchOptionsRevision ?? 0) > nextRevision) { - return null; - } - return { - ...entries, - [slot.root]: updatedReceipt, - }; - }); - if (sidecarPersisted) { - syncedLaunchOptionsBySlotRoot.set(slot.root, { - receipt: updatedReceipt, - persisted: true, - }); - } }, ); @@ -3015,26 +3133,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); - // Supersede any stale launch-options sidecar/memory entry left from an earlier broken - // install at destinationRoot so fallback never resurrects old options over the new receipt. - const priorMemoryRev = - syncedLaunchOptionsBySlotRoot.get(destinationRoot)?.receipt.launchOptionsRevision ?? 0; - const priorSidecarExists = yield* fileSystem - .exists(binaryLaunchOptionsPath) - .pipe(Effect.orElseSucceed(() => false)); - const priorSidecarResult = priorSidecarExists - ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) - : ({ status: "ok", entries: {} } as const); - const priorDiskRev = - priorSidecarResult.status === "ok" - ? (priorSidecarResult.entries[destinationRoot]?.launchOptionsRevision ?? 0) - : 0; - const maxPriorRev = Math.max(priorMemoryRev, priorDiskRev); - const freshLaunchOptionsRevision = maxPriorRev > 0 ? maxPriorRev + 1 : undefined; + // Stamp a fresh installId so stale in-memory or sidecar launch options from any prior + // broken install at destinationRoot can never match or outrank the new receipt. + const installId = yield* random.uuidV4(); yield* fileSystem .writeFileString( path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), - encodeBinaryArtifactReceipt(agent, target, freshLaunchOptionsRevision), + encodeBinaryArtifactReceipt(agent, target, { installId }), { flag: "wx" }, ) .pipe( @@ -3065,14 +3170,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return validated.value; } } - let promotedFreshSlot = false; - const promotedPath = yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( + return yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), - Effect.tap(() => - Effect.sync(() => { - promotedFreshSlot = true; - }), - ), Effect.catch((renameError) => findMatchingBinarySlot(paths, target).pipe( Effect.flatMap( @@ -3085,26 +3184,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ), ); - if (promotedFreshSlot) { - syncedLaunchOptionsBySlotRoot.delete(destinationRoot); - if ( - priorSidecarExists || - (yield* fileSystem - .exists(binaryLaunchOptionsPath) - .pipe(Effect.orElseSucceed(() => false))) - ) { - const promotedRev = freshLaunchOptionsRevision ?? 0; - yield* updateBinaryLaunchOptionsStore((entries) => { - const existing = entries[destinationRoot]; - if (existing === undefined || (existing.launchOptionsRevision ?? 0) > promotedRev) { - return null; - } - const { [destinationRoot]: _removed, ...rest } = entries; - return rest; - }); - } - } - return promotedPath; }).pipe(Effect.scoped), ).pipe( Effect.mapError((cause) => @@ -3467,6 +3546,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .toSorted((left, right) => compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), ); + // Read the launch-options sidecar BEFORE reading slot receipts so a concurrent writer that + // publishes a newer receipt and then prunes the older sidecar cannot leave fallback seeing + // both the older receipt and the post-prune empty sidecar. + const diskOverrideResult = (yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false))) + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); for (const versionDir of versions) { const versionRoot = path.join(agentRoot, versionDir); const entries = yield* fileSystem @@ -3520,25 +3607,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.option, ); if (Option.isNone(validated)) continue; - const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir)?.receipt; - const diskOverrideResult = (yield* fileSystem - .exists(binaryLaunchOptionsPath) - .pipe(Effect.orElseSucceed(() => false))) - ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) - : ({ status: "ok", entries: {} } as const); + const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir); const diskOverride = diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; - const matchesReceiptArtifact = ( - candidate: AcpRegistryBinaryArtifactReceipt | undefined, - ): candidate is AcpRegistryBinaryArtifactReceipt => - candidate !== undefined && - candidate.archive === receipt.archive && - candidate.cmd === receipt.cmd && - (candidate.sha256 ?? null) === (receipt.sha256 ?? null); let effectiveReceipt = receipt; for (const candidate of [diskOverride, memoryOverride]) { if ( - matchesReceiptArtifact(candidate) && + receiptMatchesInstall(candidate, receipt) && (candidate.launchOptionsRevision ?? 0) > (effectiveReceipt.launchOptionsRevision ?? 0) ) { @@ -3868,15 +3943,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct syncedLaunchOptionsBySlotRoot.delete(slotRoot); } } - } - return { agentId: safeAgentId, removed }; - }), - ), - ) - .pipe( - Effect.tap(({ agentId: removedAgentId, removed }) => - removed - ? Effect.all([ + // Finish durable metadata cleanup before releasing the agent permit so a concurrent + // reinstall cannot write new entries and have this uninstall prune them afterwards. + yield* Effect.all([ fileSystem.exists(legacyBaselinesPath).pipe( Effect.orElseSucceed(() => false), Effect.flatMap((hasBaselinesFile) => @@ -3888,7 +3957,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct legacyBaselinesPath, ); if (disk.status !== "ok") return; - const prefix = `${removedAgentId}\0`; const remaining = Object.fromEntries( Object.entries(disk.baselines).filter( ([key]) => !key.startsWith(prefix), @@ -3910,13 +3978,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.flatMap((hasLaunchOptionsFile) => hasLaunchOptionsFile ? updateBinaryLaunchOptionsStore((entries) => { - const removedAgentRoot = path.join(installsDirectory, removedAgentId); - const removedPrefix = `${removedAgentRoot}${path.sep}`; const remaining = Object.fromEntries( Object.entries(entries).filter( ([slotRoot]) => - slotRoot !== removedAgentRoot && - !slotRoot.startsWith(removedPrefix), + slotRoot !== agentRoot && !slotRoot.startsWith(agentRootPrefix), ), ); return Object.keys(remaining).length !== Object.keys(entries).length @@ -3926,9 +3991,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct : Effect.void, ), ), - ]).pipe(Effect.asVoid) - : Effect.void, + ]).pipe(Effect.asVoid); + } + return { agentId: safeAgentId, removed }; + }), ), + ) + .pipe( Effect.catchTags({ ServerSettingsError: (cause) => new AcpRegistryError({ diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index e44df8f718d12..b87492f5e1d2f 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -23,6 +23,7 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -3585,6 +3586,8 @@ describe("AcpRegistryDriver registry recovery", () => { "acp-driver-reconcile-edge-", ); const authFailAgentPath = path.join(directory, "auth-fail-agent.mjs"); + const exitFailAgentPath = path.join(directory, "exit-fail-agent.mjs"); + yield* fileSystem.writeFileString(exitFailAgentPath, "process.exit(1);\n"); yield* fileSystem.writeFileString( authFailAgentPath, ` @@ -3617,6 +3620,8 @@ createInterface({ input: process.stdin }).on("line", (line) => { let failArchiveVersions = new Set(); let failProbeSpawn = false; let failProbeAuth = false; + let failProbeExit = false; + let probeResolveCount = 0; let defectInspectCount = 0; let inspectCalls = 0; let onRefreshIndex: (() => Effect.Effect) | null = null; @@ -3762,6 +3767,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { }), resolve: (settings, cwd, environment) => Effect.gen(function* () { + if (environment?.MISE_OFFLINE === "1") { + probeResolveCount += 1; + } if (environment?.MISE_OFFLINE === "1" && onBeforeProbeResolve !== null) { const hook = onBeforeProbeResolve; onBeforeProbeResolve = null; @@ -3789,9 +3797,11 @@ createInterface({ input: process.stdin }).on("line", (line) => { spawn: { command: process.execPath, args: - environment?.MISE_OFFLINE === "1" && failProbeAuth - ? [authFailAgentPath] - : [agentPath, modelsPath], + environment?.MISE_OFFLINE === "1" && failProbeExit + ? [exitFailAgentPath] + : environment?.MISE_OFFLINE === "1" && failProbeAuth + ? [authFailAgentPath] + : [agentPath, modelsPath], }, }; }), @@ -4008,11 +4018,97 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(fallbackAuthSnapshot.status).toBe("warning"); expect(fallbackAuthSnapshot.auth.status).toBe("unauthenticated"); expect(fallbackAuthSnapshot.message).toContain("API key"); + + // A live config update while the active runtime itself is unauthenticated must preserve + // warning status, unauthenticated auth, and sign-in guidance instead of flipping to ready. + const unauthLiveUpdated = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-d")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-d", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-d", name: "fg-v1-d" }, + ], + }), + v1Identity, + ); + const unauthWithD = Option.getOrThrow(yield* Fiber.join(unauthLiveUpdated)); + expect(unauthWithD.status).toBe("warning"); + expect(unauthWithD.auth.status).toBe("unauthenticated"); + expect(unauthWithD.message).toContain("API key"); + + // (c) Fallback auth failure records failedTarget.indexRevision so a refresh where resolve + // discovers a newer failing target (2.0.1) and falls back to 1.0.0 does not re-probe + // 2.0.1 / 1.0.0 a second time inside the same refresh. + failArchiveVersions = new Set(["2.0.0", "2.0.1"]); + onBeforeProbeResolve = () => { + remoteVersion = "2.0.1"; + return realCatalog + .invalidateIndex() + .pipe( + Effect.andThen(realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 })), + Effect.ignore, + ); + }; + probeResolveCount = 0; + const fallbackRevDedupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackRevDedupDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackRevDedupDone); + expect(probeResolveCount).toBe(1); + + // (d) A post-resolution non-auth failure after fallback (2.0.1 download fails, fallback + // 1.0.0 exits immediately) must preserve warning + the real probe error and replace + // failedUpgradeTarget so the stale "API key" message does not return on live updates. + failProbeAuth = false; + failProbeExit = true; + const fallbackExitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackExitDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackExitDone); + const fallbackExitSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(fallbackExitSnapshot.version).toBe("1.0.0"); + expect(fallbackExitSnapshot.status).toBe("warning"); + expect(fallbackExitSnapshot.auth.status).toBe("unknown"); + expect(fallbackExitSnapshot.message).toBeDefined(); + expect(fallbackExitSnapshot.message).not.toContain("API key"); + const exitLiveUpdated = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-e")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-e", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-e", name: "fg-v1-e" }, + ], + }), + v1Identity, + ); + const exitWithE = Option.getOrThrow(yield* Fiber.join(exitLiveUpdated)); + expect(exitWithE.status).toBe("warning"); + expect(exitWithE.message).toBeDefined(); + expect(exitWithE.message).not.toContain("API key"); + failProbeExit = false; failArchiveVersions = new Set(); + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); // Now make 2.0.0 fail with a different install_failed message and verify the earlier // auth warning message did not leak into lastSuccessfulRuntime. - failProbeAuth = false; failProbeSpawn = true; const fgSwitchedWarning = yield* fgConfigInstance.snapshot.streamChanges.pipe( Stream.filter((snapshot) => Boolean(snapshot.message?.includes("2.0.0"))), @@ -4028,7 +4124,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.await(fgSwitchedDone); expect(fgSwitchedSnapshot.version).toBe("1.0.0"); expect(fgSwitchedSnapshot.message).not.toContain("API key"); - expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-c"); + expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-e"); // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed // 2.0.0 probe discovered via recheck (with expectedRuntimeIdentity still on 1.0.0!) publishes @@ -4054,6 +4150,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { ); yield* Deferred.await(coldFgStarted); const noAcceptId = ProviderInstanceId.make("acpRegistry_no_accepted_v1"); + // Drain makeManagedServerProvider's automatic startup enrichment before arming hooks + // so it cannot consume onRefreshIndex out of order. + const noAcceptStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptStartupDone, Exit.void); const noAcceptInstance = yield* AcpRegistryDriver.create({ instanceId: noAcceptId, displayName: "No Accepted V1", @@ -4066,7 +4166,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, coordinator, ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), ); + yield* Deferred.await(noAcceptStartupDone); const noAcceptColdEnrichmentDone = yield* Deferred.make(); onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptColdEnrichmentDone, Exit.void); yield* noAcceptInstance.snapshot.refresh.pipe( @@ -4139,6 +4241,14 @@ createInterface({ input: process.stdin }).on("line", (line) => { remoteVersion = "2.0.0"; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const controlledDispatcher = new Scheduler.MixedScheduler("async").makeDispatcher(); + const controlledScheduler: Scheduler.Scheduler = { + executionMode: "async", + shouldYield: () => false, + makeDispatcher: () => controlledDispatcher, + }; + const fallbackStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackStartupDone, Exit.void); const fallbackRetireInstance = yield* AcpRegistryDriver.create({ instanceId: fallbackRetireId, displayName: "Fallback Retire Rev", @@ -4152,7 +4262,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { coordinator, ), Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), ); + yield* Deferred.await(fallbackStartupDone); const v2Ready = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( Stream.filter( (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, @@ -4162,7 +4274,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { ); const v2ReadyDone = yield* Deferred.make(); onEnrichmentEnd = () => Deferred.doneUnsafe(v2ReadyDone, Exit.void); - yield* fallbackRetireInstance.snapshot.refresh; + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); expect(Option.isSome(yield* Fiber.join(v2Ready))).toBe(true); yield* Deferred.await(v2ReadyDone); const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); @@ -4387,53 +4501,68 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(Option.isSome(yield* Fiber.join(v4RecoveredByReplay))).toBe(true); yield* Deferred.await(v4RecoveredEnrichmentDone); - // Defect replay is bounded to one retry so a parked event arriving during the replay's - // own defect cannot loop forever (while still releasing reconcilingState cleanly). + // A defect with no parked update does not self-loop, and scope interruption of a + // reconciliation with a parked update does NOT replay (!Cause.hasInterruptsOnly). remoteExtraAgentVersion = "10.0.3"; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const boundedGate1 = { - started: yield* Deferred.make(), - release: yield* Deferred.make(), - }; - const boundedGate2 = { - started: yield* Deferred.make(), - release: yield* Deferred.make(), - }; - inspectGate = boundedGate1; - defectInspectCount = 2; - const inspectsBeforeBounded = inspectCalls; + defectInspectCount = 1; + const inspectsBeforeNoPending = inspectCalls; + const noPendingDefectDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(noPendingDefectDone, Exit.void); yield* coordinator.publishAvailableCommands( fallbackRetireId, - { slashCommands: [{ name: "v2-bounded-defect-1" }], skills: [] }, + { slashCommands: [{ name: "v2-defect-no-pending" }], skills: [] }, v2Identity, ); - yield* Deferred.await(boundedGate1.started); - const boundedParked1 = yield* Deferred.make(); - onCommandHandled = { matchName: "v2-bounded-defect-2", done: boundedParked1 }; + yield* Deferred.await(noPendingDefectDone); + controlledDispatcher.flush(); + expect(inspectCalls).toBe(inspectsBeforeNoPending + 1); + + const interruptScope = yield* Scope.make(); + const interruptId = ProviderInstanceId.make("acpRegistry_interrupt_reconcile"); + const interruptStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(interruptStartupDone, Exit.void); + yield* AcpRegistryDriver.create({ + instanceId: interruptId, + displayName: "Interrupt Reconcile", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Scope.provide(interruptScope), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), + ); + yield* Deferred.await(interruptStartupDone); + const interruptGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = interruptGate; + const inspectsBeforeInterrupt = inspectCalls; yield* coordinator.publishAvailableCommands( - fallbackRetireId, - { slashCommands: [{ name: "v2-bounded-defect-2" }], skills: [] }, + interruptId, + { slashCommands: [{ name: "v2-interrupt-1" }], skills: [] }, v2Identity, ); - yield* Deferred.await(boundedParked1); - inspectGate = boundedGate2; - yield* Deferred.succeed(boundedGate1.release, undefined); - yield* Deferred.await(boundedGate2.started); - // Park another v2 event during the replay defect; bounded replay must NOT launch a 3rd inspect. - const boundedParked2 = yield* Deferred.make(); - onCommandHandled = { matchName: "v2-bounded-defect-3", done: boundedParked2 }; + yield* Deferred.await(interruptGate.started); + const interruptParked = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-interrupt-2", done: interruptParked }; yield* coordinator.publishAvailableCommands( - fallbackRetireId, - { slashCommands: [{ name: "v2-bounded-defect-3" }], skills: [] }, + interruptId, + { slashCommands: [{ name: "v2-interrupt-2" }], skills: [] }, v2Identity, ); - yield* Deferred.await(boundedParked2); - const boundedSecondSpanDone = yield* Deferred.make(); - onReconcileEnd = () => Deferred.doneUnsafe(boundedSecondSpanDone, Exit.void); - yield* Deferred.succeed(boundedGate2.release, undefined); - yield* Deferred.await(boundedSecondSpanDone); - expect(inspectCalls).toBe(inspectsBeforeBounded + 2); + yield* Deferred.await(interruptParked); + yield* Scope.close(interruptScope, Exit.void); + controlledDispatcher.flush(); + expect(inspectCalls).toBe(inspectsBeforeInterrupt + 1); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index abc61dfb516a8..d53c51ec60496 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -664,6 +664,7 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( readonly fallbackTargetLaunchIdentity?: string | null; readonly fallbackTargetVersion?: string | null; readonly fallbackTargetIndexRevision?: number | null; + readonly probedLaunchIdentity?: string | null; readonly failedTargetLaunchIdentity?: string | null; readonly probeFailed?: boolean; }, @@ -737,9 +738,18 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( ? {} : { launchIdentity: resolvedDuringProbe.launchIdentity }), }; - const failedLaunchIdentity = + const probedLaunchIdentity = resolvedDuringProbe?.launchIdentity ?? inspected.success.launchIdentity ?? null; - const failedIndexRevision = resolvedDuringProbe?.indexRevision ?? inspectedIndexRevision; + const failedTargetLaunchIdentity = + (resolvedDuringProbe?.fallback + ? resolvedDuringProbe.failedTarget?.launchIdentity + : undefined) ?? probedLaunchIdentity; + const failedIndexRevision = + (resolvedDuringProbe?.fallback + ? resolvedDuringProbe.failedTarget?.indexRevision + : undefined) ?? + resolvedDuringProbe?.indexRevision ?? + inspectedIndexRevision; return { provider: buildCheckedAcpRegistrySnapshot({ ...input, @@ -747,10 +757,11 @@ const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( inspection: failedInspection, probeError: probed.failure, }), - launchIdentity: failedLaunchIdentity, + launchIdentity: null, indexRevision: failedIndexRevision, cacheable: false, - failedTargetLaunchIdentity: failedLaunchIdentity, + probedLaunchIdentity, + failedTargetLaunchIdentity, probeFailed: true, }; } @@ -1368,6 +1379,7 @@ export const AcpRegistryDriver: ProviderDriver({ inFlight: null, pending: null }); const maybeReconcileUnmatchedRuntime = ( incomingIdentity: string | undefined, - allowDefectReplay = true, ): Effect.Effect => { if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; return Effect.gen(function* () { @@ -1592,10 +1606,9 @@ export const AcpRegistryDriver: ProviderDriver - // Replay a parked update once after an unexpected defect (not scope - // interruption), bounding replay so repeated defects cannot loop. - replayPending && allowDefectReplay && !Cause.hasInterruptsOnly(cause) - ? maybeReconcileUnmatchedRuntime(incomingIdentity, false) + // Replay a parked update after an unexpected defect (never on interruption). + replayPending && !Cause.hasInterruptsOnly(cause) + ? maybeReconcileUnmatchedRuntime(incomingIdentity) : Effect.void, ), ), @@ -1673,6 +1686,7 @@ export const AcpRegistryDriver: ProviderDriver prev !== null && prev.identity === activeId - ? { identity: prev.identity, provider: appliedClean } - : prev === null + ? { + identity: prev.identity, + provider: isUnauthenticated + ? { ...appliedClean, auth: prev.provider.auth } + : appliedClean, + } + : prev === null && !isUnauthenticated ? { identity: activeId, provider: { From 33fe92c2008ebd9561441e9c5e9079f1091bbc2b Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 19:28:46 +0000 Subject: [PATCH 21/28] fix(acp-registry): separate pending launch options from committed revisions and gate auth confirmation on accepted publications --- .../src/server/AcpRegistrySupport.test.ts | 369 ++++++++++++++++-- .../src/server/AcpRegistrySupport.ts | 158 +++++--- .../src/server/driver.test.ts | 276 +++++++++++-- .../src/server/driver.ts | 272 ++++++++----- 4 files changed, 843 insertions(+), 232 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index ef7ba9891c5ab..b3fcb46389741 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -18,6 +18,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -4466,28 +4467,118 @@ describe("AcpRegistrySupport", () => { expect(rebuiltBaselines["removed-unreadable-agent\u0000*"]).toBe("unknown"); expect(rebuiltBaselines["chrome-headless-shell\u0000*"]).toBe("unknown"); - // Make removed-unreadable-agent readable again, re-add it at 1.0.0 archive B, restart - // (keeping chrome-headless-shell unreadable to prove normal refreshes ignore it), and - // verify resolve() installs archive B instead of running old receipt-less legacy-a. + // Verify \0* sentinels are excluded from normal requiredAgentIds, honored on direct disk + // and in-memory lookups and in recordDivergingInMemory, and pruned on uninstall. failRemovedUnreadable = false; - extraUpstreamAgents = [ - { ...binaryAgent("1.0.0", archiveBUrl), id: "removed-unreadable-agent" }, - ]; - const restartedCorruptResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + upstream = binaryAgent("2.0.1", archiveCUrl); + yield* corruptResolver.invalidateIndex(); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(corruptRegistryPath)).toContain("2.0.1"); + + // Direct resolve without refreshIndex() verifies disk \0* check in isLegacyBinarySlotEligible, + // and a second resolve on a second unreceipted version verifies memory \0* check. + const corruptUnreadableV2Exe = path.join( + corruptUnreadableRemovedDir, + "2.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableV2Exe), { recursive: true }); + yield* fileSystem.writeFileString(corruptUnreadableV2Exe, "#!/bin/sh\necho legacy-v2\n"); + yield* fileSystem.chmod(corruptUnreadableV2Exe, 0o755); + yield* fileSystem.writeFileString( + corruptRegistryPath, + JSON.stringify({ + version: "1.0.0", + agents: [ + binaryAgent("2.0.1", archiveCUrl), + { ...binaryAgent("1.0.0", archiveAUrl), id: "removed-unreadable-agent" }, + ], + }), + ); + const directDiskSentinelCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: corruptDir, toolsDir: corruptToolsDir, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, corruptToolsFs)); - yield* restartedCorruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const resolvedReaddedUnreadable = yield* restartedCorruptResolver.resolve( + const resolvedDirectDiskSentinel = yield* directDiskSentinelCatalog.resolve( settings({ agentId: "removed-unreadable-agent" }), "/workspace", ); - expect(yield* fileSystem.readFileString(resolvedReaddedUnreadable.spawn.command)).toBe( + expect(yield* fileSystem.readFileString(resolvedDirectDiskSentinel.spawn.command)).toBe( + "#!/bin/sh\necho archive-a\n", + ); + // Now refresh from 1.0.0 archiveA -> 1.0.0 archiveB while 2.0.0 stays unreceipted: + // recordDivergingInMemory must record "unknown" (not archiveA) for 2.0.0, and direct + // resolve of 2.0.0 hits the in-memory \0* check. + extraUpstreamAgents = [ + { ...binaryAgent("2.0.0", archiveBUrl), id: "removed-unreadable-agent" }, + ]; + yield* directDiskSentinelCatalog.invalidateIndex(); + yield* directDiskSentinelCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const baselinesAfterDiverge = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(baselinesAfterDiverge["removed-unreadable-agent\u00002.0.0\u0000linux-x86_64"]).toBe( + "unknown", + ); + const resolvedMemorySentinel = yield* directDiskSentinelCatalog.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedMemorySentinel.spawn.command)).toBe( "#!/bin/sh\necho archive-b\n", ); + expect( + yield* directDiskSentinelCatalog.uninstallManagedBinary({ + agentId: "removed-unreadable-agent", + }), + ).toEqual({ agentId: "removed-unreadable-agent", removed: true }); + const baselinesAfterSentinelUninstall = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(baselinesAfterSentinelUninstall["removed-unreadable-agent\u0000*"]).toBeUndefined(); + expect( + baselinesAfterSentinelUninstall["removed-unreadable-agent\u00002.0.0\u0000linux-x86_64"], + ).toBeUndefined(); + expect(baselinesAfterSentinelUninstall["chrome-headless-shell\u0000*"]).toBe("unknown"); extraUpstreamAgents = []; + // Corrupt-baselines rebuild with ONLY an unreadable extra directory (zero readable legacy + // slots) must still copy aside .corrupt and persist the agent-level unknown sentinel. + const onlyUnscannedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-only-unscanned-", + }); + const onlyUnscannedTools = path.join(onlyUnscannedDir, "tools"); + const onlyUnscannedTool = path.join(onlyUnscannedTools, "chrome-headless-shell"); + const onlyUnscannedDummyFile = path.join(onlyUnscannedDir, "not-a-dir"); + const onlyUnscannedRegDir = path.join(onlyUnscannedDir, "acp-registry"); + const onlyUnscannedBaselines = path.join(onlyUnscannedRegDir, "legacy-baselines.json"); + yield* fileSystem.makeDirectory(onlyUnscannedTool, { recursive: true }); + yield* fileSystem.writeFileString(onlyUnscannedDummyFile, "x"); + yield* fileSystem.makeDirectory(onlyUnscannedRegDir, { recursive: true }); + yield* fileSystem.writeFileString(onlyUnscannedBaselines, "{only-unscanned"); + const onlyUnscannedFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === onlyUnscannedTool + ? fileSystem.readDirectory(onlyUnscannedDummyFile, options) + : fileSystem.readDirectory(dirPath, options), + }; + const onlyUnscannedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: onlyUnscannedDir, + toolsDir: onlyUnscannedTools, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, onlyUnscannedFs)); + yield* onlyUnscannedResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${onlyUnscannedBaselines}.corrupt`)).toBe( + "{only-unscanned", + ); + expect(JSON.parse(yield* fileSystem.readFileString(onlyUnscannedBaselines))).toEqual({ + "chrome-headless-shell\u0000*": "unknown", + }); + // Rolling back from C (2.0.0) to B (1.0.0) must install B instead of running legacy A as B. upstream = binaryAgent("1.0.0", archiveBUrl); yield* corruptResolver.invalidateIndex(); @@ -5856,7 +5947,7 @@ describe("AcpRegistrySupport", () => { expect(coordFallbackC3.spawn.args).toEqual(["--c3"]); // (c) Uninstall finishes sidecar cleanup before releasing the agent permit so a concurrent - // reinstall cannot have its new sidecar entry pruned by the old uninstall. + // reinstall cannot enter install I/O or write a sidecar entry before cleanup runs. failReceiptTempWrite = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -5867,27 +5958,45 @@ describe("AcpRegistrySupport", () => { yield* coordSeed.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* coordSeed.resolve(settings(), "/workspace"); failReceiptTempWrite = false; - const uninstallPruneStarted = yield* Deferred.make(); - const releaseUninstallPrune = yield* Deferred.make(); - let gateUninstallSidecar = true; + const uninstallBeforeLockStarted = yield* Deferred.make(); + const releaseUninstallBeforeLock = yield* Deferred.make(); + let gateUninstallExists = true; + let reinstallEnteredInstall = false; const coordUninstallFs: FileSystem.FileSystem = { ...posixModeFs, - readFileString: (filePath, encoding) => { - if (gateUninstallSidecar && filePath === coordSidecarPath) { - gateUninstallSidecar = false; - return Deferred.succeed(uninstallPruneStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseUninstallPrune)), - Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + exists: (filePath) => { + // Pause uninstall BEFORE it takes the sidecar lock so an early permit release would + // let reinstall run all the way through install + sidecar write while paused. + if (gateUninstallExists && filePath === coordSidecarPath) { + gateUninstallExists = false; + return Deferred.succeed(uninstallBeforeLockStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseUninstallBeforeLock)), + Effect.andThen(posixModeFs.exists(filePath)), ); } - return posixModeFs.readFileString(filePath, encoding); + return posixModeFs.exists(filePath); }, + makeDirectory: (dirPath, options) => + Effect.sync(() => { + if (!gateUninstallExists && dirPath.startsWith(coordToolsDir)) { + reinstallEnteredInstall = true; + } + }).pipe(Effect.andThen(posixModeFs.makeDirectory(dirPath, options))), + }; + const uninstallSchedulerDispatcher = new Scheduler.MixedScheduler("async").makeDispatcher(); + const uninstallScheduler: Scheduler.Scheduler = { + executionMode: "async", + shouldYield: () => false, + makeDispatcher: () => uninstallSchedulerDispatcher, }; const coordPermitCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: coordDir, toolsDir: coordToolsDir, registryUrl, - }).pipe(Effect.provideService(FileSystem.FileSystem, coordUninstallFs)); + }).pipe( + Effect.provideService(FileSystem.FileSystem, coordUninstallFs), + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + ); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -5896,47 +6005,221 @@ describe("AcpRegistrySupport", () => { yield* coordPermitCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const uninstallFiber = yield* coordPermitCatalog .uninstallManagedBinary({ agentId: "example-agent" }) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* Deferred.await(uninstallPruneStarted); - // Start reinstall on the same catalog while uninstall is paused inside its sidecar prune; - // reinstall must wait on the agent permit until uninstall completes its prune. + .pipe( + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.await(uninstallBeforeLockStarted); + // Start reinstall on the same catalog while uninstall is paused BEFORE its sidecar lock; + // flush the scheduler and assert reinstall has NOT entered installBinary (blocked on permit). const reinstallFiber = yield* coordPermitCatalog .resolve(settings(), "/workspace") - .pipe(Effect.forkScoped({ startImmediately: true })); - expect(reinstallFiber.pollUnsafe()).toBeUndefined(); - yield* Deferred.succeed(releaseUninstallPrune, undefined); + .pipe( + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + Effect.forkScoped({ startImmediately: true }), + ); + uninstallSchedulerDispatcher.flush(); + expect(reinstallEnteredInstall).toBe(false); + yield* Deferred.succeed(releaseUninstallBeforeLock, undefined); expect(yield* Fiber.join(uninstallFiber)).toEqual({ agentId: "example-agent", removed: true, }); const reinstalledAfterPermit = yield* Fiber.join(reinstallFiber); + expect(reinstallEnteredInstall).toBe(true); expect(reinstalledAfterPermit.spawn.args).toEqual(["--after-uninstall"]); + + // (d) Sidecar io_error neither rewrites matching receipts nor allocates below unreadable + // sidecars; pending options stay separate from committed revisions; lock timeouts + // observe fast-path sidecar revisions for in-process fallback. + const edgeSyncDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-edge-sync-", + }); + const edgeSyncToolsDir = path.join(edgeSyncDir, "tools"); + const edgeSyncSidecarPath = path.join( + edgeSyncDir, + "acp-registry", + "binary-launch-options.json", + ); + const edgeSyncSidecarLockPath = `${edgeSyncSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-init"], + }); + const edgeCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const edgeCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* edgeCatA.resolve(settings(), "/workspace"); + // Write rev 1 and rev 2 to sidecar while receipt stays at rev 0 (--edge-init). failReceiptTempWrite = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", - args: ["--after-uninstall-sidecar"], + args: ["--edge-sidecar-1"], }); - yield* coordPermitCatalog.invalidateIndex(); - yield* coordPermitCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - yield* coordPermitCatalog.resolve(settings(), "/workspace"); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-sidecar-2"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); failReceiptTempWrite = false; + // 1) Matching receipt + sidecar io_error must NOT rewrite the receipt on every resolve. + failSidecarRead = true; + receiptRenameCount = 0; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-init"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + // 2) Different target + sidecar io_error must NOT allocate rev 1 below unreadable sidecar rev 2. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-after-io"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + // Once reads recover, retrying the same target allocates rev 3 (> sidecar rev 2) cleanly. + failSidecarRead = false; + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(1); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - const afterUninstallVerify = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: coordDir, - toolsDir: coordToolsDir, + const edgeVerifyAfterIo = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, registryUrl, }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); - yield* afterUninstallVerify.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const fallbackAfterPermitUninstall = yield* afterUninstallVerify.resolve( - settings(), - "/workspace", - ); - expect(fallbackAfterPermitUninstall.fallback).toBe(true); - expect(fallbackAfterPermitUninstall.spawn.args).toEqual(["--after-uninstall-sidecar"]); + yield* edgeVerifyAfterIo.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeVerifyAfterIo.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-after-io", + ]); + // 3) Repeated failed writes (both receipt & sidecar failing twice) must NOT inflate + // committed revisions: in-process fallback uses pending --fail-2 while disk stays at + // rev 3, and once catalog B commits rev 4 (--commit-b), catalog A's fallback yields --commit-b. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fail-1"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fail-2"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + // Before catalog B commits a newer rev, edgeCatA's in-process fallback uses pending --fail-2. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fail-2", + ]); + // Now catalog B commits rev 4 (--commit-b); edgeCatA's fallback must prefer committed --commit-b. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-b"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-b", + ]); + // 4) Lock timeout after restart with higher-rev sidecar still preserves pending --lock-c in fallback. + failReceiptTempWrite = true; + for (const arg of ["--s5", "--s6", "--s7"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + } + failReceiptTempWrite = false; + const lockTimeoutCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* fileSystem.writeFileString(edgeSyncSidecarLockPath, "external-holder"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c"], + }); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + let nextLockStat = yield* Deferred.make(); + onStatPath = { + matchPath: edgeSyncSidecarLockPath, + onHit: () => { + Deferred.doneUnsafe(nextLockStat, Exit.void); + }, + }; + const lockTimeoutFiber = yield* lockTimeoutCat + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + for (let step = 0; step < 20; step += 1) { + yield* Deferred.await(nextLockStat); + nextLockStat = yield* Deferred.make(); + yield* TestClock.adjust("100 millis"); + } + onStatPath = null; + yield* Fiber.join(lockTimeoutFiber); + yield* fileSystem.remove(edgeSyncSidecarLockPath, { force: true }); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c", + ]); // 3. A superseded primary executable that lost execute permission must not fail inspect() // when the registry selects a different same-version artifact. diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 85484f94957e2..9703a70f5f403 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1164,8 +1164,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // True after an incomplete tools-directory scan or disk-index read error during baseline // discovery; requires positive baseline provenance before reusing unreceipted legacy installs. let legacyBaselineDiscoveryIncomplete = false; - // In-memory mirror of last-resolved binary launch options when updating .t3-artifact.json fails. - const syncedLaunchOptionsBySlotRoot = new Map(); + // In-memory mirror of uncommitted binary launch options when durable writes fail or cannot read + // the sidecar; tracked separately from committed revisions so failed writes never outrank later + // durable updates from another catalog. + const pendingLaunchOptionsBySlotRoot = new Map< + string, + { + readonly baseDurableRevision: number; + readonly receipt: AcpRegistryBinaryArtifactReceipt; + } + >(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -2733,14 +2741,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const hasSidecar = yield* fileSystem .exists(binaryLaunchOptionsPath) .pipe(Effect.orElseSucceed(() => false)); - const memoryEntry = syncedLaunchOptionsBySlotRoot.get(slot.root); - const memoryStored = receiptMatchesInstall(memoryEntry, initialReceipt) - ? memoryEntry - : undefined; + const pendingEntry = pendingLaunchOptionsBySlotRoot.get(slot.root); + const hasMatchingPending = + pendingEntry !== undefined && receiptMatchesInstall(pendingEntry.receipt, initialReceipt); const receiptRev = initialReceipt.launchOptionsRevision ?? 0; - const memoryRev = memoryStored?.launchOptionsRevision ?? 0; + let observedDiskRev = 0; if (!hasSidecar) { - if (receiptMatchesLaunchOptions(initialReceipt, target) && memoryRev <= receiptRev) { + if (!hasMatchingPending && receiptMatchesLaunchOptions(initialReceipt, target)) { return; } } else { @@ -2748,15 +2755,14 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (diskResult.status === "ok") { const diskStored = diskResult.entries[slot.root]; const diskMatches = receiptMatchesInstall(diskStored, initialReceipt); - const diskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; - const durableRev = Math.max(receiptRev, diskRev); - if (memoryRev <= durableRev) { + observedDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + if (!hasMatchingPending) { if (diskStored === undefined && receiptMatchesLaunchOptions(initialReceipt, target)) { return; } if ( diskMatches && - diskRev > receiptRev && + observedDiskRev > receiptRev && receiptMatchesLaunchOptions(diskStored, target) ) { return; @@ -2766,9 +2772,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); - const buildUpdatedReceipt = ( + const buildLaunchOptionsReceipt = ( baseReceipt: AcpRegistryBinaryArtifactReceipt, - revision: number, + revision?: number, ): AcpRegistryBinaryArtifactReceipt => ({ version: agent.version, archive: target.archive, @@ -2776,9 +2782,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct sha256: target.sha256 ?? null, ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), - launchOptionsRevision: revision, + ...(revision !== undefined ? { launchOptionsRevision: revision } : {}), ...(baseReceipt.installId !== undefined ? { installId: baseReceipt.installId } : {}), }); + const recordPending = ( + baseReceipt: AcpRegistryBinaryArtifactReceipt, + baseDurableRevision: number, + ) => { + pendingLaunchOptionsBySlotRoot.set(slot.root, { + baseDurableRevision, + receipt: buildLaunchOptionsReceipt(baseReceipt), + }); + }; yield* withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { const rawFreshReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); @@ -2787,6 +2802,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Option.isNone(decodedFreshReceipt) || !receiptMatchesInstall(decodedFreshReceipt.value, initialReceipt) ) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } const freshReceipt = decodedFreshReceipt.value; @@ -2795,9 +2811,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct fileSystem, binaryLaunchOptionsPath, ); + if (diskResult.status === "io_error") { + // Do not rewrite a matching receipt or allocate a revision below an unreadable sidecar; + // keep launch usable via pending options and retry once sidecar reads recover. + if (receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending(freshReceipt, Math.max(freshReceiptRev, observedDiskRev)); + } + return; + } const isCorrupt = diskResult.status === "corrupt"; - const diskEntries = diskResult.status === "ok" ? diskResult.entries : {}; - const diskStored = diskResult.status === "ok" ? diskEntries[slot.root] : undefined; + const diskEntries = isCorrupt ? {} : diskResult.entries; + const diskStored = diskEntries[slot.root]; const diskMatches = receiptMatchesInstall(diskStored, freshReceipt); const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; if (receiptMatchesLaunchOptions(freshReceipt, target)) { @@ -2807,40 +2833,36 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) .pipe(Effect.ignore); yield* writeJsonFileAtomically(binaryLaunchOptionsPath, {}).pipe(Effect.ignore); - syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); + pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } - if (diskResult.status === "ok") { - if (diskStored === undefined) { - syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); - return; - } - if (!diskMatches || freshDiskRev <= freshReceiptRev) { - if (!(yield* isLockOwned)) return; - const { [slot.root]: _removed, ...rest } = diskEntries; - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); - syncedLaunchOptionsBySlotRoot.set(slot.root, freshReceipt); - return; - } + if (diskStored === undefined) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; + } + if (freshDiskRev <= freshReceiptRev) { + if (!(yield* isLockOwned)) return; + const { [slot.root]: _removed, ...rest } = diskEntries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; } } if ( - diskResult.status === "ok" && diskMatches && freshDiskRev > freshReceiptRev && receiptMatchesLaunchOptions(diskStored, target) ) { - syncedLaunchOptionsBySlotRoot.set(slot.root, diskStored); + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; + } + const committedBaseRev = Math.max(freshReceiptRev, freshDiskRev); + const nextRevision = committedBaseRev + 1; + const updatedReceipt = buildLaunchOptionsReceipt(freshReceipt, nextRevision); + if (!(yield* isLockOwned)) { + recordPending(freshReceipt, committedBaseRev); return; } - const rawMemory = syncedLaunchOptionsBySlotRoot.get(slot.root); - const freshMemoryRev = receiptMatchesInstall(rawMemory, freshReceipt) - ? (rawMemory.launchOptionsRevision ?? 0) - : 0; - const nextRevision = Math.max(freshReceiptRev, freshDiskRev, freshMemoryRev) + 1; - const updatedReceipt = buildUpdatedReceipt(freshReceipt, nextRevision); - syncedLaunchOptionsBySlotRoot.set(slot.root, updatedReceipt); - if (!(yield* isLockOwned)) return; const receiptWrite = yield* Effect.result( random.uuidV4().pipe( Effect.flatMap((id) => { @@ -2865,7 +2887,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); if (Result.isSuccess(receiptWrite)) { - if (isCorrupt || (diskResult.status === "ok" && diskStored !== undefined)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + if (isCorrupt || diskStored !== undefined) { if (!(yield* isLockOwned)) return; if (isCorrupt) { yield* fileSystem @@ -2880,25 +2903,31 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // If updating the receipt inside tools/ failed (e.g., read-only install directory or file // lock), persist the updated launch options in registry cache storage so fallback still // restores the last-resolved args and env even across restarts. - if (diskResult.status === "io_error") return; - if (!(yield* isLockOwned)) return; + if (!(yield* isLockOwned)) { + recordPending(freshReceipt, committedBaseRev); + return; + } if (isCorrupt) { yield* fileSystem .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) .pipe(Effect.ignore); } - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, { - ...diskEntries, - [slot.root]: updatedReceipt, - }).pipe(Effect.ignore); + const sidecarWrite = yield* Effect.result( + writeJsonFileAtomically(binaryLaunchOptionsPath, { + ...diskEntries, + [slot.root]: updatedReceipt, + }), + ); + if (Result.isSuccess(sidecarWrite)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending(freshReceipt, committedBaseRev); + } }), ).pipe( Effect.catch(() => Effect.sync(() => { - syncedLaunchOptionsBySlotRoot.set( - slot.root, - buildUpdatedReceipt(initialReceipt, Math.max(receiptRev, memoryRev) + 1), - ); + recordPending(initialReceipt, Math.max(receiptRev, observedDiskRev)); }), ), ); @@ -3607,19 +3636,20 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.option, ); if (Option.isNone(validated)) continue; - const memoryOverride = syncedLaunchOptionsBySlotRoot.get(dir); const diskOverride = diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; - let effectiveReceipt = receipt; - for (const candidate of [diskOverride, memoryOverride]) { - if ( - receiptMatchesInstall(candidate, receipt) && - (candidate.launchOptionsRevision ?? 0) > - (effectiveReceipt.launchOptionsRevision ?? 0) - ) { - effectiveReceipt = candidate; - } - } + const durableReceipt = + receiptMatchesInstall(diskOverride, receipt) && + (diskOverride.launchOptionsRevision ?? 0) > (receipt.launchOptionsRevision ?? 0) + ? diskOverride + : receipt; + const pendingOverride = pendingLaunchOptionsBySlotRoot.get(dir); + const effectiveReceipt = + pendingOverride !== undefined && + receiptMatchesInstall(pendingOverride.receipt, receipt) && + (durableReceipt.launchOptionsRevision ?? 0) <= pendingOverride.baseDurableRevision + ? pendingOverride.receipt + : durableReceipt; const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); const fallbackArgs = effectiveReceipt.args ?? []; const fallbackEnv = effectiveReceipt.env ?? {}; @@ -3938,9 +3968,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } } const agentRootPrefix = `${agentRoot}${path.sep}`; - for (const slotRoot of syncedLaunchOptionsBySlotRoot.keys()) { + for (const slotRoot of pendingLaunchOptionsBySlotRoot.keys()) { if (slotRoot === agentRoot || slotRoot.startsWith(agentRootPrefix)) { - syncedLaunchOptionsBySlotRoot.delete(slotRoot); + pendingLaunchOptionsBySlotRoot.delete(slotRoot); } } // Finish durable metadata cleanup before releasing the agent permit so a concurrent diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index b87492f5e1d2f..1e185bddd393d 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -8,6 +8,7 @@ import { import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { toCustomModelSetting } from "@t3tools/shared/model"; @@ -30,6 +31,7 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as Tracer from "effect/Tracer"; +import * as AcpRegistryAuthenticationState from "./authenticationState.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import { @@ -3623,6 +3625,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { let failProbeExit = false; let probeResolveCount = 0; let defectInspectCount = 0; + let interruptInspectOnce = false; let inspectCalls = 0; let onRefreshIndex: (() => Effect.Effect) | null = null; let onBeforeProbeResolve: (() => Effect.Effect) | null = null; @@ -3741,6 +3744,16 @@ createInterface({ input: process.stdin }).on("line", (line) => { inspect: (settings, environment) => Effect.gen(function* () { inspectCalls += 1; + if (interruptInspectOnce) { + interruptInspectOnce = false; + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + return yield* Effect.interrupt; + } if (defectInspectCount > 0) { defectInspectCount -= 1; if (inspectGate !== null) { @@ -4078,7 +4091,8 @@ createInterface({ input: process.stdin }).on("line", (line) => { const fallbackExitSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; expect(fallbackExitSnapshot.version).toBe("1.0.0"); expect(fallbackExitSnapshot.status).toBe("warning"); - expect(fallbackExitSnapshot.auth.status).toBe("unknown"); + // Retains step (b)'s auth rejection rather than clearing it on a startup crash. + expect(fallbackExitSnapshot.auth.status).toBe("unauthenticated"); expect(fallbackExitSnapshot.message).toBeDefined(); expect(fallbackExitSnapshot.message).not.toContain("API key"); const exitLiveUpdated = yield* fgConfigInstance.snapshot.streamChanges.pipe( @@ -4102,6 +4116,88 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(exitWithE.message).toBeDefined(); expect(exitWithE.message).not.toContain("API key"); failProbeExit = false; + + // (e) Non-upgrade same-runtime auth failure clears failedUpgradeTarget and preserves + // warning + unauthenticated + sign-in message across live config updates via + // preserveUnauthenticated (without failedUpgradeTarget or activeFallback). + failArchiveVersions = new Set(); + remoteVersion = "1.0.0"; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const directUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(directUnauthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(directUnauthDone); + const directUnauthLive = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-f")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-f", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-f", name: "fg-v1-f" }, + ], + }), + v1Identity, + ); + const directUnauthWithF = Option.getOrThrow(yield* Fiber.join(directUnauthLive)); + expect(directUnauthWithF.status).toBe("warning"); + expect(directUnauthWithF.auth.status).toBe("unauthenticated"); + expect(directUnauthWithF.message).toContain("API key"); + + // (f) After a successful fallback sets activeFallback, a subsequent auth rejection on the + // fallback runtime preserves the auth warning across live config updates (taking + // precedence over activeFallback's install notice) and clears activeFallback so + // subsequent refreshes don't mask it behind backoff. + failProbeAuth = false; + remoteVersion = "2.0.0"; + failArchiveVersions = new Set(["2.0.0"]); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const activeFbReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbReadyDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbReadyDone); + expect((yield* fgConfigInstance.snapshot.getSnapshot).status).toBe("ready"); + expect((yield* fgConfigInstance.snapshot.getSnapshot).message).toContain("2.0.0"); + yield* TestClock.adjust("61 seconds"); + failProbeAuth = true; + const activeFbUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbUnauthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbUnauthDone); + const activeFbUnauthLive = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-g")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-g", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-g", name: "fg-v1-g" }, + ], + }), + v1Identity, + ); + const activeFbWithG = Option.getOrThrow(yield* Fiber.join(activeFbUnauthLive)); + expect(activeFbWithG.status).toBe("warning"); + expect(activeFbWithG.auth.status).toBe("unauthenticated"); + expect(activeFbWithG.message).toContain("API key"); + failProbeAuth = false; failArchiveVersions = new Set(); remoteVersion = "2.0.0"; yield* realCatalog.invalidateIndex(); @@ -4124,7 +4220,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.await(fgSwitchedDone); expect(fgSwitchedSnapshot.version).toBe("1.0.0"); expect(fgSwitchedSnapshot.message).not.toContain("API key"); - expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-e"); + expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-g"); // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed // 2.0.0 probe discovered via recheck (with expectedRuntimeIdentity still on 1.0.0!) publishes @@ -4519,35 +4615,17 @@ createInterface({ input: process.stdin }).on("line", (line) => { controlledDispatcher.flush(); expect(inspectCalls).toBe(inspectsBeforeNoPending + 1); - const interruptScope = yield* Scope.make(); - const interruptId = ProviderInstanceId.make("acpRegistry_interrupt_reconcile"); - const interruptStartupDone = yield* Deferred.make(); - onEnrichmentEnd = () => Deferred.doneUnsafe(interruptStartupDone, Exit.void); - yield* AcpRegistryDriver.create({ - instanceId: interruptId, - displayName: "Interrupt Reconcile", - enabled: true, - environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], - config: decodeSettings({ agentId: "test-agent" }), - }).pipe( - Scope.provide(interruptScope), - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.provideService( - AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, - coordinator, - ), - Effect.provideService(Tracer.Tracer, enrichmentTracer), - Effect.provideService(Scheduler.Scheduler, controlledScheduler), - ); - yield* Deferred.await(interruptStartupDone); + // Interruption of a reconciliation fiber while driverScope is still OPEN (with a parked + // event) must NOT replay (!Cause.hasInterruptsOnly). const interruptGate = { started: yield* Deferred.make(), release: yield* Deferred.make(), }; inspectGate = interruptGate; + interruptInspectOnce = true; const inspectsBeforeInterrupt = inspectCalls; yield* coordinator.publishAvailableCommands( - interruptId, + fallbackRetireId, { slashCommands: [{ name: "v2-interrupt-1" }], skills: [] }, v2Identity, ); @@ -4555,14 +4633,160 @@ createInterface({ input: process.stdin }).on("line", (line) => { const interruptParked = yield* Deferred.make(); onCommandHandled = { matchName: "v2-interrupt-2", done: interruptParked }; yield* coordinator.publishAvailableCommands( - interruptId, + fallbackRetireId, { slashCommands: [{ name: "v2-interrupt-2" }], skills: [] }, v2Identity, ); yield* Deferred.await(interruptParked); - yield* Scope.close(interruptScope, Exit.void); + const interruptSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(interruptSpanDone, Exit.void); + yield* Deferred.succeed(interruptGate.release, undefined); + yield* Deferred.await(interruptSpanDone); controlledDispatcher.flush(); expect(inspectCalls).toBe(inspectsBeforeInterrupt + 1); + + // 5. Saved sign-in confirmation: first-probe auth rejection clears it without + // lastSuccessfulRuntime, rejected publications keep it, and a later failure on B + // never restores confirmation after A rejected auth. + const host = yield* ProviderHost.ProviderHost; + const authConfirmId = ProviderInstanceId.make("acpRegistry_confirmed_auth_edge"); + const authConfirmEnv = [{ name: "MISE_OFFLINE", value: "0", sensitive: false }] as const; + const authConfirmSettings = decodeSettings({ agentId: "test-agent" }); + const seedConfirmedAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: authConfirmId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + remoteVersion = "1.0.0"; + failProbeSpawn = false; + failProbeExit = false; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* (yield* seedConfirmedAuth()).set(true); + const firstRejectScope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(firstRejectScope, Exit.void)); + const firstRejectStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(firstRejectStartupDone, Exit.void); + const firstRejectInstance = yield* AcpRegistryDriver.create({ + instanceId: authConfirmId, + displayName: "Confirmed Auth Edge", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Scope.provide(firstRejectScope), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(firstRejectStartupDone); + expect((yield* firstRejectInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); + yield* Scope.close(firstRejectScope, Exit.void); + + // (b) & (c): Re-seed saved confirmation, verify stale rejected publication leaves it intact, + // verify B's auth failure preserves A's authenticated state, then A's own auth + // rejection clears it and a later B failure never restores old confirmation. + yield* (yield* seedConfirmedAuth()).set(true); + failProbeAuth = false; + const authRetainStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(authRetainStartupDone, Exit.void); + const authRetainInstance = yield* AcpRegistryDriver.create({ + instanceId: authConfirmId, + displayName: "Confirmed Auth Retain", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(authRetainStartupDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // Start a probe of 1.0.0 that will fail auth, pause it at resolveGate, supersede it with + // a newer refresh (succeeding auth), then release the stale probe -> saved confirmation stays true. + yield* authRetainInstance.invalidateCaches ?? Effect.void; + const staleUnauthGate = { + matchVersion: "1.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = staleUnauthGate; + failProbeAuth = true; + yield* authRetainInstance.snapshot.refresh; + yield* Deferred.await(staleUnauthGate.started); + failProbeAuth = false; + const supersedingRefreshDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(supersedingRefreshDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(supersedingRefreshDone); + yield* Deferred.succeed(staleUnauthGate.release, undefined); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(true); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // B fails auth -> retained A keeps authenticated. + remoteVersion = "2.0.0"; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bFailKeepAuthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(bFailKeepAuthDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(bFailKeepAuthDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // Now A itself rejects auth (after 15m probe cache TTL expires) -> A becomes + // unauthenticated and clears saved confirmation. + yield* TestClock.adjust("16 minutes"); + remoteVersion = "1.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const aRejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(aRejectDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(aRejectDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); + + // Now B fails without launching A -> retained A MUST stay unauthenticated (never restoring + // A's old authenticated state from lastSuccessfulRuntime). + remoteVersion = "2.0.0"; + failProbeAuth = false; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bFailAfterARejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(bFailAfterARejectDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(bFailAfterARejectDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).version).toBe("1.0.0"); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index d53c51ec60496..d0c8133af2035 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1013,6 +1013,12 @@ export const AcpRegistryDriver: ProviderDriver(null); + // Tracks the latest accepted auth result per runtime separately from lastSuccessfulRuntime + // capabilities so a failure on B neither clears A's confirmation nor restores lost confirmation. + const latestAcceptedAuth = yield* Ref.make<{ + readonly identity: string; + readonly auth: ServerProvider["auth"]; + } | null>(null); const failedUpgradeTarget = yield* Ref.make(null); const clearLiveState = ( options?: AcpRegistryRuntimeCoordinator.AcpRegistryClearLiveStateOptions, @@ -1030,9 +1036,14 @@ export const AcpRegistryDriver: ProviderDriver + current !== null && current.identity === options.preserveRuntimeIdentity + ? current + : null, + ), ), ); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( @@ -1043,10 +1054,16 @@ export const AcpRegistryDriver: ProviderDriver { - const withLocalVersion = - snapshot.installed && snapshot.version === null && version !== null - ? { ...snapshot, version } - : snapshot; - if ( - options?.preserveActiveFallback === true && - fallbackState !== null && - withLocalVersion.installed && - launchIdentity !== null && - launchIdentity === fallbackState.targetLaunchIdentity - ) { - const preservedBase = + Effect.map( + ({ + version, + fallbackState, + failedUpgrade, + lastRuntime, + acceptedAuth, + activeIdentity, + }) => { + const withLocalVersion = + snapshot.installed && snapshot.version === null && version !== null + ? { ...snapshot, version } + : snapshot; + if ( + options?.preserveActiveFallback === true && + fallbackState !== null && + withLocalVersion.installed && + launchIdentity !== null && + launchIdentity === fallbackState.targetLaunchIdentity + ) { + const preservedBase = + lastRuntime !== null && + fallbackState.fallbackLaunchIdentity !== null && + lastRuntime.identity === fallbackState.fallbackLaunchIdentity + ? applyRegistryReadinessMetadata(lastRuntime.provider, withLocalVersion) + : withLocalVersion; + return { + snapshot: { + ...preservedBase, + checkedAt: withLocalVersion.checkedAt, + installed: true, + version: fallbackState.fallbackVersion, + status: withLocalVersion.enabled ? ("ready" as const) : ("disabled" as const), + }, + launchIdentity: fallbackState.fallbackLaunchIdentity, + indexRevision, + fallback: true as const, + fallbackTargetIndexRevision: fallbackState.targetIndexRevision, + retryFailedUpgrade: false as const, + preserveStatus: undefined as ServerProvider["status"] | undefined, + preserveMessage: fallbackState.message as string | undefined, + }; + } + if ( + options?.preserveActiveFallback === true && + failedUpgrade !== null && lastRuntime !== null && - fallbackState.fallbackLaunchIdentity !== null && - lastRuntime.identity === fallbackState.fallbackLaunchIdentity - ? applyRegistryReadinessMetadata(lastRuntime.provider, withLocalVersion) - : withLocalVersion; - return { - snapshot: { - ...preservedBase, - checkedAt: withLocalVersion.checkedAt, - installed: true, - version: fallbackState.fallbackVersion, - status: withLocalVersion.enabled ? ("ready" as const) : ("disabled" as const), - }, - launchIdentity: fallbackState.fallbackLaunchIdentity, - indexRevision, - fallback: true as const, - fallbackTargetIndexRevision: fallbackState.targetIndexRevision, - retryFailedUpgrade: false as const, - preserveStatus: undefined as ServerProvider["status"] | undefined, - preserveMessage: fallbackState.message as string | undefined, - }; - } - if ( - options?.preserveActiveFallback === true && - failedUpgrade !== null && - lastRuntime !== null && - activeIdentity !== null && - lastRuntime.identity === activeIdentity && - withLocalVersion.installed && - launchIdentity !== null && - launchIdentity === failedUpgrade.targetLaunchIdentity - ) { - const { message: _previousMessage, ...lastProviderWithoutMessage } = - lastRuntime.provider; + activeIdentity !== null && + lastRuntime.identity === activeIdentity && + withLocalVersion.installed && + launchIdentity !== null && + launchIdentity === failedUpgrade.targetLaunchIdentity + ) { + const { message: _previousMessage, ...lastProviderWithoutMessage } = + lastRuntime.provider; + const preservedAuth = + acceptedAuth !== null && acceptedAuth.identity === lastRuntime.identity + ? acceptedAuth.auth + : lastProviderWithoutMessage.auth; + return { + snapshot: { + ...lastProviderWithoutMessage, + auth: preservedAuth, + checkedAt: withLocalVersion.checkedAt, + installed: true, + status: withLocalVersion.enabled + ? failedUpgrade.status + : ("disabled" as const), + ...(failedUpgrade.message !== undefined + ? { message: failedUpgrade.message } + : {}), + }, + launchIdentity: lastRuntime.identity, + indexRevision, + fallback: false as const, + fallbackTargetIndexRevision: null as number | null, + retryFailedUpgrade: true as const, + preserveStatus: (withLocalVersion.enabled + ? failedUpgrade.status + : "disabled") as ServerProvider["status"] | undefined, + preserveMessage: failedUpgrade.message, + }; + } return { - snapshot: { - ...lastProviderWithoutMessage, - checkedAt: withLocalVersion.checkedAt, - installed: true, - status: withLocalVersion.enabled ? failedUpgrade.status : ("disabled" as const), - ...(failedUpgrade.message !== undefined - ? { message: failedUpgrade.message } - : {}), - }, - launchIdentity: lastRuntime.identity, + snapshot: withLocalVersion, + launchIdentity, indexRevision, fallback: false as const, fallbackTargetIndexRevision: null as number | null, - retryFailedUpgrade: true as const, - preserveStatus: (withLocalVersion.enabled ? failedUpgrade.status : "disabled") as - | ServerProvider["status"] - | undefined, - preserveMessage: failedUpgrade.message, + retryFailedUpgrade: false as const, + preserveStatus: undefined as ServerProvider["status"] | undefined, + preserveMessage: undefined as string | undefined, }; - } - return { - snapshot: withLocalVersion, - launchIdentity, - indexRevision, - fallback: false as const, - fallbackTargetIndexRevision: null as number | null, - retryFailedUpgrade: false as const, - preserveStatus: undefined as ServerProvider["status"] | undefined, - preserveMessage: undefined as string | undefined, - }; - }), + }, + ), ), ), Effect.flatMap( @@ -1720,15 +1754,18 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), + Effect.tap(() => Ref.set(latestAcceptedAuth, null)), Effect.tap(() => liveSnapshotSemaphore.withPermit( invalidateEnrichmentCache.pipe( From 52ce3d0f9d73c975a6f62f02e7bbf9cc6c3e6221 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 20:19:36 +0000 Subject: [PATCH 22/28] fix(acp-registry): harden logout auth retention, cache invalidation, and pending launch-option retries --- .../src/server/AcpRegistrySupport.test.ts | 294 ++++++++++++++-- .../src/server/AcpRegistrySupport.ts | 65 +++- .../src/server/driver.test.ts | 322 +++++++++++++++++- .../src/server/driver.ts | 123 +++++-- 4 files changed, 728 insertions(+), 76 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index b3fcb46389741..3b065c894707c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -4509,9 +4509,8 @@ describe("AcpRegistrySupport", () => { expect(yield* fileSystem.readFileString(resolvedDirectDiskSentinel.spawn.command)).toBe( "#!/bin/sh\necho archive-a\n", ); - // Now refresh from 1.0.0 archiveA -> 1.0.0 archiveB while 2.0.0 stays unreceipted: - // recordDivergingInMemory must record "unknown" (not archiveA) for 2.0.0, and direct - // resolve of 2.0.0 hits the in-memory \0* check. + // Refreshing 1.0.0 -> 2.0.0 while 2.0.0 stays unreceipted persists a slot-specific + // "unknown" baseline for 2.0.0 instead of attributing it to archiveA. extraUpstreamAgents = [ { ...binaryAgent("2.0.0", archiveBUrl), id: "removed-unreadable-agent" }, ]; @@ -4523,12 +4522,55 @@ describe("AcpRegistrySupport", () => { expect(baselinesAfterDiverge["removed-unreadable-agent\u00002.0.0\u0000linux-x86_64"]).toBe( "unknown", ); + const resolvedSlotSentinel = yield* directDiskSentinelCatalog.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedSlotSentinel.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + // Resolve an unreceipted 3.0.0 legacy slot absent during the scan with the on-disk \0* + // sentinel removed so ONLY the cached in-memory \0* sentinel can reject legacy reuse. + extraUpstreamAgents = [ + { ...binaryAgent("3.0.0", archiveCUrl), id: "removed-unreadable-agent" }, + ]; + yield* directDiskSentinelCatalog.invalidateIndex(); + yield* directDiskSentinelCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const baselinesBeforeV3 = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect( + baselinesBeforeV3["removed-unreadable-agent\u00003.0.0\u0000linux-x86_64"], + ).toBeUndefined(); + const { + ["removed-unreadable-agent\u0000*"]: _droppedDiskSentinel, + ...baselinesWithoutAgentSentinel + } = baselinesBeforeV3; + yield* fileSystem.writeFileString( + corruptBaselinesPath, + JSON.stringify(baselinesWithoutAgentSentinel), + ); + const corruptUnreadableV3Exe = path.join( + corruptUnreadableRemovedDir, + "3.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableV3Exe), { recursive: true }); + yield* fileSystem.writeFileString(corruptUnreadableV3Exe, "#!/bin/sh\necho legacy-v3\n"); + yield* fileSystem.chmod(corruptUnreadableV3Exe, 0o755); const resolvedMemorySentinel = yield* directDiskSentinelCatalog.resolve( settings({ agentId: "removed-unreadable-agent" }), "/workspace", ); expect(yield* fileSystem.readFileString(resolvedMemorySentinel.spawn.command)).toBe( - "#!/bin/sh\necho archive-b\n", + "#!/bin/sh\necho archive-c\n", + ); + // Restore the on-disk \0* sentinel to confirm uninstallManagedBinary prunes both keys. + yield* fileSystem.writeFileString( + corruptBaselinesPath, + JSON.stringify(baselinesAfterDiverge), ); expect( yield* directDiskSentinelCatalog.uninstallManagedBinary({ @@ -5070,6 +5112,10 @@ describe("AcpRegistrySupport", () => { let failReceiptTempWrite = false; let failSidecarWrite = false; let failSidecarRead = false; + let failSidecarReadOnCount: number | null = null; + let sidecarReadCount = 0; + let failReceiptReadOnCount: number | null = null; + let receiptReadCount = 0; let receiptRenameCount = 0; let onStatPath: { readonly matchPath: string; @@ -5097,10 +5143,22 @@ describe("AcpRegistrySupport", () => { : { ...info, mode: (info.mode & ~0o777) | override }; }), ), - readFileString: (filePath, encoding) => - failSidecarRead && path.basename(filePath) === "binary-launch-options.json" - ? fileSystem.readFileString(path.dirname(filePath), encoding) - : fileSystem.readFileString(filePath, encoding), + readFileString: (filePath, encoding) => { + const base = path.basename(filePath); + if (base === "binary-launch-options.json") { + sidecarReadCount += 1; + if (failSidecarRead || failSidecarReadOnCount === sidecarReadCount) { + return fileSystem.readFileString(path.dirname(filePath), encoding); + } + } + if (base === ".t3-artifact.json") { + receiptReadCount += 1; + if (failReceiptReadOnCount === receiptReadCount) { + return fileSystem.readFileString(path.dirname(filePath), encoding); + } + } + return fileSystem.readFileString(filePath, encoding); + }, writeFileString: (filePath, data, options) => (failReceiptTempWrite && path.basename(filePath).startsWith(".t3-artifact.json.")) || (failSidecarWrite && @@ -5962,11 +6020,16 @@ describe("AcpRegistrySupport", () => { const releaseUninstallBeforeLock = yield* Deferred.make(); let gateUninstallExists = true; let reinstallEnteredInstall = false; + const markReinstallToolsTouch = (filePath: string) => { + if (!gateUninstallExists && filePath.startsWith(coordToolsDir)) { + reinstallEnteredInstall = true; + } + }; const coordUninstallFs: FileSystem.FileSystem = { ...posixModeFs, exists: (filePath) => { // Pause uninstall BEFORE it takes the sidecar lock so an early permit release would - // let reinstall run all the way through install + sidecar write while paused. + // let reinstall enter installBinary while cleanup is paused. if (gateUninstallExists && filePath === coordSidecarPath) { gateUninstallExists = false; return Deferred.succeed(uninstallBeforeLockStarted, undefined).pipe( @@ -5974,14 +6037,25 @@ describe("AcpRegistrySupport", () => { Effect.andThen(posixModeFs.exists(filePath)), ); } + markReinstallToolsTouch(filePath); return posixModeFs.exists(filePath); }, + readFileString: (filePath, encoding) => + Effect.sync(() => markReinstallToolsTouch(filePath)).pipe( + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ), + readDirectory: (dirPath, options) => + Effect.sync(() => markReinstallToolsTouch(dirPath)).pipe( + Effect.andThen(posixModeFs.readDirectory(dirPath, options)), + ), + stat: (filePath) => + Effect.sync(() => markReinstallToolsTouch(filePath)).pipe( + Effect.andThen(posixModeFs.stat(filePath)), + ), makeDirectory: (dirPath, options) => - Effect.sync(() => { - if (!gateUninstallExists && dirPath.startsWith(coordToolsDir)) { - reinstallEnteredInstall = true; - } - }).pipe(Effect.andThen(posixModeFs.makeDirectory(dirPath, options))), + Effect.sync(() => markReinstallToolsTouch(dirPath)).pipe( + Effect.andThen(posixModeFs.makeDirectory(dirPath, options)), + ), }; const uninstallSchedulerDispatcher = new Scheduler.MixedScheduler("async").makeDispatcher(); const uninstallScheduler: Scheduler.Scheduler = { @@ -6090,7 +6164,26 @@ describe("AcpRegistrySupport", () => { yield* edgeCatB.resolve(settings(), "/workspace"); yield* edgeCatB.resolve(settings(), "/workspace"); expect(receiptRenameCount).toBe(0); - // 2) Different target + sidecar io_error must NOT allocate rev 1 below unreadable sidecar rev 2. + // 1b) Reverting to matching receipt (--edge-init rev 0) after observing newer sidecar rev 2 + // on the fast path, then hitting io_error on the locked read, keeps --edge-init pending. + failSidecarRead = false; + sidecarReadCount = 0; + failSidecarReadOnCount = 2; + yield* edgeCatB.resolve(settings(), "/workspace"); + failSidecarReadOnCount = null; + expect(receiptRenameCount).toBe(0); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatB.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-init", + ]); + // 2) Different target + sidecar io_error does not allocate below sidecar rev 2 and keeps + // launch usable via pending options while the sidecar is STILL unreadable. + failSidecarRead = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -6100,8 +6193,24 @@ describe("AcpRegistrySupport", () => { yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* edgeCatB.resolve(settings(), "/workspace"); expect(receiptRenameCount).toBe(0); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatB.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-after-io", + ]); // Once reads recover, retrying the same target allocates rev 3 (> sidecar rev 2) cleanly. failSidecarRead = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-after-io"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* edgeCatB.resolve(settings(), "/workspace"); expect(receiptRenameCount).toBe(1); upstream = makeBinary("2.0.0", { @@ -6117,9 +6226,8 @@ describe("AcpRegistrySupport", () => { expect((yield* edgeVerifyAfterIo.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--edge-after-io", ]); - // 3) Repeated failed writes (both receipt & sidecar failing twice) must NOT inflate - // committed revisions: in-process fallback uses pending --fail-2 while disk stays at - // rev 3, and once catalog B commits rev 4 (--commit-b), catalog A's fallback yields --commit-b. + // 3) Repeated failed writes do not inflate committed revisions, and a transient locked + // receipt reread error keeps pending --fail-2 until another catalog commits rev 4. failReceiptTempWrite = true; failSidecarWrite = true; upstream = makeBinary("1.0.0", { @@ -6140,6 +6248,11 @@ describe("AcpRegistrySupport", () => { yield* edgeCatA.resolve(settings(), "/workspace"); failReceiptTempWrite = false; failSidecarWrite = false; + // Transient locked receipt reread failure must preserve pending --fail-2. + receiptReadCount = 0; + failReceiptReadOnCount = 2; + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptReadOnCount = null; // Before catalog B commits a newer rev, edgeCatA's in-process fallback uses pending --fail-2. upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -6168,7 +6281,8 @@ describe("AcpRegistrySupport", () => { expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--commit-b", ]); - // 4) Lock timeout after restart with higher-rev sidecar still preserves pending --lock-c in fallback. + // 4) Lock timeout preserves pending base rev 7; retrying with unreadable sidecars keeps + // base rev 7 so unchanged rev 7 does not override pending, while rev 8 still wins. failReceiptTempWrite = true; for (const arg of ["--s5", "--s6", "--s7"]) { upstream = makeBinary("1.0.0", { @@ -6220,6 +6334,75 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--lock-c", ]); + // Retry with unreadable sidecar keeps baseDurableRevision=7 (not downgraded to receipt rev 4). + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-retry"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-retry", + ]); + // A newer committed rev 8 (--commit-8) still outranks pending base rev 7. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-8", + ]); + // 5) Fast-path hasMatchingPending gating: reverting to matching receipt --commit-8 clears + // earlier pending options instead of short-circuiting and leaving them active. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pending-stale"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-8", + ]); // 3. A superseded primary executable that lost execute permission must not fail inspect() // when the registry selects a different same-version artifact. @@ -6374,9 +6557,12 @@ describe("AcpRegistrySupport", () => { "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", }); - // Sidecar lock-ownership fence: losing the sidecar lock before writing leaves holder-2 intact. + // Sidecar lock-ownership fence: losing the lock leaves holder-2 intact while recording + // pending options in memory, and reverting to the matching receipt clears stale pending + // options even if the prune loses the lock. yield* fileSystem.remove(fenceLockPath, { force: true }); - yield* holder1.resolve(settings(), "/workspace"); + const fenceInstalledB = yield* holder1.resolve(settings(), "/workspace"); + const fenceSlotRoot = path.dirname(path.dirname(fenceInstalledB.spawn.command)); failReceiptTempWrite = true; upstream = makeBinary("1.0.0", { archive: archiveBUrl, @@ -6413,6 +6599,72 @@ describe("AcpRegistrySupport", () => { expect( Object.keys(JSON.parse(yield* fileSystem.readFileString(fenceSidecarPath)) as object), ).toEqual(["keep-slot"]); + // Verify lock-lost resolve recorded pending --fenced-sidecar for in-process fallback. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fenced-sidecar", + ]); + // Reverting to the receipt's no-args target clears stale pending options even on lock loss. + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + yield* fileSystem.writeFileString( + fenceSidecarPath, + JSON.stringify({ + [fenceSlotRoot]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--stale-rev0"], + launchOptionsRevision: 0, + }, + }), + ); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertEntered = yield* Deferred.make(); + const releaseRevert = yield* Deferred.make(); + let revertReadCount = 0; + const origFenceRead = fencedFs.readFileString; + (fencedFs as { readFileString: FileSystem.FileSystem["readFileString"] }).readFileString = ( + filePath, + encoding, + ) => { + if (filePath === fenceSidecarPath) { + revertReadCount += 1; + if (revertReadCount === 2) { + return Deferred.succeed(revertEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseRevert)), + Effect.andThen(origFenceRead(filePath, encoding)), + ); + } + } + return origFenceRead(filePath, encoding); + }; + const fencedRevertResolve = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(revertEntered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-3"); + yield* Deferred.succeed(releaseRevert, undefined); + yield* Fiber.join(fencedRevertResolve); + (fencedFs as { readFileString: FileSystem.FileSystem["readFileString"] }).readFileString = + origFenceRead; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([]); // Uninstall baselines prune lock-ownership fence: losing the lock leaves holder-2 intact. yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 9703a70f5f403..89e368e2a3ec2 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -2744,6 +2744,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const pendingEntry = pendingLaunchOptionsBySlotRoot.get(slot.root); const hasMatchingPending = pendingEntry !== undefined && receiptMatchesInstall(pendingEntry.receipt, initialReceipt); + const initialPriorPendingBase = hasMatchingPending ? pendingEntry.baseDurableRevision : 0; const receiptRev = initialReceipt.launchOptionsRevision ?? 0; let observedDiskRev = 0; if (!hasSidecar) { @@ -2796,8 +2797,30 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }; yield* withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { - const rawFreshReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); - const decodedFreshReceipt = Option.flatMap(rawFreshReceipt, decodeBinaryArtifactReceipt); + const freshReceiptRead = yield* Effect.result(fileSystem.readFileString(receiptPath)); + if (Result.isFailure(freshReceiptRead)) { + if (freshReceiptRead.failure.reason._tag === "NotFound") { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const currentPriorPendingBase = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, initialReceipt) + ? currentPending.baseDurableRevision + : 0; + recordPending( + initialReceipt, + Math.max( + receiptRev, + observedDiskRev, + initialPriorPendingBase, + currentPriorPendingBase, + ), + ); + } + return; + } + const decodedFreshReceipt = decodeBinaryArtifactReceipt(freshReceiptRead.success); if ( Option.isNone(decodedFreshReceipt) || !receiptMatchesInstall(decodedFreshReceipt.value, initialReceipt) @@ -2807,6 +2830,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const freshReceipt = decodedFreshReceipt.value; const freshReceiptRev = freshReceipt.launchOptionsRevision ?? 0; + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const priorPendingBase = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, freshReceipt) + ? currentPending.baseDurableRevision + : 0; + const effectiveObservedBase = Math.max( + freshReceiptRev, + observedDiskRev, + priorPendingBase, + ); const diskResult = yield* readBinaryLaunchOptionsFile( fileSystem, binaryLaunchOptionsPath, @@ -2814,10 +2848,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (diskResult.status === "io_error") { // Do not rewrite a matching receipt or allocate a revision below an unreadable sidecar; // keep launch usable via pending options and retry once sidecar reads recover. - if (receiptMatchesLaunchOptions(freshReceipt, target)) { + if ( + receiptMatchesLaunchOptions(freshReceipt, target) && + effectiveObservedBase <= freshReceiptRev + ) { pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - recordPending(freshReceipt, Math.max(freshReceiptRev, observedDiskRev)); + recordPending(freshReceipt, effectiveObservedBase); } return; } @@ -2828,12 +2865,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; if (receiptMatchesLaunchOptions(freshReceipt, target)) { if (isCorrupt) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); if (!(yield* isLockOwned)) return; yield* fileSystem .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) .pipe(Effect.ignore); yield* writeJsonFileAtomically(binaryLaunchOptionsPath, {}).pipe(Effect.ignore); - pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } if (diskStored === undefined) { @@ -2841,10 +2878,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return; } if (freshDiskRev <= freshReceiptRev) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); if (!(yield* isLockOwned)) return; const { [slot.root]: _removed, ...rest } = diskEntries; yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); - pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } } @@ -2927,7 +2964,21 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ).pipe( Effect.catch(() => Effect.sync(() => { - recordPending(initialReceipt, Math.max(receiptRev, observedDiskRev)); + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const currentPriorPendingBase = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, initialReceipt) + ? currentPending.baseDurableRevision + : 0; + recordPending( + initialReceipt, + Math.max( + receiptRev, + observedDiskRev, + initialPriorPendingBase, + currentPriorPendingBase, + ), + ); }), ), ); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 1e185bddd393d..f00f07aef7734 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3589,7 +3589,15 @@ describe("AcpRegistryDriver registry recovery", () => { ); const authFailAgentPath = path.join(directory, "auth-fail-agent.mjs"); const exitFailAgentPath = path.join(directory, "exit-fail-agent.mjs"); + const logoutAgentPath = path.join(directory, "logout-agent.mjs"); yield* fileSystem.writeFileString(exitFailAgentPath, "process.exit(1);\n"); + yield* fileSystem.writeFileString( + logoutAgentPath, + fakeAgentSource.replace( + "agentCapabilities: {}", + "agentCapabilities: { auth: { logout: {} } }", + ), + ); yield* fileSystem.writeFileString( authFailAgentPath, ` @@ -3623,6 +3631,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { let failProbeSpawn = false; let failProbeAuth = false; let failProbeExit = false; + let useLogoutAgent = false; let probeResolveCount = 0; let defectInspectCount = 0; let interruptInspectOnce = false; @@ -3639,6 +3648,12 @@ createInterface({ input: process.stdin }).on("line", (line) => { readonly started: Deferred.Deferred; readonly release: Deferred.Deferred; } | null = null; + let getAvailableCommandsGate: { + readonly instanceId: ProviderInstanceId; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly interrupted: Deferred.Deferred; + } | null = null; let onCommandHandled: { readonly matchName: string; readonly done: Deferred.Deferred; @@ -3673,6 +3688,26 @@ createInterface({ input: process.stdin }).on("line", (line) => { const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = { ...baseCoordinator, + getAvailableCommands: (instanceId, options) => { + if ( + getAvailableCommandsGate !== null && + getAvailableCommandsGate.instanceId === instanceId + ) { + const gate = getAvailableCommandsGate; + getAvailableCommandsGate = null; + return Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen( + Deferred.await(gate.release).pipe( + Effect.onInterrupt(() => + Deferred.succeed(gate.interrupted, undefined).pipe(Effect.asVoid), + ), + ), + ), + Effect.andThen(baseCoordinator.getAvailableCommands(instanceId, options)), + ); + } + return baseCoordinator.getAvailableCommands(instanceId, options); + }, watchAvailableCommands: (instanceId, onUpdate) => baseCoordinator.watchAvailableCommands(instanceId, (commands, meta) => onUpdate(commands, meta).pipe( @@ -3814,7 +3849,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { ? [exitFailAgentPath] : environment?.MISE_OFFLINE === "1" && failProbeAuth ? [authFailAgentPath] - : [agentPath, modelsPath], + : [useLogoutAgent ? logoutAgentPath : agentPath, modelsPath], }, }; }), @@ -4197,6 +4232,29 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(activeFbWithG.status).toBe("warning"); expect(activeFbWithG.auth.status).toBe("unauthenticated"); expect(activeFbWithG.message).toContain("API key"); + // Follow-up refresh must never mask the rejection behind activeFallback or drop + // latestAcceptedAuth during readiness (every emitted snapshot stays warning/unauthenticated). + const followUpSnapshots: Array = []; + const followUpCollector = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + followUpSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const activeFbFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbFollowUpDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbFollowUpDone); + yield* Fiber.interrupt(followUpCollector); + expect(followUpSnapshots.length).toBeGreaterThan(0); + for (const emitted of followUpSnapshots) { + expect(emitted.status).toBe("warning"); + expect(emitted.auth.status).toBe("unauthenticated"); + } failProbeAuth = false; failArchiveVersions = new Set(); remoteVersion = "2.0.0"; @@ -4643,6 +4701,15 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.succeed(interruptGate.release, undefined); yield* Deferred.await(interruptSpanDone); controlledDispatcher.flush(); + const interruptBarrierHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-interrupt-barrier", done: interruptBarrierHandled }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-interrupt-barrier" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(interruptBarrierHandled); + controlledDispatcher.flush(); expect(inspectCalls).toBe(inspectsBeforeInterrupt + 1); // 5. Saved sign-in confirmation: first-probe auth rejection clears it without @@ -4717,8 +4784,8 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.await(authRetainStartupDone); expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); - // Start a probe of 1.0.0 that will fail auth, pause it at resolveGate, supersede it with - // a newer refresh (succeeding auth), then release the stale probe -> saved confirmation stays true. + // Start a 1.0.0 probe that rejects auth, pause it inside withLiveRuntimeState before + // tryPublishSnapshot, and supersede it with a succeeding refresh -> confirmation stays true. yield* authRetainInstance.invalidateCaches ?? Effect.void; const staleUnauthGate = { matchVersion: "1.0.0", @@ -4729,14 +4796,26 @@ createInterface({ input: process.stdin }).on("line", (line) => { failProbeAuth = true; yield* authRetainInstance.snapshot.refresh; yield* Deferred.await(staleUnauthGate.started); + const staleWithLiveStarted = yield* Deferred.make(); + const staleWithLiveRelease = yield* Deferred.make(); + const staleWithLiveInterrupted = yield* Deferred.make(); + getAvailableCommandsGate = { + instanceId: authConfirmId, + started: staleWithLiveStarted, + release: staleWithLiveRelease, + interrupted: staleWithLiveInterrupted, + }; + yield* Deferred.succeed(staleUnauthGate.release, undefined); + // Wait until authFailAgentPath returned authentication_failed and entered withLiveRuntimeState. + yield* Deferred.await(staleWithLiveStarted); failProbeAuth = false; const supersedingRefreshDone = yield* Deferred.make(); onEnrichmentEnd = () => Deferred.doneUnsafe(supersedingRefreshDone, Exit.void); yield* authRetainInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), ); + yield* Deferred.await(staleWithLiveInterrupted); yield* Deferred.await(supersedingRefreshDone); - yield* Deferred.succeed(staleUnauthGate.release, undefined); expect(yield* (yield* seedConfirmedAuth()).get).toBe(true); expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); @@ -4753,22 +4832,38 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.await(bFailKeepAuthDone); expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); - // Now A itself rejects auth (after 15m probe cache TTL expires) -> A becomes - // unauthenticated and clears saved confirmation. - yield* TestClock.adjust("16 minutes"); + // While A's 15m probe cache entry is still fresh, B's download fails (503) and fallback A + // rejects auth -> invalidates A's cached probe so rolling back to A before TTL expires + // does not serve stale cached unknown auth and erase the rejection. + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "2.0.0"), { + recursive: true, + force: true, + }); + failArchiveVersions = new Set(["2.0.0"]); + const fallbackARejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackARejectDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackARejectDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); remoteVersion = "1.0.0"; + failArchiveVersions = new Set(); yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const aRejectDone = yield* Deferred.make(); - onEnrichmentEnd = () => Deferred.doneUnsafe(aRejectDone, Exit.void); + const rollbackNoCacheDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(rollbackNoCacheDone, Exit.void); yield* authRetainInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), ); - yield* Deferred.await(aRejectDone); + yield* Deferred.await(rollbackNoCacheDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).status).toBe("warning"); expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( "unauthenticated", ); - expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); // Now B fails without launching A -> retained A MUST stay unauthenticated (never restoring // A's old authenticated state from lastSuccessfulRuntime). @@ -4787,6 +4882,211 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( "unauthenticated", ); + + // (d) Logout invalidates confirmed authentication without restoring historical + // "authenticated" from lastSuccessfulRuntime on subsequent non-auth failures. + failProbeSpawn = false; + useLogoutAgent = true; + remoteVersion = "1.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const logoutInstanceId = ProviderInstanceId.make("acpRegistry_logout_edge"); + const seedLogoutAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: logoutInstanceId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* (yield* seedLogoutAuth()).set(true); + const beforeLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(beforeLogoutDone, Exit.void); + const logoutInstance = yield* AcpRegistryDriver.create({ + instanceId: logoutInstanceId, + displayName: "Logout Edge", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(beforeLogoutDone); + expect((yield* logoutInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + expect((yield* logoutInstance.snapshot.getSnapshot).auth.canLogout).toBe(true); + yield* logoutInstance.acpSessionManagement!.logout(directory); + expect(yield* (yield* seedLogoutAuth()).get).toBe(false); + // Same-runtime non-auth failure after logout must show unknown (never authenticated). + failProbeSpawn = true; + const afterLogoutSameFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutSameFailDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutSameFailDone); + expect((yield* logoutInstance.snapshot.getSnapshot).status).toBe("warning"); + expect((yield* logoutInstance.snapshot.getSnapshot).auth.status).toBe("unknown"); + // Failed upgrade to 2.0.0 after logout keeps A's capabilities and stays unknown across + // both retained-runtime publication and follow-up inspectReadiness. + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const afterLogoutUpgradeFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutUpgradeFailDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutUpgradeFailDone); + const afterLogoutUpgradeSnap = yield* logoutInstance.snapshot.getSnapshot; + expect(afterLogoutUpgradeSnap.version).toBe("1.0.0"); + expect(afterLogoutUpgradeSnap.status).toBe("warning"); + expect(afterLogoutUpgradeSnap.auth.status).toBe("unknown"); + expect(afterLogoutUpgradeSnap.models.length).toBeGreaterThan(0); + const afterLogoutSnapshots: Array = []; + const afterLogoutCollector = yield* logoutInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + afterLogoutSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const afterLogoutFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutFollowUpDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutFollowUpDone); + yield* Fiber.interrupt(afterLogoutCollector); + expect(afterLogoutSnapshots.length).toBeGreaterThan(0); + for (const emitted of afterLogoutSnapshots) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + useLogoutAgent = false; + failProbeSpawn = false; + + // (e) Cold-start direct-publish branch clears saved confirmation when fallback runtime + // rejects auth so the next refresh does not flash authenticated. + const coldFallbackAuthId = ProviderInstanceId.make("acpRegistry_cold_fallback_unauth"); + const seedColdFallbackAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: coldFallbackAuthId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "3.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "3.0.0"; + failArchiveVersions = new Set(["3.0.0"]); + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* (yield* seedColdFallbackAuth()).set(true); + const coldFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(coldFallbackDone, Exit.void); + const coldFallbackInstance = yield* AcpRegistryDriver.create({ + instanceId: coldFallbackAuthId, + displayName: "Cold Fallback Unauth", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(coldFallbackDone); + const coldFallbackSnap = yield* coldFallbackInstance.snapshot.getSnapshot; + expect(coldFallbackSnap.version).toBe("2.0.0"); + expect(coldFallbackSnap.status).toBe("warning"); + expect(coldFallbackSnap.auth.status).toBe("unauthenticated"); + expect(yield* (yield* seedColdFallbackAuth()).get).toBe(false); + const coldFollowUpSnaps: Array = []; + const coldFollowUpCollector = yield* coldFallbackInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + coldFollowUpSnaps.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const coldFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(coldFollowUpDone, Exit.void); + yield* coldFallbackInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(coldFollowUpDone); + yield* Fiber.interrupt(coldFollowUpCollector); + expect(coldFollowUpSnaps.length).toBeGreaterThan(0); + for (const emitted of coldFollowUpSnaps) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + + // (f) Local agent (previousIdentity === null, normal branch) clears saved confirmation on auth failure. + const localUnauthId = ProviderInstanceId.make("acpRegistry_local_unauth"); + const localUnauthSettings = decodeSettings({ + source: "local", + commandPath: "local-auth-fail", + }); + const seedLocalAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: localUnauthId, + settings: localUnauthSettings, + environment: [], + processEnvironment: process.env, + }); + yield* (yield* seedLocalAuth()).set(true); + const localUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localUnauthDone, Exit.void); + const localUnauthInstance = yield* AcpRegistryDriver.create({ + instanceId: localUnauthId, + displayName: "Local Unauth", + enabled: true, + environment: [], + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "local-auth-fail", + version: null, + distribution: "local", + }), + resolve: () => + Effect.succeed({ + distribution: "local", + spawn: { + command: process.execPath, + args: [authFailAgentPath], + cwd: directory, + env: process.env, + }, + }), + }), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localUnauthDone); + expect((yield* localUnauthInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedLocalAuth()).get).toBe(false); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index d0c8133af2035..ce044d656f4af 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1009,6 +1009,10 @@ export const AcpRegistryDriver: ProviderDriver(null); + // Probes never produce "authenticated" directly; saved confirmation re-promotes "unknown" + // in withLiveRuntimeState, so stripping it prevents historical auth surviving logout. + const stripConfirmedAuth = (auth: ServerProvider["auth"]): ServerProvider["auth"] => + auth.status === "authenticated" ? { ...auth, status: "unknown" } : auth; const lastSuccessfulRuntime = yield* Ref.make<{ readonly identity: string; readonly provider: ServerProvider; @@ -1180,6 +1184,7 @@ export const AcpRegistryDriver: ProviderDriver + Ref.update(enrichmentCache, (cache) => { + const entryIdentity = + cache.entry === null + ? null + : runtimeIdentityFor(cache.entry.provider, cache.entry.launchIdentity ?? null); + const matchesEntry = + cache.entry !== null && + (effectiveConfig.source === "local" || + (runtimeIdentity !== null && entryIdentity === runtimeIdentity)); + let liveGenerationByRuntime = nextLiveGenerationByRuntime( + cache.liveGenerationByRuntime, + runtimeIdentity, + ); + if (matchesEntry && entryIdentity !== runtimeIdentity) { + liveGenerationByRuntime = nextLiveGenerationByRuntime( + liveGenerationByRuntime, + entryIdentity, + ); + } + return { + ...cache, + liveGenerationByRuntime, + ...(matchesEntry ? { entry: null } : {}), + }; + }); const isProbeStillCurrent = ( current: AcpRegistryEnrichmentCache, captured: { @@ -1755,10 +1787,11 @@ export const AcpRegistryDriver: ProviderDriver - confirmedAuthentication - .set(authenticated) - .pipe( - Effect.andThen(authenticated ? Ref.set(latestAcceptedAuth, null) : clearLiveState()), - Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)), - Effect.andThen(snapshot.refresh), - Effect.asVoid, - ), + liveSnapshotSemaphore + .withPermit( + confirmedAuthentication + .set(authenticated) + .pipe( + Effect.andThen( + authenticated ? Ref.set(latestAcceptedAuth, null) : clearLiveState(), + ), + Effect.andThen(invalidateEnrichmentCache), + ), + ) + .pipe(Effect.andThen(snapshot.refresh), Effect.asVoid), }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -2487,9 +2530,13 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), - Effect.tap(() => Ref.set(latestAcceptedAuth, null)), 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, + confirmedAuthentication + .set(false) + .pipe( + Effect.andThen(Ref.set(latestAcceptedAuth, null)), + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen( + Option.isSome(runtimeCoordinator) + ? Effect.all( + [ + runtimeCoordinator.value.clearAvailableCommands(instanceId), + runtimeCoordinator.value.clearLiveConfiguration(instanceId), + ], + { concurrency: "unbounded", discard: true }, + ) + : Effect.void, + ), ), - ), ), ), ); From 2a9b357257c991c72caba1e2efb461d1c102531a Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 21:06:05 +0000 Subject: [PATCH 23/28] fix(acp-registry): simplify auth rejection handling, preserve pending reverts on io errors, and harden tests --- .../src/server/AcpRegistrySupport.test.ts | 225 +++++++++++++++--- .../src/server/AcpRegistrySupport.ts | 59 ++--- .../src/server/driver.test.ts | 135 ++++++++--- .../src/server/driver.ts | 94 +++----- 4 files changed, 333 insertions(+), 180 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 3b065c894707c..cdaba6a486a5a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -5112,10 +5112,8 @@ describe("AcpRegistrySupport", () => { let failReceiptTempWrite = false; let failSidecarWrite = false; let failSidecarRead = false; - let failSidecarReadOnCount: number | null = null; - let sidecarReadCount = 0; - let failReceiptReadOnCount: number | null = null; - let receiptReadCount = 0; + let failSidecarReadWhileLockedPath: string | null = null; + let failReceiptReadWhileLockedPath: string | null = null; let receiptRenameCount = 0; let onStatPath: { readonly matchPath: string; @@ -5146,17 +5144,32 @@ describe("AcpRegistrySupport", () => { readFileString: (filePath, encoding) => { const base = path.basename(filePath); if (base === "binary-launch-options.json") { - sidecarReadCount += 1; - if (failSidecarRead || failSidecarReadOnCount === sidecarReadCount) { + if (failSidecarRead) { return fileSystem.readFileString(path.dirname(filePath), encoding); } - } - if (base === ".t3-artifact.json") { - receiptReadCount += 1; - if (failReceiptReadOnCount === receiptReadCount) { - return fileSystem.readFileString(path.dirname(filePath), encoding); + if (failSidecarReadWhileLockedPath !== null) { + const lockPath = failSidecarReadWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? fileSystem.readFileString(path.dirname(filePath), encoding) + : fileSystem.readFileString(filePath, encoding), + ), + ); } } + if (base === ".t3-artifact.json" && failReceiptReadWhileLockedPath !== null) { + const lockPath = failReceiptReadWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? fileSystem.readFileString(path.dirname(filePath), encoding) + : fileSystem.readFileString(filePath, encoding), + ), + ); + } return fileSystem.readFileString(filePath, encoding); }, writeFileString: (filePath, data, options) => @@ -6165,12 +6178,11 @@ describe("AcpRegistrySupport", () => { yield* edgeCatB.resolve(settings(), "/workspace"); expect(receiptRenameCount).toBe(0); // 1b) Reverting to matching receipt (--edge-init rev 0) after observing newer sidecar rev 2 - // on the fast path, then hitting io_error on the locked read, keeps --edge-init pending. + // on the fast path, then hitting io_error while locked, keeps --edge-init pending. failSidecarRead = false; - sidecarReadCount = 0; - failSidecarReadOnCount = 2; + failSidecarReadWhileLockedPath = edgeSyncSidecarLockPath; yield* edgeCatB.resolve(settings(), "/workspace"); - failSidecarReadOnCount = null; + failSidecarReadWhileLockedPath = null; expect(receiptRenameCount).toBe(0); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -6249,10 +6261,9 @@ describe("AcpRegistrySupport", () => { failReceiptTempWrite = false; failSidecarWrite = false; // Transient locked receipt reread failure must preserve pending --fail-2. - receiptReadCount = 0; - failReceiptReadOnCount = 2; + failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; yield* edgeCatA.resolve(settings(), "/workspace"); - failReceiptReadOnCount = null; + failReceiptReadWhileLockedPath = null; // Before catalog B commits a newer rev, edgeCatA's in-process fallback uses pending --fail-2. upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -6334,7 +6345,8 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--lock-c", ]); - // Retry with unreadable sidecar keeps baseDurableRevision=7 (not downgraded to receipt rev 4). + // Retry with unreadable sidecar keeps baseDurableRevision=7 (not downgraded to receipt rev 4) + // across sidecar io_error, locked receipt reread failure, and a second lock timeout. failSidecarRead = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -6354,7 +6366,97 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--lock-c-retry", ]); - // A newer committed rev 8 (--commit-8) still outranks pending base rev 7. + // Locked receipt reread error while sidecar is unreadable also preserves base rev 7. + failSidecarRead = true; + failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-reread"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-reread", + ]); + // A second lock timeout while sidecar is unreadable also preserves base rev 7. + failSidecarRead = true; + yield* fileSystem.writeFileString(edgeSyncSidecarLockPath, "external-holder-2"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-timeout2"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + let nextLockStat2 = yield* Deferred.make(); + onStatPath = { + matchPath: edgeSyncSidecarLockPath, + onHit: () => { + Deferred.doneUnsafe(nextLockStat2, Exit.void); + }, + }; + const lockTimeoutFiber2 = yield* lockTimeoutCat + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + for (let step = 0; step < 20; step += 1) { + yield* Deferred.await(nextLockStat2); + nextLockStat2 = yield* Deferred.make(); + yield* TestClock.adjust("100 millis"); + } + onStatPath = null; + yield* Fiber.join(lockTimeoutFiber2); + yield* fileSystem.remove(edgeSyncSidecarLockPath, { force: true }); + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-timeout2", + ]); + // Corrupt sidecar while pending base is rev 7 must allocate rev 8 (> 7), not rev 5. + const savedSidecarBeforeCorrupt = yield* fileSystem.readFileString(edgeSyncSidecarPath); + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-corrupt-rev8"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const afterCorruptResolved = yield* lockTimeoutCat.resolve(settings(), "/workspace"); + const afterCorruptReceiptPath = path.join( + path.dirname(path.dirname(afterCorruptResolved.spawn.command)), + ".t3-artifact.json", + ); + const afterCorruptReceipt = JSON.parse( + yield* fileSystem.readFileString(afterCorruptReceiptPath), + ) as { readonly launchOptionsRevision?: number }; + expect(afterCorruptReceipt.launchOptionsRevision).toBe(8); + // Restore sidecar at rev 7 (lower than rev 8) and confirm rev 8 receipt wins cleanly. + yield* fileSystem.writeFileString(edgeSyncSidecarPath, savedSidecarBeforeCorrupt); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--after-corrupt-rev8", + ]); + // A newer committed rev 9 (--commit-9) still outranks everything cleanly. upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -6497,6 +6599,7 @@ describe("AcpRegistrySupport", () => { let sidecarFenceGate: { readonly entered: Deferred.Deferred; readonly release: Deferred.Deferred; + readonly requireLocked?: boolean; } | null = null; let uninstallFenceGate: { readonly entered: Deferred.Deferred; @@ -6525,6 +6628,21 @@ describe("AcpRegistrySupport", () => { } if (sidecarFenceGate !== null && filePath === fenceSidecarPath) { const gate = sidecarFenceGate; + if (gate.requireLocked === true) { + return fileSystem.exists(fenceSidecarLockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => { + if (!locked || sidecarFenceGate !== gate) { + return posixModeFs.readFileString(filePath, encoding); + } + sidecarFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + }), + ); + } sidecarFenceGate = null; return Deferred.succeed(gate.entered, undefined).pipe( Effect.andThen(Deferred.await(gate.release)), @@ -6609,7 +6727,8 @@ describe("AcpRegistrySupport", () => { expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--fenced-sidecar", ]); - // Reverting to the receipt's no-args target clears stale pending options even on lock loss. + // Reverting to the receipt's no-args target clears stale pending options even on lock loss + // (for both stale rev-0 sidecar entries and corrupt sidecar files). yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); yield* fileSystem.writeFileString( fenceSidecarPath, @@ -6632,22 +6751,10 @@ describe("AcpRegistrySupport", () => { yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); const revertEntered = yield* Deferred.make(); const releaseRevert = yield* Deferred.make(); - let revertReadCount = 0; - const origFenceRead = fencedFs.readFileString; - (fencedFs as { readFileString: FileSystem.FileSystem["readFileString"] }).readFileString = ( - filePath, - encoding, - ) => { - if (filePath === fenceSidecarPath) { - revertReadCount += 1; - if (revertReadCount === 2) { - return Deferred.succeed(revertEntered, undefined).pipe( - Effect.andThen(Deferred.await(releaseRevert)), - Effect.andThen(origFenceRead(filePath, encoding)), - ); - } - } - return origFenceRead(filePath, encoding); + sidecarFenceGate = { + entered: revertEntered, + release: releaseRevert, + requireLocked: true, }; const fencedRevertResolve = yield* holder1 .resolve(settings(), "/workspace") @@ -6656,8 +6763,48 @@ describe("AcpRegistrySupport", () => { yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-3"); yield* Deferred.succeed(releaseRevert, undefined); yield* Fiber.join(fencedRevertResolve); - (fencedFs as { readFileString: FileSystem.FileSystem["readFileString"] }).readFileString = - origFenceRead; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([]); + // Same lock-lost revert check on a corrupt sidecar file. + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--fenced-before-corrupt"], + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* holder1.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + yield* fileSystem.writeFileString(fenceSidecarPath, "{corrupt-fence"); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const corruptRevertEntered = yield* Deferred.make(); + const releaseCorruptRevert = yield* Deferred.make(); + sidecarFenceGate = { + entered: corruptRevertEntered, + release: releaseCorruptRevert, + requireLocked: true, + }; + const fencedCorruptRevert = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(corruptRevertEntered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-4"); + yield* Deferred.succeed(releaseCorruptRevert, undefined); + yield* Fiber.join(fencedCorruptRevert); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 89e368e2a3ec2..6bcf92e738206 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -2795,6 +2795,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct receipt: buildLaunchOptionsReceipt(baseReceipt), }); }; + const recordPendingForInitialReceipt = () => { + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const currentPriorPendingBase = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, initialReceipt) + ? currentPending.baseDurableRevision + : 0; + recordPending( + initialReceipt, + Math.max(receiptRev, observedDiskRev, initialPriorPendingBase, currentPriorPendingBase), + ); + }; yield* withBinaryLaunchOptionsLock((isLockOwned) => Effect.gen(function* () { const freshReceiptRead = yield* Effect.result(fileSystem.readFileString(receiptPath)); @@ -2802,21 +2814,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (freshReceiptRead.failure.reason._tag === "NotFound") { pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); - const currentPriorPendingBase = - currentPending !== undefined && - receiptMatchesInstall(currentPending.receipt, initialReceipt) - ? currentPending.baseDurableRevision - : 0; - recordPending( - initialReceipt, - Math.max( - receiptRev, - observedDiskRev, - initialPriorPendingBase, - currentPriorPendingBase, - ), - ); + recordPendingForInitialReceipt(); } return; } @@ -2846,16 +2844,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct binaryLaunchOptionsPath, ); if (diskResult.status === "io_error") { - // Do not rewrite a matching receipt or allocate a revision below an unreadable sidecar; - // keep launch usable via pending options and retry once sidecar reads recover. - if ( - receiptMatchesLaunchOptions(freshReceipt, target) && - effectiveObservedBase <= freshReceiptRev - ) { - pendingLaunchOptionsBySlotRoot.delete(slot.root); - } else { - recordPending(freshReceipt, effectiveObservedBase); - } + // Never treat an unreadable sidecar as absent or allocate below it; keep the target + // pending until the sidecar can be read and reconciled under the lock. + recordPending(freshReceipt, effectiveObservedBase); return; } const isCorrupt = diskResult.status === "corrupt"; @@ -2893,7 +2884,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } - const committedBaseRev = Math.max(freshReceiptRev, freshDiskRev); + const committedBaseRev = Math.max(effectiveObservedBase, freshDiskRev); const nextRevision = committedBaseRev + 1; const updatedReceipt = buildLaunchOptionsReceipt(freshReceipt, nextRevision); if (!(yield* isLockOwned)) { @@ -2964,21 +2955,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ).pipe( Effect.catch(() => Effect.sync(() => { - const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); - const currentPriorPendingBase = - currentPending !== undefined && - receiptMatchesInstall(currentPending.receipt, initialReceipt) - ? currentPending.baseDurableRevision - : 0; - recordPending( - initialReceipt, - Math.max( - receiptRev, - observedDiskRev, - initialPriorPendingBase, - currentPriorPendingBase, - ), - ); + recordPendingForInitialReceipt(); }), ), ); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index f00f07aef7734..b15edd071f2c6 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3696,12 +3696,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { const gate = getAvailableCommandsGate; getAvailableCommandsGate = null; return Deferred.succeed(gate.started, undefined).pipe( - Effect.andThen( - Deferred.await(gate.release).pipe( - Effect.onInterrupt(() => - Deferred.succeed(gate.interrupted, undefined).pipe(Effect.asVoid), - ), - ), + Effect.andThen(Deferred.await(gate.release)), + Effect.onInterrupt(() => + Deferred.succeed(gate.interrupted, undefined).pipe(Effect.asVoid), ), Effect.andThen(baseCoordinator.getAvailableCommands(instanceId, options)), ); @@ -4430,6 +4427,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { onEnrichmentEnd = () => Deferred.doneUnsafe(v2ReadyDone, Exit.void); yield* fallbackRetireInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), ); expect(Option.isSome(yield* Fiber.join(v2Ready))).toBe(true); yield* Deferred.await(v2ReadyDone); @@ -4451,6 +4449,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { onEnrichmentEnd = () => Deferred.doneUnsafe(v4InitialDone, Exit.void); yield* fallbackRetireInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), ); expect(Option.isSome(yield* Fiber.join(v4Ready))).toBe(true); yield* Deferred.await(v4InitialDone); @@ -4486,6 +4485,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackEnrichmentDone, Exit.void); yield* fallbackRetireInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), ); yield* Deferred.await(v2FallbackGate.started); remoteVersion = "4.0.0"; @@ -4917,8 +4917,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { Effect.provideService(Tracer.Tracer, enrichmentTracer), ); yield* Deferred.await(beforeLogoutDone); - expect((yield* logoutInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); - expect((yield* logoutInstance.snapshot.getSnapshot).auth.canLogout).toBe(true); + const beforeLogoutSnap = yield* logoutInstance.snapshot.getSnapshot; + expect(beforeLogoutSnap.auth.status).toBe("authenticated"); + expect(beforeLogoutSnap.auth.canLogout).toBe(true); + expect(beforeLogoutSnap.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); yield* logoutInstance.acpSessionManagement!.logout(directory); expect(yield* (yield* seedLogoutAuth()).get).toBe(false); // Same-runtime non-auth failure after logout must show unknown (never authenticated). @@ -4931,8 +4933,8 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* Deferred.await(afterLogoutSameFailDone); expect((yield* logoutInstance.snapshot.getSnapshot).status).toBe("warning"); expect((yield* logoutInstance.snapshot.getSnapshot).auth.status).toBe("unknown"); - // Failed upgrade to 2.0.0 after logout keeps A's capabilities and stays unknown across - // both retained-runtime publication and follow-up inspectReadiness. + // Failed upgrade to 2.0.0 after logout keeps A's discovered models and stays unknown + // across both retained-runtime publication and follow-up inspectReadiness. remoteVersion = "2.0.0"; yield* realCatalog.invalidateIndex(); yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); @@ -4946,7 +4948,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(afterLogoutUpgradeSnap.version).toBe("1.0.0"); expect(afterLogoutUpgradeSnap.status).toBe("warning"); expect(afterLogoutUpgradeSnap.auth.status).toBe("unknown"); - expect(afterLogoutUpgradeSnap.models.length).toBeGreaterThan(0); + expect(afterLogoutUpgradeSnap.models.map((model) => model.slug)).toEqual([ + "model-a", + "model-b", + ]); const afterLogoutSnapshots: Array = []; const afterLogoutCollector = yield* logoutInstance.snapshot.streamChanges.pipe( Stream.runForEach((snapshot) => @@ -5034,48 +5039,106 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(emitted.auth.status).not.toBe("authenticated"); } - // (f) Local agent (previousIdentity === null, normal branch) clears saved confirmation on auth failure. + // (f) Local agent (previousIdentity === null, normal branch): a superseded auth rejection + // keeps saved confirmation intact, while an accepted auth rejection clears it. const localUnauthId = ProviderInstanceId.make("acpRegistry_local_unauth"); const localUnauthSettings = decodeSettings({ source: "local", commandPath: "local-auth-fail", }); + const localUnauthEnv = [{ name: "MISE_OFFLINE", value: "0", sensitive: false }] as const; const seedLocalAuth = () => AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ cacheDir: host.paths.providerStatusCacheDir, instanceId: localUnauthId, settings: localUnauthSettings, - environment: [], + environment: localUnauthEnv, processEnvironment: process.env, }); yield* (yield* seedLocalAuth()).set(true); - const localUnauthDone = yield* Deferred.make(); - onEnrichmentEnd = () => Deferred.doneUnsafe(localUnauthDone, Exit.void); + let localFailAuth = true; + const localWithLiveStarted = yield* Deferred.make(); + const localWithLiveRelease = yield* Deferred.make(); + const localWithLiveInterrupted = yield* Deferred.make(); + let localGateArmed = false; + const localCatalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...catalogWithInspection({ + status: "ready", + agentId: "local-auth-fail", + version: null, + distribution: "local", + }), + resolve: (_settings, _cwd, environment) => + Effect.sync(() => { + if (environment?.MISE_OFFLINE === "1" && !localGateArmed) { + localGateArmed = true; + getAvailableCommandsGate = { + instanceId: localUnauthId, + started: localWithLiveStarted, + release: localWithLiveRelease, + interrupted: localWithLiveInterrupted, + }; + } + return { + distribution: "local" as const, + spawn: { + command: process.execPath, + args: localFailAuth ? [authFailAgentPath] : [agentPath, modelsPath], + cwd: directory, + env: process.env, + }, + }; + }), + }; + // Startup probe runs with previousIdentity === null (normal branch), fails auth, and pauses + // inside withLiveRuntimeState before tryPublishSnapshot; superseding refresh keeps auth. const localUnauthInstance = yield* AcpRegistryDriver.create({ instanceId: localUnauthId, displayName: "Local Unauth", enabled: true, - environment: [], + environment: localUnauthEnv, config: localUnauthSettings, }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "local-auth-fail", - version: null, - distribution: "local", - }), - resolve: () => - Effect.succeed({ - distribution: "local", - spawn: { - command: process.execPath, - args: [authFailAgentPath], - cwd: directory, - env: process.env, - }, - }), - }), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localWithLiveStarted); + localFailAuth = false; + const localSupersedingDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localSupersedingDone, Exit.void); + yield* localUnauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localWithLiveInterrupted); + yield* Deferred.await(localSupersedingDone); + expect(yield* (yield* seedLocalAuth()).get).toBe(true); + expect((yield* localUnauthInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + // Accepted normal-branch local auth rejection clears saved confirmation. + const localAcceptedId = ProviderInstanceId.make("acpRegistry_local_unauth_accepted"); + const seedLocalAcceptedAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: localAcceptedId, + settings: localUnauthSettings, + environment: localUnauthEnv, + processEnvironment: process.env, + }); + yield* (yield* seedLocalAcceptedAuth()).set(true); + localFailAuth = true; + const localUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localUnauthDone, Exit.void); + const localAcceptedInstance = yield* AcpRegistryDriver.create({ + instanceId: localAcceptedId, + displayName: "Local Unauth Accepted", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), Effect.provideService( AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, coordinator, @@ -5083,10 +5146,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { Effect.provideService(Tracer.Tracer, enrichmentTracer), ); yield* Deferred.await(localUnauthDone); - expect((yield* localUnauthInstance.snapshot.getSnapshot).auth.status).toBe( + expect((yield* localAcceptedInstance.snapshot.getSnapshot).auth.status).toBe( "unauthenticated", ); - expect(yield* (yield* seedLocalAuth()).get).toBe(false); + expect(yield* (yield* seedLocalAcceptedAuth()).get).toBe(false); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index ce044d656f4af..7aee09b579a6d 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1058,16 +1058,9 @@ export const AcpRegistryDriver: ProviderDriver + const clearCachedProbeForRuntime = (runtimeIdentity: string | null) => Ref.update(enrichmentCache, (cache) => { - const entryIdentity = - cache.entry === null - ? null - : runtimeIdentityFor(cache.entry.provider, cache.entry.launchIdentity ?? null); - const matchesEntry = - cache.entry !== null && - (effectiveConfig.source === "local" || - (runtimeIdentity !== null && entryIdentity === runtimeIdentity)); - let liveGenerationByRuntime = nextLiveGenerationByRuntime( - cache.liveGenerationByRuntime, - runtimeIdentity, + if (cache.entry === null) return cache; + const entryIdentity = runtimeIdentityFor( + cache.entry.provider, + cache.entry.launchIdentity ?? null, ); - if (matchesEntry && entryIdentity !== runtimeIdentity) { - liveGenerationByRuntime = nextLiveGenerationByRuntime( - liveGenerationByRuntime, - entryIdentity, - ); - } - return { - ...cache, - liveGenerationByRuntime, - ...(matchesEntry ? { entry: null } : {}), - }; + return effectiveConfig.source === "local" || + (runtimeIdentity !== null && entryIdentity === runtimeIdentity) + ? { ...cache, entry: null } + : cache; }); + const recordAcceptedAuthRejection = (identity: string | null, auth: ServerProvider["auth"]) => + confirmedAuthentication + .set(false) + .pipe( + Effect.andThen(clearCachedProbeForRuntime(identity)), + Effect.andThen( + identity === null ? Effect.void : Ref.set(latestAcceptedAuth, { identity, auth }), + ), + ); const isProbeStillCurrent = ( current: AcpRegistryEnrichmentCache, captured: { @@ -1787,11 +1773,10 @@ export const AcpRegistryDriver: ProviderDriver Date: Sun, 22 Nov 2026 21:59:22 +0000 Subject: [PATCH 24/28] fix(acp-registry): harden recovery ordering, atomic auth rejection, and live replay --- .../src/server/AcpRegistrySupport.test.ts | 153 +++++++- .../src/server/AcpRegistrySupport.ts | 143 +++++-- .../src/server/driver.test.ts | 323 +++++++++++++++- .../src/server/driver.ts | 354 ++++++++++-------- 4 files changed, 790 insertions(+), 183 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index cdaba6a486a5a..09c0a77b2f943 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -5113,7 +5113,9 @@ describe("AcpRegistrySupport", () => { let failSidecarWrite = false; let failSidecarRead = false; let failSidecarReadWhileLockedPath: string | null = null; + let corruptSidecarWhileLockedPath: string | null = null; let failReceiptReadWhileLockedPath: string | null = null; + let injectedReceiptReadFailures = 0; let receiptRenameCount = 0; let onStatPath: { readonly matchPath: string; @@ -5147,6 +5149,17 @@ describe("AcpRegistrySupport", () => { if (failSidecarRead) { return fileSystem.readFileString(path.dirname(filePath), encoding); } + if (corruptSidecarWhileLockedPath !== null) { + const lockPath = corruptSidecarWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? Effect.succeed("{corrupt-under-lock") + : fileSystem.readFileString(filePath, encoding), + ), + ); + } if (failSidecarReadWhileLockedPath !== null) { const lockPath = failSidecarReadWhileLockedPath; return fileSystem.exists(lockPath).pipe( @@ -5165,7 +5178,11 @@ describe("AcpRegistrySupport", () => { Effect.orElseSucceed(() => false), Effect.flatMap((locked) => locked - ? fileSystem.readFileString(path.dirname(filePath), encoding) + ? Effect.sync(() => { + injectedReceiptReadFailures += 1; + }).pipe( + Effect.andThen(fileSystem.readFileString(path.dirname(filePath), encoding)), + ) : fileSystem.readFileString(filePath, encoding), ), ); @@ -6261,9 +6278,11 @@ describe("AcpRegistrySupport", () => { failReceiptTempWrite = false; failSidecarWrite = false; // Transient locked receipt reread failure must preserve pending --fail-2. + injectedReceiptReadFailures = 0; failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; yield* edgeCatA.resolve(settings(), "/workspace"); failReceiptReadWhileLockedPath = null; + expect(injectedReceiptReadFailures).toBe(1); // Before catalog B commits a newer rev, edgeCatA's in-process fallback uses pending --fail-2. upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -6367,6 +6386,7 @@ describe("AcpRegistrySupport", () => { "--lock-c-retry", ]); // Locked receipt reread error while sidecar is unreadable also preserves base rev 7. + injectedReceiptReadFailures = 0; failSidecarRead = true; failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; upstream = makeBinary("1.0.0", { @@ -6379,6 +6399,7 @@ describe("AcpRegistrySupport", () => { yield* lockTimeoutCat.resolve(settings(), "/workspace"); failReceiptReadWhileLockedPath = null; failSidecarRead = false; + expect(injectedReceiptReadFailures).toBe(1); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", @@ -6426,23 +6447,109 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--lock-c-timeout2", ]); - // Corrupt sidecar while pending base is rev 7 must allocate rev 8 (> 7), not rev 5. + // Corrupt sidecar repaired by a fresh catalog (via sidecar OR receipt OR matching receipt) + // must outrank lockTimeoutCat's older higher-base pending entry via launchOptionsRecoveryId. const savedSidecarBeforeCorrupt = yield* fileSystem.readFileString(edgeSyncSidecarPath); + const freshRepairCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + // (i) Sidecar repair (rev 5 < pending base 7) and subsequent normal write (rev 6 < 7). yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + failReceiptTempWrite = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", - args: ["--after-corrupt-rev8"], + args: ["--fresh-b-sidecar-repair"], + }); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fresh-b-sidecar-repair", + ]); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-sidecar-rev6"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", }); yield* lockTimeoutCat.invalidateIndex(); yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - const afterCorruptResolved = yield* lockTimeoutCat.resolve(settings(), "/workspace"); - const afterCorruptReceiptPath = path.join( - path.dirname(path.dirname(afterCorruptResolved.spawn.command)), + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fresh-b-sidecar-rev6", + ]); + // (ii) Receipt repair (rev 5 < pending base 7) and matching-receipt repair on corrupt file. + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-receipt-repair"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const freshReceiptResolved = yield* freshRepairCat.resolve(settings(), "/workspace"); + const edgeReceiptPath = path.join( + path.dirname(path.dirname(freshReceiptResolved.spawn.command)), ".t3-artifact.json", ); + const afterReceiptRepair = JSON.parse( + yield* fileSystem.readFileString(edgeReceiptPath), + ) as { readonly launchOptionsRevision?: number; readonly launchOptionsRecoveryId?: string }; + expect(afterReceiptRepair.launchOptionsRevision).toBe(5); + expect(afterReceiptRepair.launchOptionsRecoveryId).toBeDefined(); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fresh-b-receipt-repair", + ]); + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar-match"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-receipt-repair"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + const afterMatchRepair = JSON.parse(yield* fileSystem.readFileString(edgeReceiptPath)) as { + readonly launchOptionsRevision?: number; + readonly launchOptionsRecoveryId?: string; + }; + expect(afterMatchRepair.launchOptionsRevision).toBe(6); + expect(afterMatchRepair.launchOptionsRecoveryId).toBeDefined(); + expect(afterMatchRepair.launchOptionsRecoveryId).not.toBe( + afterReceiptRepair.launchOptionsRecoveryId, + ); + // Corrupt sidecar while lockTimeoutCat holds pending base rev 7 must allocate rev 8 (> 7). + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-corrupt-rev8"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); const afterCorruptReceipt = JSON.parse( - yield* fileSystem.readFileString(afterCorruptReceiptPath), + yield* fileSystem.readFileString(edgeReceiptPath), ) as { readonly launchOptionsRevision?: number }; expect(afterCorruptReceipt.launchOptionsRevision).toBe(8); // Restore sidecar at rev 7 (lower than rev 8) and confirm rev 8 receipt wins cleanly. @@ -6456,7 +6563,7 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--after-corrupt-rev8", ]); - // A newer committed rev 9 (--commit-9) still outranks everything cleanly. + // A newer committed rev 9 (--commit-8) still outranks everything cleanly. upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -6474,6 +6581,36 @@ describe("AcpRegistrySupport", () => { expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--commit-8", ]); + // Fresh catalog (no pending entry) that observes sidecar rev 10 on the fast path, then + // encounters a corrupt sidecar under the lock, allocates rev 11 (> observedDiskRev 10). + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--sidecar-rev10"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + const observedRevCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* observedRevCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + corruptSidecarWhileLockedPath = edgeSyncSidecarLockPath; + yield* observedRevCat.resolve(settings(), "/workspace"); + corruptSidecarWhileLockedPath = null; + const afterObservedRev = JSON.parse(yield* fileSystem.readFileString(edgeReceiptPath)) as { + readonly launchOptionsRevision?: number; + }; + expect(afterObservedRev.launchOptionsRevision).toBe(11); // 5) Fast-path hasMatchingPending gating: reverting to matching receipt --commit-8 clears // earlier pending options instead of short-circuiting and leaving them active. failReceiptTempWrite = true; diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 6bcf92e738206..8faa30459b661 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -742,6 +742,7 @@ const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ args: Schema.optional(Schema.Array(Schema.String)), env: Schema.optional(Schema.Record(Schema.String, Schema.String)), launchOptionsRevision: Schema.optional(Schema.Finite), + launchOptionsRecoveryId: Schema.optional(Schema.String), installId: Schema.optional(Schema.String), }); type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt.Type; @@ -951,6 +952,7 @@ function encodeBinaryArtifactReceipt( target: typeof AcpRegistryBinaryTarget.Type, options?: { readonly launchOptionsRevision?: number; + readonly launchOptionsRecoveryId?: string; readonly installId?: string; }, ): string { @@ -964,6 +966,9 @@ function encodeBinaryArtifactReceipt( ...(options?.launchOptionsRevision !== undefined ? { launchOptionsRevision: options.launchOptionsRevision } : {}), + ...(options?.launchOptionsRecoveryId !== undefined + ? { launchOptionsRecoveryId: options.launchOptionsRecoveryId } + : {}), ...(options?.installId !== undefined ? { installId: options.installId } : {}), }); } @@ -1170,7 +1175,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const pendingLaunchOptionsBySlotRoot = new Map< string, { + readonly baseReceiptRevision: number; readonly baseDurableRevision: number; + readonly baseRecoveryId: string | null; readonly receipt: AcpRegistryBinaryArtifactReceipt; } >(); @@ -2744,19 +2751,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const pendingEntry = pendingLaunchOptionsBySlotRoot.get(slot.root); const hasMatchingPending = pendingEntry !== undefined && receiptMatchesInstall(pendingEntry.receipt, initialReceipt); + const initialPriorReceiptBase = hasMatchingPending ? pendingEntry.baseReceiptRevision : 0; const initialPriorPendingBase = hasMatchingPending ? pendingEntry.baseDurableRevision : 0; const receiptRev = initialReceipt.launchOptionsRevision ?? 0; + let fastPathSidecarReadOk = false; let observedDiskRev = 0; + let observedDiskRecoveryId: string | null = null; if (!hasSidecar) { + fastPathSidecarReadOk = true; if (!hasMatchingPending && receiptMatchesLaunchOptions(initialReceipt, target)) { return; } } else { const diskResult = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); if (diskResult.status === "ok") { + fastPathSidecarReadOk = true; const diskStored = diskResult.entries[slot.root]; const diskMatches = receiptMatchesInstall(diskStored, initialReceipt); observedDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + observedDiskRecoveryId = diskMatches + ? (diskStored.launchOptionsRecoveryId ?? null) + : null; if (!hasMatchingPending) { if (diskStored === undefined && receiptMatchesLaunchOptions(initialReceipt, target)) { return; @@ -2776,6 +2791,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const buildLaunchOptionsReceipt = ( baseReceipt: AcpRegistryBinaryArtifactReceipt, revision?: number, + recoveryId?: string | null, ): AcpRegistryBinaryArtifactReceipt => ({ version: agent.version, archive: target.archive, @@ -2784,27 +2800,66 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), ...(revision !== undefined ? { launchOptionsRevision: revision } : {}), + ...(recoveryId ? { launchOptionsRecoveryId: recoveryId } : {}), ...(baseReceipt.installId !== undefined ? { installId: baseReceipt.installId } : {}), }); const recordPending = ( baseReceipt: AcpRegistryBinaryArtifactReceipt, + baseReceiptRevision: number, baseDurableRevision: number, + baseRecoveryId: string | null, ) => { pendingLaunchOptionsBySlotRoot.set(slot.root, { + baseReceiptRevision, baseDurableRevision, + baseRecoveryId, receipt: buildLaunchOptionsReceipt(baseReceipt), }); }; + const resolvePendingRecoveryId = ( + baseReceipt: AcpRegistryBinaryArtifactReceipt, + baseReceiptRev: number, + priorPending: + | { + readonly baseReceiptRevision: number; + readonly baseDurableRevision: number; + readonly baseRecoveryId: string | null; + } + | undefined, + ): string | null => { + if (fastPathSidecarReadOk && observedDiskRev > baseReceiptRev) { + return observedDiskRecoveryId; + } + if ( + priorPending !== undefined && + baseReceiptRev <= priorPending.baseReceiptRevision && + priorPending.baseDurableRevision > baseReceiptRev + ) { + return priorPending.baseRecoveryId; + } + return baseReceipt.launchOptionsRecoveryId ?? null; + }; const recordPendingForInitialReceipt = () => { const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); - const currentPriorPendingBase = + const matchingPending = currentPending !== undefined && receiptMatchesInstall(currentPending.receipt, initialReceipt) - ? currentPending.baseDurableRevision - : 0; + ? currentPending + : undefined; recordPending( initialReceipt, - Math.max(receiptRev, observedDiskRev, initialPriorPendingBase, currentPriorPendingBase), + Math.max(receiptRev, initialPriorReceiptBase, matchingPending?.baseReceiptRevision ?? 0), + Math.max( + receiptRev, + observedDiskRev, + initialPriorPendingBase, + matchingPending?.baseDurableRevision ?? 0, + ), + resolvePendingRecoveryId( + initialReceipt, + receiptRev, + matchingPending ?? (hasMatchingPending ? pendingEntry : undefined), + ), ); }; yield* withBinaryLaunchOptionsLock((isLockOwned) => @@ -2829,15 +2884,19 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const freshReceipt = decodedFreshReceipt.value; const freshReceiptRev = freshReceipt.launchOptionsRevision ?? 0; const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); - const priorPendingBase = + const matchingPending = currentPending !== undefined && receiptMatchesInstall(currentPending.receipt, freshReceipt) - ? currentPending.baseDurableRevision - : 0; + ? currentPending + : undefined; + const effectiveReceiptBase = Math.max( + freshReceiptRev, + matchingPending?.baseReceiptRevision ?? 0, + ); const effectiveObservedBase = Math.max( freshReceiptRev, observedDiskRev, - priorPendingBase, + matchingPending?.baseDurableRevision ?? 0, ); const diskResult = yield* readBinaryLaunchOptionsFile( fileSystem, @@ -2846,7 +2905,12 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (diskResult.status === "io_error") { // Never treat an unreadable sidecar as absent or allocate below it; keep the target // pending until the sidecar can be read and reconciled under the lock. - recordPending(freshReceipt, effectiveObservedBase); + recordPending( + freshReceipt, + effectiveReceiptBase, + effectiveObservedBase, + resolvePendingRecoveryId(freshReceipt, freshReceiptRev, matchingPending), + ); return; } const isCorrupt = diskResult.status === "corrupt"; @@ -2854,16 +2918,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const diskStored = diskEntries[slot.root]; const diskMatches = receiptMatchesInstall(diskStored, freshReceipt); const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; - if (receiptMatchesLaunchOptions(freshReceipt, target)) { - if (isCorrupt) { - pendingLaunchOptionsBySlotRoot.delete(slot.root); - if (!(yield* isLockOwned)) return; - yield* fileSystem - .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) - .pipe(Effect.ignore); - yield* writeJsonFileAtomically(binaryLaunchOptionsPath, {}).pipe(Effect.ignore); - return; - } + const currentDurableRecoveryId = + !isCorrupt && diskMatches && freshDiskRev > freshReceiptRev + ? (diskStored.launchOptionsRecoveryId ?? null) + : (freshReceipt.launchOptionsRecoveryId ?? null); + if (!isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { if (diskStored === undefined) { pendingLaunchOptionsBySlotRoot.delete(slot.root); return; @@ -2886,11 +2945,25 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const committedBaseRev = Math.max(effectiveObservedBase, freshDiskRev); const nextRevision = committedBaseRev + 1; - const updatedReceipt = buildLaunchOptionsReceipt(freshReceipt, nextRevision); if (!(yield* isLockOwned)) { - recordPending(freshReceipt, committedBaseRev); + if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending( + freshReceipt, + effectiveReceiptBase, + committedBaseRev, + currentDurableRecoveryId, + ); + } return; } + const nextRecoveryId = isCorrupt ? yield* random.uuidV4() : currentDurableRecoveryId; + const updatedReceipt = buildLaunchOptionsReceipt( + freshReceipt, + nextRevision, + nextRecoveryId, + ); const receiptWrite = yield* Effect.result( random.uuidV4().pipe( Effect.flatMap((id) => { @@ -2900,6 +2973,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct temporaryPath, encodeBinaryArtifactReceipt(agent, target, { launchOptionsRevision: nextRevision, + ...(nextRecoveryId !== null + ? { launchOptionsRecoveryId: nextRecoveryId } + : {}), ...(freshReceipt.installId !== undefined ? { installId: freshReceipt.installId } : {}), @@ -2932,7 +3008,16 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // lock), persist the updated launch options in registry cache storage so fallback still // restores the last-resolved args and env even across restarts. if (!(yield* isLockOwned)) { - recordPending(freshReceipt, committedBaseRev); + if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending( + freshReceipt, + effectiveReceiptBase, + committedBaseRev, + currentDurableRecoveryId, + ); + } return; } if (isCorrupt) { @@ -2948,8 +3033,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); if (Result.isSuccess(sidecarWrite)) { pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - recordPending(freshReceipt, committedBaseRev); + recordPending( + freshReceipt, + effectiveReceiptBase, + committedBaseRev, + currentDurableRecoveryId, + ); } }), ).pipe( @@ -3675,7 +3767,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveReceipt = pendingOverride !== undefined && receiptMatchesInstall(pendingOverride.receipt, receipt) && - (durableReceipt.launchOptionsRevision ?? 0) <= pendingOverride.baseDurableRevision + (receipt.launchOptionsRevision ?? 0) <= pendingOverride.baseReceiptRevision && + (durableReceipt.launchOptionsRevision ?? 0) <= + pendingOverride.baseDurableRevision && + (durableReceipt.launchOptionsRecoveryId ?? null) === pendingOverride.baseRecoveryId ? pendingOverride.receipt : durableReceipt; const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index b15edd071f2c6..b5d32d325fafa 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3590,6 +3590,8 @@ describe("AcpRegistryDriver registry recovery", () => { const authFailAgentPath = path.join(directory, "auth-fail-agent.mjs"); const exitFailAgentPath = path.join(directory, "exit-fail-agent.mjs"); const logoutAgentPath = path.join(directory, "logout-agent.mjs"); + const authLoginAgentPath = path.join(directory, "auth-login-agent.mjs"); + const versionlessLocalAgentPath = path.join(directory, "versionless-local-agent.mjs"); yield* fileSystem.writeFileString(exitFailAgentPath, "process.exit(1);\n"); yield* fileSystem.writeFileString( logoutAgentPath, @@ -3598,6 +3600,20 @@ describe("AcpRegistryDriver registry recovery", () => { "agentCapabilities: { auth: { logout: {} } }", ), ); + yield* fileSystem.writeFileString( + authLoginAgentPath, + fakeAgentSource.replace( + "authMethods: []", + 'authMethods: [{ id: "agent-login", name: "Agent Login", type: "agent" }]', + ), + ); + yield* fileSystem.writeFileString( + versionlessLocalAgentPath, + fakeAgentSource.replace( + 'agentInfo: { name: "fake", version: "1.5.9" }', + 'agentInfo: { name: "fake", version: "" }', + ), + ); yield* fileSystem.writeFileString( authFailAgentPath, ` @@ -3632,6 +3648,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { let failProbeAuth = false; let failProbeExit = false; let useLogoutAgent = false; + let useAuthLoginAgent = false; let probeResolveCount = 0; let defectInspectCount = 0; let interruptInspectOnce = false; @@ -3846,7 +3863,14 @@ createInterface({ input: process.stdin }).on("line", (line) => { ? [exitFailAgentPath] : environment?.MISE_OFFLINE === "1" && failProbeAuth ? [authFailAgentPath] - : [useLogoutAgent ? logoutAgentPath : agentPath, modelsPath], + : [ + useAuthLoginAgent + ? authLoginAgentPath + : useLogoutAgent + ? logoutAgentPath + : agentPath, + modelsPath, + ], }, }; }), @@ -4921,10 +4945,33 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(beforeLogoutSnap.auth.status).toBe("authenticated"); expect(beforeLogoutSnap.auth.canLogout).toBe(true); expect(beforeLogoutSnap.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + // Live config update while authenticated must also strip "authenticated" in lastSuccessfulRuntime. + const logoutLiveUpdated = yield* logoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "model-live")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + logoutInstanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "model-live", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-b", name: "model-b" }, + { modelId: "model-live", name: "model-live" }, + ], + }), + v1Identity, + ); + expect( + Option.getOrThrow(yield* Fiber.join(logoutLiveUpdated)).models.map((model) => model.slug), + ).toEqual(["model-a", "model-b", "model-live"]); + // Set failProbeSpawn before logout so logout's own refresh cannot overwrite + // lastSuccessfulRuntime with a fresh probe before we assert auth.status === "unknown". + failProbeSpawn = true; yield* logoutInstance.acpSessionManagement!.logout(directory); expect(yield* (yield* seedLogoutAuth()).get).toBe(false); // Same-runtime non-auth failure after logout must show unknown (never authenticated). - failProbeSpawn = true; const afterLogoutSameFailDone = yield* Deferred.make(); onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutSameFailDone, Exit.void); yield* logoutInstance.snapshot.refresh.pipe( @@ -4951,6 +4998,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(afterLogoutUpgradeSnap.models.map((model) => model.slug)).toEqual([ "model-a", "model-b", + "model-live", ]); const afterLogoutSnapshots: Array = []; const afterLogoutCollector = yield* logoutInstance.snapshot.streamChanges.pipe( @@ -4972,9 +5020,210 @@ createInterface({ input: process.stdin }).on("line", (line) => { for (const emitted of afterLogoutSnapshots) { expect(emitted.auth.status).not.toBe("authenticated"); } + + // Foreground-skipped startup runtimes populated only via live commands or live config + // while authenticated must also strip "authenticated" before logout + probe failure. + remoteVersion = "1.0.0"; + failProbeSpawn = false; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fgLogoutStarted = yield* Deferred.make(); + const releaseFgLogout = yield* Deferred.make(); + const fgLogoutFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(fgLogoutStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFgLogout)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fgLogoutStarted); + const fgCmdLogoutId = ProviderInstanceId.make("acpRegistry_fg_cmd_logout"); + const fgCfgLogoutId = ProviderInstanceId.make("acpRegistry_fg_cfg_logout"); + const seedAuthFor = (id: ProviderInstanceId) => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: id, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* (yield* seedAuthFor(fgCmdLogoutId)).set(true); + yield* (yield* seedAuthFor(fgCfgLogoutId)).set(true); + const fgCmdInitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdInitDone, Exit.void); + const fgCmdLogoutInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCmdLogoutId, + displayName: "FG Cmd Logout", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCmdInitDone); + const fgCfgInitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCfgInitDone, Exit.void); + const fgCfgLogoutInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCfgLogoutId, + displayName: "FG Cfg Logout", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCfgInitDone); + const fgCmdPopulated = yield* fgCmdLogoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((cmd) => cmd.name === "fg-logout-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgCfgPopulated = yield* fgCfgLogoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "fg-logout-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + fgCmdLogoutId, + { slashCommands: [{ name: "fg-logout-cmd" }], skills: [] }, + v1Identity, + ); + yield* coordinator.publishLiveConfiguration( + fgCfgLogoutId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-logout-model", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "fg-logout-model", name: "fg-logout-model" }, + ], + }), + v1Identity, + ); + expect(Option.getOrThrow(yield* Fiber.join(fgCmdPopulated)).auth.status).toBe( + "authenticated", + ); + expect(Option.getOrThrow(yield* Fiber.join(fgCfgPopulated)).auth.status).toBe( + "authenticated", + ); + yield* Deferred.succeed(releaseFgLogout, undefined); + yield* Fiber.join(fgLogoutFiber); + failProbeSpawn = true; + yield* fgCmdLogoutInstance.acpSessionManagement!.logout(directory); + yield* fgCfgLogoutInstance.acpSessionManagement!.logout(directory); + const fgCmdAfterLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdAfterLogoutDone, Exit.void); + yield* fgCmdLogoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCmdAfterLogoutDone); + const fgCfgAfterLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCfgAfterLogoutDone, Exit.void); + yield* fgCfgLogoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCfgAfterLogoutDone); + const fgCmdAfterLogout = yield* fgCmdLogoutInstance.snapshot.getSnapshot; + expect(fgCmdAfterLogout.auth.status).toBe("unknown"); + expect(fgCmdAfterLogout.slashCommands).toEqual([{ name: "fg-logout-cmd" }]); + const fgCfgAfterLogout = yield* fgCfgLogoutInstance.snapshot.getSnapshot; + expect(fgCfgAfterLogout.auth.status).toBe("unknown"); + expect(fgCfgAfterLogout.models.map((model) => model.slug)).toEqual([ + "model-a", + "fg-logout-model", + ]); useLogoutAgent = false; failProbeSpawn = false; + // Live config update while unauthenticated must not bake "unauthenticated" into + // lastSuccessfulRuntime: signing in again then failing probe promotes back to authenticated. + useAuthLoginAgent = true; + const reauthId = ProviderInstanceId.make("acpRegistry_unauth_live_reauth"); + const reauthStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthStartupDone, Exit.void); + const reauthInstance = yield* AcpRegistryDriver.create({ + instanceId: reauthId, + displayName: "Unauth Live Reauth", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(reauthStartupDone); + yield* TestClock.adjust("16 minutes"); + failProbeAuth = true; + const reauthUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthUnauthDone, Exit.void); + yield* reauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(reauthUnauthDone); + expect((yield* reauthInstance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); + const reauthLiveUpdated = yield* reauthInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "reauth-live-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + reauthId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "reauth-live-model", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "reauth-live-model", name: "reauth-live-model" }, + ], + }), + v1Identity, + ); + expect(Option.getOrThrow(yield* Fiber.join(reauthLiveUpdated)).auth.status).toBe( + "unauthenticated", + ); + failProbeAuth = false; + failProbeSpawn = true; + const reauthAuthFinished = yield* reauthInstance.auth!.subscribe("reauth-owner").pipe( + Stream.filter((state) => state.phase === "succeeded" || state.phase === "failed"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const reauthPostSignInDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthPostSignInDone, Exit.void); + yield* reauthInstance + .auth!.start("reauth-owner", Effect.void, "agent-login") + .pipe(Effect.provideService(Tracer.Tracer, enrichmentTracer)); + expect(Option.getOrThrow(yield* Fiber.join(reauthAuthFinished)).phase).toBe("succeeded"); + yield* Deferred.await(reauthPostSignInDone); + const reauthAfterSignIn = yield* reauthInstance.snapshot.getSnapshot; + expect(reauthAfterSignIn.status).toBe("ready"); + expect(reauthAfterSignIn.auth.status).toBe("authenticated"); + expect(reauthAfterSignIn.models.map((model) => model.slug)).toEqual([ + "model-a", + "reauth-live-model", + ]); + useAuthLoginAgent = false; + failProbeSpawn = false; + // (e) Cold-start direct-publish branch clears saved confirmation when fallback runtime // rejects auth so the next refresh does not flash authenticated. const coldFallbackAuthId = ProviderInstanceId.make("acpRegistry_cold_fallback_unauth"); @@ -5057,6 +5306,7 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); yield* (yield* seedLocalAuth()).set(true); let localFailAuth = true; + let localUseVersionless = false; const localWithLiveStarted = yield* Deferred.make(); const localWithLiveRelease = yield* Deferred.make(); const localWithLiveInterrupted = yield* Deferred.make(); @@ -5083,7 +5333,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { distribution: "local" as const, spawn: { command: process.execPath, - args: localFailAuth ? [authFailAgentPath] : [agentPath, modelsPath], + args: localFailAuth + ? [authFailAgentPath] + : [localUseVersionless ? versionlessLocalAgentPath : agentPath, modelsPath], cwd: directory, env: process.env, }, @@ -5150,6 +5402,71 @@ createInterface({ input: process.stdin }).on("line", (line) => { "unauthenticated", ); expect(yield* (yield* seedLocalAcceptedAuth()).get).toBe(false); + // Version-less local agent (entryIdentity === null): an accepted auth rejection must evict + // the cached probe entry so a live config update cannot revive it on the next refresh. + localUseVersionless = true; + localFailAuth = false; + const localVersionlessId = ProviderInstanceId.make("acpRegistry_local_versionless_cache"); + const localVersionlessReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessReadyDone, Exit.void); + const localVersionlessInstance = yield* AcpRegistryDriver.create({ + instanceId: localVersionlessId, + displayName: "Local Versionless Cache", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessReadyDone); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).version).toBeNull(); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).status).toBe("ready"); + yield* TestClock.adjust("16 minutes"); + localFailAuth = true; + const localVersionlessUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessUnauthDone, Exit.void); + yield* localVersionlessInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessUnauthDone); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + const localVersionlessLive = yield* localVersionlessInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "local-unauth-live"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + localVersionlessId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "local-unauth-live", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "local-unauth-live", name: "local-unauth-live" }, + ], + }), + ); + expect(Option.getOrThrow(yield* Fiber.join(localVersionlessLive)).auth.status).toBe( + "unauthenticated", + ); + const localVersionlessRecheckDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessRecheckDone, Exit.void); + yield* localVersionlessInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessRecheckDone); + const localVersionlessAfter = yield* localVersionlessInstance.snapshot.getSnapshot; + expect(localVersionlessAfter.status).toBe("warning"); + expect(localVersionlessAfter.auth.status).toBe("unauthenticated"); + expect(localVersionlessAfter.message).toContain("API key"); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 7aee09b579a6d..2a6ce70fadf17 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1018,7 +1018,8 @@ export const AcpRegistryDriver: ProviderDriver(null); // Tracks the latest accepted auth result per runtime separately from lastSuccessfulRuntime - // capabilities so a failure on B neither clears A's confirmation nor restores lost confirmation. + // capabilities so an un-adopted failure on B neither clears retained A's confirmation nor + // restores lost confirmation. const latestAcceptedAuth = yield* Ref.make<{ readonly identity: string; readonly auth: ServerProvider["auth"]; @@ -1367,14 +1368,12 @@ export const AcpRegistryDriver: ProviderDriver - confirmedAuthentication - .set(false) - .pipe( - Effect.andThen(clearCachedProbeForRuntime(identity)), - Effect.andThen( - identity === null ? Effect.void : Ref.set(latestAcceptedAuth, { identity, auth }), - ), - ); + clearCachedProbeForRuntime(identity).pipe( + Effect.andThen( + identity === null ? Effect.void : Ref.set(latestAcceptedAuth, { identity, auth }), + ), + Effect.andThen(confirmedAuthentication.set(false)), + ); const isProbeStillCurrent = ( current: AcpRegistryEnrichmentCache, captured: { @@ -1808,25 +1807,35 @@ export const AcpRegistryDriver: ProviderDriver + didPublish + ? Effect.gen(function* () { + if (activeRuntimeUnauthenticated) { + // Clear fallback backoff so a user's sign-in retry probes immediately. + yield* Ref.set(activeFallback, null); + yield* recordAcceptedAuthRejection( + previousIdentity, + provider.auth, + ); + } + yield* Ref.set(expectedRuntimeIdentity, previousIdentity); + yield* Ref.set( + failedUpgradeTarget, + isUpgradeFailure + ? { + targetLaunchIdentity: failedTargetLaunchIdentity, + status: provider.status, + message: provider.message, + } + : null, + ); + }) + : Effect.void, + ), + ), + ); return { published, readiness: published @@ -1843,20 +1852,37 @@ export const AcpRegistryDriver: ProviderDriver + didPublish + ? Effect.gen(function* () { + if (provider.auth.status === "unauthenticated") { + // Adopting failedIdentity with no retained runtime clears + // saved confirmation so refreshes do not flash authenticated. + yield* recordAcceptedAuthRejection( + failedIdentity, + provider.auth, + ); + } + if ( + failedIdentity !== null && + failedIdentity !== previousIdentity + ) { + yield* clearLiveState({ + preserveRuntimeIdentity: failedIdentity, + }); + } + yield* Ref.set(expectedRuntimeIdentity, failedIdentity); + }) + : Effect.void, + ), + ), + ); return { published, readiness: published @@ -1897,111 +1923,140 @@ export const AcpRegistryDriver: ProviderDriver= existingFallback.failedAtMs && - now - existingFallback.failedAtMs < FALLBACK_RETRY_BACKOFF_MS; - yield* Ref.set(activeFallback, { - targetLaunchIdentity: fallbackTargetLaunchIdentity, - targetVersion: fallbackTargetVersion, - targetIndexRevision: fallbackTargetIndexRevision, - fallbackVersion: providerToPublish.version, - fallbackLaunchIdentity: launchIdentity, - failedAtMs: keepFailedAt ? existingFallback.failedAtMs : now, - message: - fallbackMessage ?? - existingFallback?.message ?? - "Using the previously installed version.", - }); - } else if (!fallback && !probeFailed) { - yield* Ref.set(activeFallback, null); - } - if (runtimeChanged) { - yield* clearLiveState({ preserveRuntimeIdentity: resolvedIdentity }); - const retiredAtRevision = - (fallback ? fallbackTargetIndexRevision : indexRevision) ?? - (yield* currentCatalogIndexRevision); - yield* Ref.update(retiredRuntimeIdentities, (retired) => { - const next = new Map(retired); - // Retire only a runtime that actually succeeded; a never-installed - // target replaced during cold fallback stays eligible to reconcile. - if (previousLastSuccessful?.identity === previousIdentity) { - next.set(previousIdentity, retiredAtRevision); - } - next.delete(resolvedIdentity); - return next; - }); - if (appliedLiveConfiguration) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); - } else { - if ( - appliedLiveConfiguration && - nextSnapshot.models !== providerToPublish.models - ) { - yield* Ref.set(learnedModels, nextSnapshot.models); - } - if (resolvedIdentity !== null) { - yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); - yield* Ref.update(retiredRuntimeIdentities, (retired) => { - if (!retired.has(resolvedIdentity)) return retired; - const next = new Map(retired); - next.delete(resolvedIdentity); - return next; - }); - } - yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); - } - if (!probeFailed && resolvedIdentity !== null) { - const { message: _fallbackMsg, ...cleanProvider } = nextSnapshotRaw; - const storedProvider = fallback ? cleanProvider : nextSnapshotRaw; - yield* Ref.set(lastSuccessfulRuntime, { - identity: resolvedIdentity, - provider: { - ...storedProvider, - auth: stripConfirmedAuth(storedProvider.auth), - }, - }); - yield* Ref.set(latestAcceptedAuth, { - identity: resolvedIdentity, - auth: stripConfirmedAuth(nextSnapshot.auth), - }); - } - } - } + const published = yield* Effect.uninterruptible( + tryPublishSnapshot(nextSnapshot).pipe( + Effect.tap((didPublish) => + didPublish + ? Effect.gen(function* () { + if (!providerToPublish.installed) { + yield* Ref.set(activeFallback, null); + yield* Ref.set(failedUpgradeTarget, null); + yield* Ref.set(lastSuccessfulRuntime, null); + yield* Ref.set(latestAcceptedAuth, null); + if (previousIdentity !== null || current.entry !== null) { + yield* clearLiveState(); + yield* invalidateEnrichmentCache; + } + yield* Ref.set(expectedRuntimeIdentity, null); + } else { + const previousLastSuccessful = + yield* Ref.get(lastSuccessfulRuntime); + if (nextSnapshot.auth.status === "unauthenticated") { + yield* recordAcceptedAuthRejection( + resolvedIdentity ?? + runtimeIdentityFor( + providerToPublish, + probedLaunchIdentity, + ), + nextSnapshot.auth, + ); + } + if (!probeFailed) { + yield* Ref.set(failedUpgradeTarget, null); + } + if (fallback && !fromCache) { + const now = yield* Clock.currentTimeMillis; + const keepFailedAt = + existingFallback !== null && + existingFallback.targetLaunchIdentity === + fallbackTargetLaunchIdentity && + now >= existingFallback.failedAtMs && + now - existingFallback.failedAtMs < + FALLBACK_RETRY_BACKOFF_MS; + yield* Ref.set(activeFallback, { + targetLaunchIdentity: fallbackTargetLaunchIdentity, + targetVersion: fallbackTargetVersion, + targetIndexRevision: fallbackTargetIndexRevision, + fallbackVersion: providerToPublish.version, + fallbackLaunchIdentity: launchIdentity, + failedAtMs: keepFailedAt + ? existingFallback.failedAtMs + : now, + message: + fallbackMessage ?? + existingFallback?.message ?? + "Using the previously installed version.", + }); + } else if (!fallback && !probeFailed) { + yield* Ref.set(activeFallback, null); + } + if (runtimeChanged) { + yield* clearLiveState({ + preserveRuntimeIdentity: resolvedIdentity, + }); + const retiredAtRevision = + (fallback ? fallbackTargetIndexRevision : indexRevision) ?? + (yield* currentCatalogIndexRevision); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + const next = new Map(retired); + // Retire only a runtime that actually succeeded; a + // never-installed target replaced during cold fallback + // stays eligible to reconcile. + if (previousLastSuccessful?.identity === previousIdentity) { + next.set(previousIdentity, retiredAtRevision); + } + next.delete(resolvedIdentity); + return next; + }); + if (appliedLiveConfiguration) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } else { + if ( + appliedLiveConfiguration && + nextSnapshot.models !== providerToPublish.models + ) { + yield* Ref.set(learnedModels, nextSnapshot.models); + } + if (resolvedIdentity !== null) { + yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + if (!retired.has(resolvedIdentity)) return retired; + const next = new Map(retired); + next.delete(resolvedIdentity); + return next; + }); + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } + if (!probeFailed && resolvedIdentity !== null) { + const { message: _fallbackMsg, ...cleanProvider } = + nextSnapshotRaw; + const storedProvider = fallback + ? cleanProvider + : nextSnapshotRaw; + yield* Ref.set(lastSuccessfulRuntime, { + identity: resolvedIdentity, + provider: { + ...storedProvider, + auth: stripConfirmedAuth(storedProvider.auth), + }, + }); + yield* Ref.set(latestAcceptedAuth, { + identity: resolvedIdentity, + auth: stripConfirmedAuth(nextSnapshot.auth), + }); + } + } + }) + : Effect.void, + ), + ), + ); return { published, readiness: published @@ -2176,15 +2231,18 @@ export const AcpRegistryDriver: ProviderDriver - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - runtimeIdentity: meta.runtimeIdentity ?? gate.expected, - }), + cache.entry === null && !snapshotChanged + ? cache + : updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + runtimeIdentity: meta.runtimeIdentity ?? gate.expected, + }), ); return undefined; }), From 58a0eb5affa8eae8ab6e03d782b58efb13181a7d Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 22:34:23 +0000 Subject: [PATCH 25/28] fix(acp-registry): fix sidecar recovery-id chains and refresh auth commit race --- .../src/server/AcpRegistrySupport.test.ts | 404 +++++++++++++++++- .../src/server/AcpRegistrySupport.ts | 185 ++++---- .../src/server/driver.test.ts | 138 +++++- .../src/server/driver.ts | 87 ++-- .../src/server/managedProvider.ts | 39 +- 5 files changed, 699 insertions(+), 154 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 09c0a77b2f943..ec72bc9a4c75a 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -5103,6 +5103,7 @@ describe("AcpRegistrySupport", () => { version, }); let upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: ".t3-artifact.json" }); + let extraUpstream: ReturnType | null = null; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -6508,9 +6509,8 @@ describe("AcpRegistrySupport", () => { ); const afterReceiptRepair = JSON.parse( yield* fileSystem.readFileString(edgeReceiptPath), - ) as { readonly launchOptionsRevision?: number; readonly launchOptionsRecoveryId?: string }; + ) as { readonly launchOptionsRevision?: number }; expect(afterReceiptRepair.launchOptionsRevision).toBe(5); - expect(afterReceiptRepair.launchOptionsRecoveryId).toBeDefined(); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", @@ -6531,13 +6531,8 @@ describe("AcpRegistrySupport", () => { yield* freshRepairCat.resolve(settings(), "/workspace"); const afterMatchRepair = JSON.parse(yield* fileSystem.readFileString(edgeReceiptPath)) as { readonly launchOptionsRevision?: number; - readonly launchOptionsRecoveryId?: string; }; expect(afterMatchRepair.launchOptionsRevision).toBe(6); - expect(afterMatchRepair.launchOptionsRecoveryId).toBeDefined(); - expect(afterMatchRepair.launchOptionsRecoveryId).not.toBe( - afterReceiptRepair.launchOptionsRecoveryId, - ); // Corrupt sidecar while lockTimeoutCat holds pending base rev 7 must allocate rev 8 (> 7). yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); upstream = makeBinary("1.0.0", { @@ -6611,6 +6606,392 @@ describe("AcpRegistrySupport", () => { readonly launchOptionsRevision?: number; }; expect(afterObservedRev.launchOptionsRevision).toBe(11); + + // (e) Recovery-ID edge cases: unreadable/corrupt sidecar fallback keeps pending options + // after a sidecar repair, unreadable-sidecar retries preserve the recovery ID, another + // slot's or uninstall's corrupt repair invalidates stale pending options, and receipt + // advances never pair stale pre-repair revisions with post-repair observations. + const recoveryEdgeDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-recovery-edge-", + }); + const recoveryEdgeToolsDir = path.join(recoveryEdgeDir, "tools"); + const recoveryEdgeSidecarPath = path.join( + recoveryEdgeDir, + "acp-registry", + "binary-launch-options.json", + ); + const recoveryEdgeLockPath = `${recoveryEdgeSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const recCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: recoveryEdgeDir, + toolsDir: recoveryEdgeToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* recCatA.resolve(settings(), "/workspace"); + // 1) Corrupt sidecar repaired via sidecar gets a recovery ID; pending options recorded over + // it must survive unreadable or corrupt sidecar fallbacks instead of reverting to --init. + failReceiptTempWrite = true; + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-rec"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--repaired"], + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recCatA.resolve(settings(), "/workspace"); + const savedRepairedSidecar = yield* fileSystem.readFileString(recoveryEdgeSidecarPath); + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pending"], + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + failSidecarRead = true; + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + failSidecarRead = false; + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-after-pending"); + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + // 2) Fast-path observation of a repaired sidecar's recovery ID survives locked io_error, + // subsequent both-unreadable io_error retries, and locked receipt reread errors; a + // corrupt+matching-receipt sync when both writes fail clears stale pending options. + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, savedRepairedSidecar); + const ioChainCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: recoveryEdgeDir, + toolsDir: recoveryEdgeToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fast-path-io"], + }); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + failSidecarReadWhileLockedPath = recoveryEdgeLockPath; + yield* ioChainCat.resolve(settings(), "/workspace"); + failSidecarReadWhileLockedPath = null; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fast-path-io", + ]); + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--both-io-retry"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + injectedReceiptReadFailures = 0; + failReceiptReadWhileLockedPath = recoveryEdgeLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--reread-io-retry"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + failSidecarRead = false; + expect(injectedReceiptReadFailures).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--reread-io-retry", + ]); + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-match-both-fail"); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--init", + ]); + + // 3) Corrupt sidecar repaired by a DIFFERENT agent (or uninstall) wipes example-agent's + // entry; catalog B's rev-1 write gets a fresh recovery ID and beats catalog A's pending. + const otherSlotDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-other-slot-repair-", + }); + const otherSlotToolsDir = path.join(otherSlotDir, "tools"); + const otherSlotSidecarPath = path.join( + otherSlotDir, + "acp-registry", + "binary-launch-options.json", + ); + const otherSettings = () => settings({ agentId: "other-agent" }); + const makeOtherBinary = (version: string, args?: ReadonlyArray) => ({ + ...makeBinary(version, { + archive: archiveBUrl, + cmd: "./bin/other-agent", + ...(args ? { args } : {}), + }), + id: "other-agent", + name: "Other Agent", + }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + extraUpstream = makeOtherBinary("1.0.0", ["--other-init"]); + const otherCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: otherSlotDir, + toolsDir: otherSlotToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const otherCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: otherSlotDir, + toolsDir: otherSlotToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* otherCatA.resolve(settings(), "/workspace"); + yield* otherCatA.resolve(otherSettings(), "/workspace"); + failReceiptTempWrite = true; + for (const arg of ["--a1", "--a2", "--a3"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-pending"], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + // Sidecar corrupts; catalog B repairs it while syncing other-agent, wiping example-agent. + yield* fileSystem.writeFileString(otherSlotSidecarPath, "{corrupt-other-slot"); + extraUpstream = makeOtherBinary("1.0.0", ["--other-repair"]); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(otherSettings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-newer"], + }); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* otherCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-newer", + ]); + // Same check when uninstall of other-agent repairs the corrupt sidecar. + for (const arg of ["--a4", "--a5"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-pending2"], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + yield* fileSystem.writeFileString(otherSlotSidecarPath, "{corrupt-uninstall-repair"); + yield* otherCatB.uninstallManagedBinary({ agentId: "other-agent" }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-after-uninstall"], + }); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* otherCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-after-uninstall", + ]); + extraUpstream = null; + + // 4) When another catalog advances the receipt after a corrupt sidecar and writes a newer + // sidecar, an unreadable-sidecar retry in catalog A must NOT carry its stale higher + // pre-repair baseDurableRevision onto the newer receipt observation. + const obsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-obs-pair-", + }); + const obsToolsDir = path.join(obsDir, "tools"); + const obsSidecarPath = path.join(obsDir, "acp-registry", "binary-launch-options.json"); + const obsLockPath = `${obsSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const obsCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: obsDir, + toolsDir: obsToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const obsCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: obsDir, + toolsDir: obsToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* obsCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--r1"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + for (const arg of ["--s2", "--s3", "--s4"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-old"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + // Corrupt sidecar; B repairs receipt to rev 2 and writes sidecar rev 3. + yield* fileSystem.writeFileString(obsSidecarPath, "{corrupt-obs"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-r2"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-s3"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + // With sidecar unreadable, A retries on top of receipt rev 2; once readable, B's rev 3 wins. + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-io-after-r2"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + injectedReceiptReadFailures = 0; + failReceiptReadWhileLockedPath = obsLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-reread-after-r2"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + failSidecarRead = false; + expect(injectedReceiptReadFailures).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + // Restore upstream to --commit-8 before step 5 below. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); // 5) Fast-path hasMatchingPending gating: reverting to matching receipt --commit-8 clears // earlier pending options instead of short-circuiting and leaving them active. failReceiptTempWrite = true; @@ -6987,7 +7368,14 @@ describe("AcpRegistrySupport", () => { layerResolver((request) => { if (request.url === registryUrl) { return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(upstream))), + HttpClientResponse.fromWeb( + request, + new Response( + extraUpstream === null + ? makeRegistry(upstream) + : JSON.stringify({ version: "1.0.0", agents: [upstream, extraUpstream] }), + ), + ), ); } if (request.url === archiveFailUrl) { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 8faa30459b661..c09f253951f29 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -952,7 +952,6 @@ function encodeBinaryArtifactReceipt( target: typeof AcpRegistryBinaryTarget.Type, options?: { readonly launchOptionsRevision?: number; - readonly launchOptionsRecoveryId?: string; readonly installId?: string; }, ): string { @@ -966,9 +965,6 @@ function encodeBinaryArtifactReceipt( ...(options?.launchOptionsRevision !== undefined ? { launchOptionsRevision: options.launchOptionsRevision } : {}), - ...(options?.launchOptionsRecoveryId !== undefined - ? { launchOptionsRecoveryId: options.launchOptionsRecoveryId } - : {}), ...(options?.installId !== undefined ? { installId: options.installId } : {}), }); } @@ -2751,8 +2747,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const pendingEntry = pendingLaunchOptionsBySlotRoot.get(slot.root); const hasMatchingPending = pendingEntry !== undefined && receiptMatchesInstall(pendingEntry.receipt, initialReceipt); - const initialPriorReceiptBase = hasMatchingPending ? pendingEntry.baseReceiptRevision : 0; - const initialPriorPendingBase = hasMatchingPending ? pendingEntry.baseDurableRevision : 0; const receiptRev = initialReceipt.launchOptionsRevision ?? 0; let fastPathSidecarReadOk = false; let observedDiskRev = 0; @@ -2788,6 +2782,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); + type PendingBase = { + readonly baseReceiptRevision: number; + readonly baseDurableRevision: number; + readonly baseRecoveryId: string | null; + }; const buildLaunchOptionsReceipt = ( baseReceipt: AcpRegistryBinaryArtifactReceipt, revision?: number, @@ -2803,41 +2802,44 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ...(recoveryId ? { launchOptionsRecoveryId: recoveryId } : {}), ...(baseReceipt.installId !== undefined ? { installId: baseReceipt.installId } : {}), }); - const recordPending = ( - baseReceipt: AcpRegistryBinaryArtifactReceipt, - baseReceiptRevision: number, - baseDurableRevision: number, - baseRecoveryId: string | null, - ) => { + const recordPending = (baseReceipt: AcpRegistryBinaryArtifactReceipt, base: PendingBase) => { pendingLaunchOptionsBySlotRoot.set(slot.root, { - baseReceiptRevision, - baseDurableRevision, - baseRecoveryId, + ...base, receipt: buildLaunchOptionsReceipt(baseReceipt), }); }; - const resolvePendingRecoveryId = ( - baseReceipt: AcpRegistryBinaryArtifactReceipt, + // Keep baseDurableRevision and baseRecoveryId paired from the same observation/chain so a + // pre-repair sidecar revision never gates a newer receipt or post-repair sidecar chain. + const resolvePendingBaseOnUnreadableSidecar = ( baseReceiptRev: number, - priorPending: - | { - readonly baseReceiptRevision: number; - readonly baseDurableRevision: number; - readonly baseRecoveryId: string | null; - } - | undefined, - ): string | null => { + priorPending: PendingBase | undefined, + ): PendingBase => { if (fastPathSidecarReadOk && observedDiskRev > baseReceiptRev) { - return observedDiskRecoveryId; + const sameChain = + priorPending !== undefined && + baseReceiptRev <= priorPending.baseReceiptRevision && + priorPending.baseRecoveryId === observedDiskRecoveryId; + return { + baseReceiptRevision: Math.max( + baseReceiptRev, + sameChain ? priorPending.baseReceiptRevision : 0, + ), + baseDurableRevision: Math.max( + baseReceiptRev, + observedDiskRev, + sameChain ? priorPending.baseDurableRevision : 0, + ), + baseRecoveryId: observedDiskRecoveryId, + }; } - if ( - priorPending !== undefined && - baseReceiptRev <= priorPending.baseReceiptRevision && - priorPending.baseDurableRevision > baseReceiptRev - ) { - return priorPending.baseRecoveryId; + if (priorPending !== undefined && baseReceiptRev <= priorPending.baseReceiptRevision) { + return priorPending; } - return baseReceipt.launchOptionsRecoveryId ?? null; + return { + baseReceiptRevision: baseReceiptRev, + baseDurableRevision: baseReceiptRev, + baseRecoveryId: null, + }; }; const recordPendingForInitialReceipt = () => { const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); @@ -2848,15 +2850,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct : undefined; recordPending( initialReceipt, - Math.max(receiptRev, initialPriorReceiptBase, matchingPending?.baseReceiptRevision ?? 0), - Math.max( - receiptRev, - observedDiskRev, - initialPriorPendingBase, - matchingPending?.baseDurableRevision ?? 0, - ), - resolvePendingRecoveryId( - initialReceipt, + resolvePendingBaseOnUnreadableSidecar( receiptRev, matchingPending ?? (hasMatchingPending ? pendingEntry : undefined), ), @@ -2889,15 +2883,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct receiptMatchesInstall(currentPending.receipt, freshReceipt) ? currentPending : undefined; - const effectiveReceiptBase = Math.max( - freshReceiptRev, - matchingPending?.baseReceiptRevision ?? 0, - ); - const effectiveObservedBase = Math.max( - freshReceiptRev, - observedDiskRev, - matchingPending?.baseDurableRevision ?? 0, - ); const diskResult = yield* readBinaryLaunchOptionsFile( fileSystem, binaryLaunchOptionsPath, @@ -2907,9 +2892,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct // pending until the sidecar can be read and reconciled under the lock. recordPending( freshReceipt, - effectiveReceiptBase, - effectiveObservedBase, - resolvePendingRecoveryId(freshReceipt, freshReceiptRev, matchingPending), + resolvePendingBaseOnUnreadableSidecar(freshReceiptRev, matchingPending), ); return; } @@ -2918,10 +2901,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const diskStored = diskEntries[slot.root]; const diskMatches = receiptMatchesInstall(diskStored, freshReceipt); const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; - const currentDurableRecoveryId = - !isCorrupt && diskMatches && freshDiskRev > freshReceiptRev - ? (diskStored.launchOptionsRecoveryId ?? null) - : (freshReceipt.launchOptionsRecoveryId ?? null); + const sidecarIsAuthoritative = + !isCorrupt && diskMatches && freshDiskRev > freshReceiptRev; + const currentSidecarRecoveryId = sidecarIsAuthoritative + ? (diskStored.launchOptionsRecoveryId ?? null) + : null; if (!isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { if (diskStored === undefined) { pendingLaunchOptionsBySlotRoot.delete(slot.root); @@ -2943,27 +2927,43 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct pendingLaunchOptionsBySlotRoot.delete(slot.root); return; } - const committedBaseRev = Math.max(effectiveObservedBase, freshDiskRev); - const nextRevision = committedBaseRev + 1; + const allocationBaseRev = Math.max( + freshReceiptRev, + observedDiskRev, + freshDiskRev, + matchingPending?.baseDurableRevision ?? 0, + ); + const nextRevision = allocationBaseRev + 1; + const lockedPendingBase = (): PendingBase => { + if (sidecarIsAuthoritative) { + const sameChain = + matchingPending !== undefined && + freshReceiptRev <= matchingPending.baseReceiptRevision && + matchingPending.baseRecoveryId === currentSidecarRecoveryId; + return { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: Math.max( + freshReceiptRev, + freshDiskRev, + sameChain ? matchingPending.baseDurableRevision : 0, + ), + baseRecoveryId: currentSidecarRecoveryId, + }; + } + return { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: freshReceiptRev, + baseRecoveryId: null, + }; + }; if (!(yield* isLockOwned)) { if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - recordPending( - freshReceipt, - effectiveReceiptBase, - committedBaseRev, - currentDurableRecoveryId, - ); + recordPending(freshReceipt, lockedPendingBase()); } return; } - const nextRecoveryId = isCorrupt ? yield* random.uuidV4() : currentDurableRecoveryId; - const updatedReceipt = buildLaunchOptionsReceipt( - freshReceipt, - nextRevision, - nextRecoveryId, - ); const receiptWrite = yield* Effect.result( random.uuidV4().pipe( Effect.flatMap((id) => { @@ -2973,9 +2973,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct temporaryPath, encodeBinaryArtifactReceipt(agent, target, { launchOptionsRevision: nextRevision, - ...(nextRecoveryId !== null - ? { launchOptionsRecoveryId: nextRecoveryId } - : {}), ...(freshReceipt.installId !== undefined ? { installId: freshReceipt.installId } : {}), @@ -3011,12 +3008,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - recordPending( - freshReceipt, - effectiveReceiptBase, - committedBaseRev, - currentDurableRecoveryId, - ); + recordPending(freshReceipt, lockedPendingBase()); } return; } @@ -3025,10 +3017,21 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) .pipe(Effect.ignore); } + // Stamp a fresh recovery ID whenever starting a new sidecar chain (including after + // corrupt repair by this or any other slot) so older higher-base pending options yield. + const nextSidecarRecoveryId = + sidecarIsAuthoritative && currentSidecarRecoveryId !== null + ? currentSidecarRecoveryId + : yield* random.uuidV4(); + const updatedSidecarReceipt = buildLaunchOptionsReceipt( + freshReceipt, + nextRevision, + nextSidecarRecoveryId, + ); const sidecarWrite = yield* Effect.result( writeJsonFileAtomically(binaryLaunchOptionsPath, { ...diskEntries, - [slot.root]: updatedReceipt, + [slot.root]: updatedSidecarReceipt, }), ); if (Result.isSuccess(sidecarWrite)) { @@ -3036,12 +3039,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } else if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { pendingLaunchOptionsBySlotRoot.delete(slot.root); } else { - recordPending( - freshReceipt, - effectiveReceiptBase, - committedBaseRev, - currentDurableRecoveryId, - ); + recordPending(freshReceipt, lockedPendingBase()); } }), ).pipe( @@ -3758,11 +3756,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (Option.isNone(validated)) continue; const diskOverride = diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; - const durableReceipt = + const durableFromSidecar = receiptMatchesInstall(diskOverride, receipt) && - (diskOverride.launchOptionsRevision ?? 0) > (receipt.launchOptionsRevision ?? 0) - ? diskOverride - : receipt; + (diskOverride.launchOptionsRevision ?? 0) > (receipt.launchOptionsRevision ?? 0); + const durableReceipt = durableFromSidecar ? diskOverride : receipt; const pendingOverride = pendingLaunchOptionsBySlotRoot.get(dir); const effectiveReceipt = pendingOverride !== undefined && @@ -3770,7 +3767,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (receipt.launchOptionsRevision ?? 0) <= pendingOverride.baseReceiptRevision && (durableReceipt.launchOptionsRevision ?? 0) <= pendingOverride.baseDurableRevision && - (durableReceipt.launchOptionsRecoveryId ?? null) === pendingOverride.baseRecoveryId + (!durableFromSidecar || + (durableReceipt.launchOptionsRecoveryId ?? null) === + pendingOverride.baseRecoveryId) ? pendingOverride.receipt : durableReceipt; const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index b5d32d325fafa..e87eb27ae0e00 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3675,6 +3675,10 @@ createInterface({ input: process.stdin }).on("line", (line) => { readonly matchName: string; readonly done: Deferred.Deferred; } | null = null; + let onConfigHandled: { + readonly matchModelId: string; + readonly done: Deferred.Deferred; + } | null = null; let onEnrichmentEnd: (() => void) | null = null; let onReconcileEnd: ((exit: Exit.Exit) => void) | null = null; const enrichmentTracer: Tracer.Tracer = { @@ -3738,6 +3742,24 @@ createInterface({ input: process.stdin }).on("line", (line) => { }), ), ), + watchLiveConfiguration: (instanceId, onUpdate) => + baseCoordinator.watchLiveConfiguration(instanceId, (configuration, meta) => + onUpdate(configuration, meta).pipe( + Effect.tap(() => { + if ( + onConfigHandled !== null && + configuration.models.some( + (model) => model.id === onConfigHandled!.matchModelId, + ) + ) { + const handled = onConfigHandled; + onConfigHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), }; const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir: directory, @@ -5307,6 +5329,11 @@ createInterface({ input: process.stdin }).on("line", (line) => { yield* (yield* seedLocalAuth()).set(true); let localFailAuth = true; let localUseVersionless = false; + let localProbeCount = 0; + let localResolveGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; const localWithLiveStarted = yield* Deferred.make(); const localWithLiveRelease = yield* Deferred.make(); const localWithLiveInterrupted = yield* Deferred.make(); @@ -5319,15 +5346,24 @@ createInterface({ input: process.stdin }).on("line", (line) => { distribution: "local", }), resolve: (_settings, _cwd, environment) => - Effect.sync(() => { - if (environment?.MISE_OFFLINE === "1" && !localGateArmed) { - localGateArmed = true; - getAvailableCommandsGate = { - instanceId: localUnauthId, - started: localWithLiveStarted, - release: localWithLiveRelease, - interrupted: localWithLiveInterrupted, - }; + Effect.gen(function* () { + if (environment?.MISE_OFFLINE === "1") { + localProbeCount += 1; + if (!localGateArmed) { + localGateArmed = true; + getAvailableCommandsGate = { + instanceId: localUnauthId, + started: localWithLiveStarted, + release: localWithLiveRelease, + interrupted: localWithLiveInterrupted, + }; + } + if (localResolveGate !== null) { + const gate = localResolveGate; + localResolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } } return { distribution: "local" as const, @@ -5444,6 +5480,11 @@ createInterface({ input: process.stdin }).on("line", (line) => { Stream.runHead, Effect.forkScoped({ startImmediately: true }), ); + const localVersionlessConfigHandled = yield* Deferred.make(); + onConfigHandled = { + matchModelId: "local-unauth-live", + done: localVersionlessConfigHandled, + }; yield* coordinator.publishLiveConfiguration( localVersionlessId, normalizeAcpRegistryLiveConfiguration([], undefined, { @@ -5457,16 +5498,95 @@ createInterface({ input: process.stdin }).on("line", (line) => { expect(Option.getOrThrow(yield* Fiber.join(localVersionlessLive)).auth.status).toBe( "unauthenticated", ); + // Wait until the watcher callback finishes (including cache update) before refreshing. + yield* Deferred.await(localVersionlessConfigHandled); + const probesBeforeRecheck = localProbeCount; const localVersionlessRecheckDone = yield* Deferred.make(); onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessRecheckDone, Exit.void); yield* localVersionlessInstance.snapshot.refresh.pipe( Effect.provideService(Tracer.Tracer, enrichmentTracer), ); yield* Deferred.await(localVersionlessRecheckDone); + expect(localProbeCount).toBe(probesBeforeRecheck + 1); const localVersionlessAfter = yield* localVersionlessInstance.snapshot.getSnapshot; expect(localVersionlessAfter.status).toBe("warning"); expect(localVersionlessAfter.auth.status).toBe("unauthenticated"); expect(localVersionlessAfter.message).toContain("API key"); + + // (g) A refresh checkProvider that read confirmedAuthentication=true before an in-flight + // enrichment probe accepted an auth rejection must NOT commit auth.status="authenticated". + const raceAuthId = ProviderInstanceId.make("acpRegistry_check_vs_reject_race"); + const seedRaceAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: raceAuthId, + settings: localUnauthSettings, + environment: localUnauthEnv, + processEnvironment: process.env, + }); + yield* (yield* seedRaceAuth()).set(true); + localFailAuth = true; + const raceProbeStarted = yield* Deferred.make(); + const raceProbeRelease = yield* Deferred.make(); + localResolveGate = { started: raceProbeStarted, release: raceProbeRelease }; + const raceAuthInstance = yield* AcpRegistryDriver.create({ + instanceId: raceAuthId, + displayName: "Check vs Reject Race", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(raceProbeStarted); + const raceCheckStarted = yield* Deferred.make(); + const raceCheckRelease = yield* Deferred.make(); + const raceCheckInterrupted = yield* Deferred.make(); + getAvailableCommandsGate = { + instanceId: raceAuthId, + started: raceCheckStarted, + release: raceCheckRelease, + interrupted: raceCheckInterrupted, + }; + const raceRefreshFiber = yield* raceAuthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.forkScoped({ startImmediately: true }), + ); + // Refresh gen 2 already observed confirmedAuthentication=true and paused in checkProvider. + yield* Deferred.await(raceCheckStarted); + const raceGen1RejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(raceGen1RejectDone, Exit.void); + yield* Deferred.succeed(raceProbeRelease, undefined); + yield* Deferred.await(raceGen1RejectDone); + expect((yield* raceAuthInstance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); + expect(yield* (yield* seedRaceAuth()).get).toBe(false); + const raceSnapsAfterReject: Array = []; + const raceCollector = yield* raceAuthInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + raceSnapsAfterReject.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const raceGen2Done = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(raceGen2Done, Exit.void); + yield* Deferred.succeed(raceCheckRelease, undefined); + yield* Fiber.join(raceRefreshFiber); + yield* Deferred.await(raceGen2Done); + yield* Fiber.interrupt(raceCollector); + expect(raceSnapsAfterReject.length).toBeGreaterThan(0); + for (const emitted of raceSnapsAfterReject) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + const raceFinal = yield* raceAuthInstance.snapshot.getSnapshot; + expect(raceFinal.status).toBe("warning"); + expect(raceFinal.auth.status).toBe("unauthenticated"); }).pipe(Effect.scoped, Effect.provide(driverLayer)), ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 2a6ce70fadf17..93736dcf65b42 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1367,12 +1367,22 @@ export const AcpRegistryDriver: ProviderDriver + Effect.uninterruptible( + Effect.sync(() => { + latestAuthConfirmed = authenticated; + }).pipe(Effect.andThen(confirmedAuthentication.set(authenticated))), + ); + const markAuthConfirmationCleared = () => { + latestAuthConfirmed = false; + }; const recordAcceptedAuthRejection = (identity: string | null, auth: ServerProvider["auth"]) => clearCachedProbeForRuntime(identity).pipe( Effect.andThen( identity === null ? Effect.void : Ref.set(latestAcceptedAuth, { identity, auth }), ), - Effect.andThen(confirmedAuthentication.set(false)), + Effect.andThen(setConfirmedAuth(false)), ); const isProbeStillCurrent = ( current: AcpRegistryEnrichmentCache, @@ -1529,6 +1539,10 @@ export const AcpRegistryDriver: ProviderDriver buildInitialAcpRegistrySnapshot(readinessInput), checkProvider, + reconcileCheckedSnapshot: ({ probed }) => + !latestAuthConfirmed && probed.auth.status === "authenticated" + ? { ...probed, auth: stripConfirmedAuth(probed.auth) } + : probed, enrichSnapshot: Effect.fn("enrichSnapshot")(function* ({ snapshot, getSnapshot, @@ -1808,7 +1822,12 @@ export const AcpRegistryDriver: ProviderDriver didPublish ? Effect.gen(function* () { @@ -1857,7 +1876,12 @@ export const AcpRegistryDriver: ProviderDriver didPublish ? Effect.gen(function* () { @@ -1937,7 +1961,13 @@ export const AcpRegistryDriver: ProviderDriver didPublish ? Effect.gen(function* () { @@ -2536,14 +2566,10 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore .withPermit( - confirmedAuthentication - .set(authenticated) - .pipe( - Effect.andThen( - authenticated ? Ref.set(latestAcceptedAuth, null) : clearLiveState(), - ), - Effect.andThen(invalidateEnrichmentCache), - ), + setConfirmedAuth(authenticated).pipe( + Effect.andThen(authenticated ? Ref.set(latestAcceptedAuth, null) : clearLiveState()), + Effect.andThen(invalidateEnrichmentCache), + ), ) .pipe(Effect.andThen(snapshot.refresh), Effect.asVoid), }).pipe( @@ -2556,9 +2582,10 @@ export const AcpRegistryDriver: ProviderDriver liveSnapshotSemaphore.withPermit( - confirmedAuthentication - .set(false) - .pipe( - Effect.andThen(Ref.set(latestAcceptedAuth, null)), - Effect.andThen(invalidateEnrichmentCache), - Effect.andThen( - Option.isSome(runtimeCoordinator) - ? Effect.all( - [ - runtimeCoordinator.value.clearAvailableCommands(instanceId), - runtimeCoordinator.value.clearLiveConfiguration(instanceId), - ], - { concurrency: "unbounded", discard: true }, - ) - : Effect.void, - ), + setConfirmedAuth(false).pipe( + Effect.andThen(Ref.set(latestAcceptedAuth, null)), + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen( + Option.isSome(runtimeCoordinator) + ? Effect.all( + [ + runtimeCoordinator.value.clearAvailableCommands(instanceId), + runtimeCoordinator.value.clearLiveConfiguration(instanceId), + ], + { concurrency: "unbounded", discard: true }, + ) + : Effect.void, ), + ), ), ), ); diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 02f7fb1fa1649..af85c10dd06ed 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -69,8 +69,15 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly snapshot: ServerProvider; readonly getSnapshot: Effect.Effect; readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; - readonly tryPublishSnapshot: (snapshot: ServerProvider) => Effect.Effect; + readonly tryPublishSnapshot: ( + snapshot: ServerProvider, + onAccepted?: () => void, + ) => Effect.Effect; }) => Effect.Effect; + readonly reconcileCheckedSnapshot?: (input: { + readonly probed: ServerProvider; + readonly current: ServerProvider; + }) => ServerProvider; readonly refreshInterval?: Duration.Input; readonly refreshOnInterval?: boolean | ((snapshot: ServerProvider) => boolean); readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean; @@ -102,6 +109,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* ( generation: number, nextSnapshot: ServerProvider, + onAccepted?: () => void, ): Effect.fn.Return { const outcome = yield* Ref.modify(snapshotStateRef, (state) => { let applied = true; @@ -110,6 +118,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( if (state.enrichmentGeneration !== generation) { applied = false; } else { + onAccepted?.(); // Enrichment must not revert usage updates newer than its input snapshot. const merged = withUsageLimits( state.usageAuthLabel === undefined @@ -154,7 +163,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot).pipe(Effect.asVoid), - tryPublishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot), + tryPublishSnapshot: (nextSnapshot, onAccepted) => + publishEnrichedSnapshot(generation, nextSnapshot, onAccepted), }) .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope)); @@ -216,38 +226,41 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const generation = input.enrichSnapshot ? state.enrichmentGeneration + 1 : state.enrichmentGeneration; + const checkedSnapshot = input.reconcileCheckedSnapshot + ? input.reconcileCheckedSnapshot({ probed: probedSnapshot, current: state.snapshot }) + : probedSnapshot; // Failed reads retain limits only for the same account and original workspace. const previous = state.snapshot.auth; const differs = (a: string | undefined, b: string | undefined) => a !== undefined && b !== undefined && a !== b; const switchedAccount = - differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) || - (probedSnapshot.auth.workspaceId !== undefined && - probedSnapshot.auth.workspaceId !== previous.workspaceId); + differs(checkedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) || + (checkedSnapshot.auth.workspaceId !== undefined && + checkedSnapshot.auth.workspaceId !== previous.workspaceId); const usageLimits = switchedAccount - ? probedSnapshot.usageLimits - : probedSnapshot.usageLimits === undefined && + ? checkedSnapshot.usageLimits + : checkedSnapshot.usageLimits === undefined && state.snapshot.usageLimits !== usageBeforeProbe ? state.snapshot.usageLimits : resolveUsageLimitsAfterProbe({ published: state.snapshot.usageLimits, - probed: probedSnapshot.usageLimits, + probed: checkedSnapshot.usageLimits, }); const workspaceId = - usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId; + usageLimits === checkedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId; const usageAuthLabel = !switchedAccount && usageLimits?.checkedAt === state.snapshot.usageLimits?.checkedAt ? state.usageAuthLabel : undefined; const labeledProbe = usageAuthLabel === undefined - ? probedSnapshot + ? checkedSnapshot : { - ...probedSnapshot, - auth: { ...probedSnapshot.auth, label: usageAuthLabel ?? undefined }, + ...checkedSnapshot, + auth: { ...checkedSnapshot.auth, label: usageAuthLabel ?? undefined }, }; const snapshot = withUsageLimits( - workspaceId && !probedSnapshot.auth.workspaceId + workspaceId && !checkedSnapshot.auth.workspaceId ? { ...labeledProbe, auth: { ...labeledProbe.auth, workspaceId } } : labeledProbe, usageLimits, From c10597579b80989424d71736c2d5c9e967669a16 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:04:47 +0000 Subject: [PATCH 26/28] fix(acp-registry): retire superseded pending options on fallback and simplify recovery state --- .../src/server/AcpRegistrySupport.test.ts | 222 ++++++++++++++---- .../src/server/AcpRegistrySupport.ts | 65 ++--- .../src/server/driver.test.ts | 8 + .../src/server/driver.ts | 2 +- .../src/server/managedProvider.ts | 7 +- 5 files changed, 214 insertions(+), 90 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index ec72bc9a4c75a..af2dd9ca037c0 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -6449,13 +6449,36 @@ describe("AcpRegistrySupport", () => { "--lock-c-timeout2", ]); // Corrupt sidecar repaired by a fresh catalog (via sidecar OR receipt OR matching receipt) - // must outrank lockTimeoutCat's older higher-base pending entry via launchOptionsRecoveryId. + // must outrank older higher-base pending entries via launchOptionsRecoveryId / receipt rev. const savedSidecarBeforeCorrupt = yield* fileSystem.readFileString(edgeSyncSidecarPath); - const freshRepairCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: edgeSyncDir, - toolsDir: edgeSyncToolsDir, - registryUrl, - }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const makeEdgePendingCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const staleSidecarCat = yield* makeEdgePendingCat(); + const staleSidecarNormalCat = yield* makeEdgePendingCat(); + const staleReceiptCat = yield* makeEdgePendingCat(); + const freshRepairCat = yield* makeEdgePendingCat(); + failReceiptTempWrite = true; + failSidecarWrite = true; + for (const [cat, arg] of [ + [staleSidecarCat, "--stale-sidecar-pending"], + [staleSidecarNormalCat, "--stale-sidecar-normal"], + [staleReceiptCat, "--stale-receipt-pending"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } + failReceiptTempWrite = false; + failSidecarWrite = false; // (i) Sidecar repair (rev 5 < pending base 7) and subsequent normal write (rev 6 < 7). yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); failReceiptTempWrite = true; @@ -6470,9 +6493,9 @@ describe("AcpRegistrySupport", () => { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - yield* lockTimeoutCat.invalidateIndex(); - yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + yield* staleSidecarCat.invalidateIndex(); + yield* staleSidecarCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleSidecarCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--fresh-b-sidecar-repair", ]); upstream = makeBinary("1.0.0", { @@ -6488,11 +6511,11 @@ describe("AcpRegistrySupport", () => { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - yield* lockTimeoutCat.invalidateIndex(); - yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ - "--fresh-b-sidecar-rev6", - ]); + yield* staleSidecarNormalCat.invalidateIndex(); + yield* staleSidecarNormalCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleSidecarNormalCat.resolve(settings(), "/workspace")).spawn.args).toEqual( + ["--fresh-b-sidecar-rev6"], + ); // (ii) Receipt repair (rev 5 < pending base 7) and matching-receipt repair on corrupt file. yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); upstream = makeBinary("1.0.0", { @@ -6515,9 +6538,9 @@ describe("AcpRegistrySupport", () => { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - yield* lockTimeoutCat.invalidateIndex(); - yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + yield* staleReceiptCat.invalidateIndex(); + yield* staleReceiptCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleReceiptCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ "--fresh-b-receipt-repair", ]); yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar-match"); @@ -6821,6 +6844,18 @@ describe("AcpRegistrySupport", () => { yield* otherCatB.invalidateIndex(); yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* otherCatB.resolve(otherSettings(), "/workspace"); + expect(yield* fileSystem.readFileString(`${otherSlotSidecarPath}.corrupt`)).toBe( + "{corrupt-other-slot", + ); + const repairedByOtherEntries = JSON.parse( + yield* fileSystem.readFileString(otherSlotSidecarPath), + ) as Record }>; + expect( + Object.keys(repairedByOtherEntries).every((key) => key.includes("other-agent")), + ).toBe(true); + expect(Object.values(repairedByOtherEntries).map((entry) => entry.args)).toEqual([ + ["--other-repair"], + ]); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -6861,6 +6896,10 @@ describe("AcpRegistrySupport", () => { failSidecarWrite = false; yield* fileSystem.writeFileString(otherSlotSidecarPath, "{corrupt-uninstall-repair"); yield* otherCatB.uninstallManagedBinary({ agentId: "other-agent" }); + expect(yield* fileSystem.readFileString(`${otherSlotSidecarPath}.corrupt`)).toBe( + "{corrupt-uninstall-repair", + ); + expect(JSON.parse(yield* fileSystem.readFileString(otherSlotSidecarPath))).toEqual({}); upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", @@ -6882,8 +6921,9 @@ describe("AcpRegistrySupport", () => { extraUpstream = null; // 4) When another catalog advances the receipt after a corrupt sidecar and writes a newer - // sidecar, an unreadable-sidecar retry in catalog A must NOT carry its stale higher - // pre-repair baseDurableRevision onto the newer receipt observation. + // sidecar, an unreadable-sidecar retry (and locked receipt reread) in catalog A must + // NOT carry stale pre-repair baseDurableRevision; same-chain newer sidecar writes beat + // and retire pending options, and a receipt advance resets lockedPendingBase cleanly. const obsDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-registry-obs-pair-", }); @@ -6895,25 +6935,102 @@ describe("AcpRegistrySupport", () => { cmd: "./bin/example-agent", args: ["--init"], }); - const obsCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: obsDir, - toolsDir: obsToolsDir, - registryUrl, - }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); - const obsCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: obsDir, - toolsDir: obsToolsDir, - registryUrl, - }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const makeObsCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: obsDir, + toolsDir: obsToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const obsCatA = yield* makeObsCat(); + const obsCatA2 = yield* makeObsCat(); + const obsCatB = yield* makeObsCat(); + yield* obsCatA.resolve(settings(), "/workspace"); + // Same-chain newer sidecar write beats and retires catalog A's pending entry (so a later + // unreadable sidecar cannot resurrect the retired pending entry). + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--same-chain-1"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-stale-same-chain"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-newer-same-chain"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-newer-same-chain", + ]); + failSidecarRead = true; + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--init"]); + failSidecarRead = false; + // Receipt advance pruning the sidecar resets lockedPendingBase when both writes later fail. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-before-r-prune"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent", args: ["--r1"], }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-after-r-prune"], + }); yield* obsCatA.invalidateIndex(); yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-after-r-prune", + ]); + // Build sidecar revs on top of receipt rev 3, record pending on BOTH obsCatA and obsCatA2, + // then let B repair receipt + write a lower-rev sidecar; test io_error and receipt reread. failReceiptTempWrite = true; for (const arg of ["--s2", "--s3", "--s4"]) { upstream = makeBinary("1.0.0", { @@ -6926,17 +7043,22 @@ describe("AcpRegistrySupport", () => { yield* obsCatA.resolve(settings(), "/workspace"); } failSidecarWrite = true; - upstream = makeBinary("1.0.0", { - archive: archiveAUrl, - cmd: "./bin/example-agent", - args: ["--a-old"], - }); - yield* obsCatA.invalidateIndex(); - yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - yield* obsCatA.resolve(settings(), "/workspace"); + for (const [cat, arg] of [ + [obsCatA, "--a-old"], + [obsCatA2, "--a-old-2"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } failReceiptTempWrite = false; failSidecarWrite = false; - // Corrupt sidecar; B repairs receipt to rev 2 and writes sidecar rev 3. + // Corrupt sidecar; B repairs receipt to rev 4 and writes sidecar rev 5 (< A's old base 6). yield* fileSystem.writeFileString(obsSidecarPath, "{corrupt-obs"); upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -6956,7 +7078,7 @@ describe("AcpRegistrySupport", () => { yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatB.resolve(settings(), "/workspace"); failReceiptTempWrite = false; - // With sidecar unreadable, A retries on top of receipt rev 2; once readable, B's rev 3 wins. + // (i) Locked sidecar io_error path on obsCatA: verify fallback immediately picks --b-s3. failSidecarRead = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -6966,6 +7088,16 @@ describe("AcpRegistrySupport", () => { yield* obsCatA.invalidateIndex(); yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatA.resolve(settings(), "/workspace"); + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + // (ii) Locked receipt-reread path on obsCatA2: verify fault count and --b-s3 on fallback. + failSidecarRead = true; injectedReceiptReadFailures = 0; failReceiptReadWhileLockedPath = obsLockPath; upstream = makeBinary("1.0.0", { @@ -6973,9 +7105,9 @@ describe("AcpRegistrySupport", () => { cmd: "./bin/example-agent", args: ["--a-reread-after-r2"], }); - yield* obsCatA.invalidateIndex(); - yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - yield* obsCatA.resolve(settings(), "/workspace"); + yield* obsCatA2.invalidateIndex(); + yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA2.resolve(settings(), "/workspace"); failReceiptReadWhileLockedPath = null; failSidecarRead = false; expect(injectedReceiptReadFailures).toBe(1); @@ -6983,9 +7115,9 @@ describe("AcpRegistrySupport", () => { archive: archiveFailUrl, cmd: "./bin/example-agent", }); - yield* obsCatA.invalidateIndex(); - yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); - expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + yield* obsCatA2.invalidateIndex(); + yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA2.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); // Restore upstream to --commit-8 before step 5 below. upstream = makeBinary("1.0.0", { archive: archiveAUrl, diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index c09f253951f29..60fe4a896bfb5 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -2815,20 +2815,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct priorPending: PendingBase | undefined, ): PendingBase => { if (fastPathSidecarReadOk && observedDiskRev > baseReceiptRev) { - const sameChain = - priorPending !== undefined && - baseReceiptRev <= priorPending.baseReceiptRevision && - priorPending.baseRecoveryId === observedDiskRecoveryId; return { - baseReceiptRevision: Math.max( - baseReceiptRev, - sameChain ? priorPending.baseReceiptRevision : 0, - ), - baseDurableRevision: Math.max( - baseReceiptRev, - observedDiskRev, - sameChain ? priorPending.baseDurableRevision : 0, - ), + baseReceiptRevision: baseReceiptRev, + baseDurableRevision: observedDiskRev, baseRecoveryId: observedDiskRecoveryId, }; } @@ -2934,28 +2923,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct matchingPending?.baseDurableRevision ?? 0, ); const nextRevision = allocationBaseRev + 1; - const lockedPendingBase = (): PendingBase => { - if (sidecarIsAuthoritative) { - const sameChain = - matchingPending !== undefined && - freshReceiptRev <= matchingPending.baseReceiptRevision && - matchingPending.baseRecoveryId === currentSidecarRecoveryId; - return { - baseReceiptRevision: freshReceiptRev, - baseDurableRevision: Math.max( - freshReceiptRev, - freshDiskRev, - sameChain ? matchingPending.baseDurableRevision : 0, - ), - baseRecoveryId: currentSidecarRecoveryId, - }; - } - return { - baseReceiptRevision: freshReceiptRev, - baseDurableRevision: freshReceiptRev, - baseRecoveryId: null, - }; - }; + const lockedPendingBase = (): PendingBase => + sidecarIsAuthoritative + ? { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: freshDiskRev, + baseRecoveryId: currentSidecarRecoveryId, + } + : { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: freshReceiptRev, + baseRecoveryId: null, + }; if (!(yield* isLockOwned)) { if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { pendingLaunchOptionsBySlotRoot.delete(slot.root); @@ -3761,7 +3740,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (diskOverride.launchOptionsRevision ?? 0) > (receipt.launchOptionsRevision ?? 0); const durableReceipt = durableFromSidecar ? diskOverride : receipt; const pendingOverride = pendingLaunchOptionsBySlotRoot.get(dir); - const effectiveReceipt = + const usePendingOverride = pendingOverride !== undefined && receiptMatchesInstall(pendingOverride.receipt, receipt) && (receipt.launchOptionsRevision ?? 0) <= pendingOverride.baseReceiptRevision && @@ -3769,9 +3748,17 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct pendingOverride.baseDurableRevision && (!durableFromSidecar || (durableReceipt.launchOptionsRecoveryId ?? null) === - pendingOverride.baseRecoveryId) - ? pendingOverride.receipt - : durableReceipt; + pendingOverride.baseRecoveryId); + if ( + pendingOverride !== undefined && + !usePendingOverride && + pendingLaunchOptionsBySlotRoot.get(dir) === pendingOverride + ) { + pendingLaunchOptionsBySlotRoot.delete(dir); + } + const effectiveReceipt = usePendingOverride + ? pendingOverride.receipt + : durableReceipt; const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); const fallbackArgs = effectiveReceipt.args ?? []; const fallbackEnv = effectiveReceipt.env ?? {}; diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index e87eb27ae0e00..b4ddab1bfceb1 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -5243,6 +5243,14 @@ createInterface({ input: process.stdin }).on("line", (line) => { "model-a", "reauth-live-model", ]); + // Subsequent refresh checkProvider commit must keep authenticated via latestAuthConfirmed. + const reauthCheckedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthCheckedDone, Exit.void); + const reauthChecked = yield* reauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + expect(reauthChecked.auth.status).toBe("authenticated"); + yield* Deferred.await(reauthCheckedDone); useAuthLoginAgent = false; failProbeSpawn = false; diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 93736dcf65b42..34406111fa8ef 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -1539,7 +1539,7 @@ export const AcpRegistryDriver: ProviderDriver buildInitialAcpRegistrySnapshot(readinessInput), checkProvider, - reconcileCheckedSnapshot: ({ probed }) => + reconcileCheckedSnapshot: (probed) => !latestAuthConfirmed && probed.auth.status === "authenticated" ? { ...probed, auth: stripConfirmedAuth(probed.auth) } : probed, diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index af85c10dd06ed..d50b62da1f0aa 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -74,10 +74,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( onAccepted?: () => void, ) => Effect.Effect; }) => Effect.Effect; - readonly reconcileCheckedSnapshot?: (input: { - readonly probed: ServerProvider; - readonly current: ServerProvider; - }) => ServerProvider; + readonly reconcileCheckedSnapshot?: (probed: ServerProvider) => ServerProvider; readonly refreshInterval?: Duration.Input; readonly refreshOnInterval?: boolean | ((snapshot: ServerProvider) => boolean); readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean; @@ -227,7 +224,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( ? state.enrichmentGeneration + 1 : state.enrichmentGeneration; const checkedSnapshot = input.reconcileCheckedSnapshot - ? input.reconcileCheckedSnapshot({ probed: probedSnapshot, current: state.snapshot }) + ? input.reconcileCheckedSnapshot(probedSnapshot) : probedSnapshot; // Failed reads retain limits only for the same account and original workspace. const previous = state.snapshot.auth; From 75eb3a1844478e87384484a0ab9c04dc8297eb8e Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:24:02 +0000 Subject: [PATCH 27/28] test(acp-registry): pin cross-chain recovery-id retirement and failed-reread pending recording --- .../src/server/AcpRegistrySupport.test.ts | 154 +++++++++++++++++- .../src/server/AcpRegistrySupport.ts | 6 +- 2 files changed, 151 insertions(+), 9 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index af2dd9ca037c0..674e9aaa7eb9e 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -7078,7 +7078,8 @@ describe("AcpRegistrySupport", () => { yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatB.resolve(settings(), "/workspace"); failReceiptTempWrite = false; - // (i) Locked sidecar io_error path on obsCatA: verify fallback immediately picks --b-s3. + // (i) Locked sidecar io_error path on obsCatA: verify pending is recorded while unreadable, + // then superseded by --b-s3 once sidecar reads recover. failSidecarRead = true; upstream = makeBinary("1.0.0", { archive: archiveAUrl, @@ -7088,15 +7089,19 @@ describe("AcpRegistrySupport", () => { yield* obsCatA.invalidateIndex(); yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatA.resolve(settings(), "/workspace"); - failSidecarRead = false; upstream = makeBinary("2.0.0", { archive: archiveFailUrl, cmd: "./bin/example-agent", }); yield* obsCatA.invalidateIndex(); yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-io-after-r2", + ]); + failSidecarRead = false; expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); - // (ii) Locked receipt-reread path on obsCatA2: verify fault count and --b-s3 on fallback. + // (ii) Locked receipt-reread path on obsCatA2: verify fault count, pending recording while + // unreadable, and --b-s3 once sidecar reads recover. failSidecarRead = true; injectedReceiptReadFailures = 0; failReceiptReadWhileLockedPath = obsLockPath; @@ -7109,7 +7114,6 @@ describe("AcpRegistrySupport", () => { yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); yield* obsCatA2.resolve(settings(), "/workspace"); failReceiptReadWhileLockedPath = null; - failSidecarRead = false; expect(injectedReceiptReadFailures).toBe(1); upstream = makeBinary("2.0.0", { archive: archiveFailUrl, @@ -7117,7 +7121,149 @@ describe("AcpRegistrySupport", () => { }); yield* obsCatA2.invalidateIndex(); yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA2.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-reread-after-r2", + ]); + failSidecarRead = false; expect((yield* obsCatA2.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + + // (f) Cross-chain sidecar repair: fallback retires old-chain pending on recovery-ID + // mismatch, and retries on the new chain (both locked write failure and fast-path ok + + // locked io_error) adopt the new chain's revision and recovery ID without old-chain base. + const xcDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cross-chain-", + }); + const xcToolsDir = path.join(xcDir, "tools"); + const xcSidecarPath = path.join(xcDir, "acp-registry", "binary-launch-options.json"); + const xcLockPath = `${xcSidecarPath}.lock`; + const makeXcCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: xcDir, + toolsDir: xcToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const xcCatB = yield* makeXcCat(); + const xcRetireCat = yield* makeXcCat(); + const xcLockedCat = yield* makeXcCat(); + const xcUnreadableCat = yield* makeXcCat(); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-init"], + }); + yield* xcCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + for (const arg of ["--xc-y1", "--xc-y2", "--xc-y3", "--xc-y4"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + for (const [cat, arg] of [ + [xcRetireCat, "--xc-stale-retire"], + [xcLockedCat, "--xc-stale-locked"], + [xcUnreadableCat, "--xc-stale-unreadable"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } + failSidecarWrite = false; + // Corrupt sidecar and repair into chain Z at rev 1 (< old chain Y base rev 4). + yield* fileSystem.writeFileString(xcSidecarPath, "{corrupt-xc"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-b-z1"], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + // Retire-chain variant: recovery-ID mismatch retires stale pending so unreadable fallback + // cannot resurrect --xc-stale-retire. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcRetireCat.invalidateIndex(); + yield* xcRetireCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcRetireCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z1", + ]); + failSidecarRead = true; + expect((yield* xcRetireCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-init", + ]); + failSidecarRead = false; + // Locked-write-failure and fast-path-ok/locked-io_error retries adopt chain Z (rev 1, Z). + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-a-locked-on-z"], + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcLockedCat.resolve(settings(), "/workspace"); + failSidecarWrite = false; + failSidecarReadWhileLockedPath = xcLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-a-unreadable-on-z"], + }); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcUnreadableCat.resolve(settings(), "/workspace"); + failSidecarReadWhileLockedPath = null; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcLockedCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-a-locked-on-z", + ]); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcUnreadableCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-a-unreadable-on-z", + ]); + // B writes chain Z rev 2 (< old chain Y rev 4) -> beats both catalogs' rev-1 pending entries. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-b-z2"], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcLockedCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z2", + ]); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcUnreadableCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z2", + ]); // Restore upstream to --commit-8 before step 5 below. upstream = makeBinary("1.0.0", { archive: archiveAUrl, diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 60fe4a896bfb5..7ee088cfeb899 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -3749,11 +3749,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (!durableFromSidecar || (durableReceipt.launchOptionsRecoveryId ?? null) === pendingOverride.baseRecoveryId); - if ( - pendingOverride !== undefined && - !usePendingOverride && - pendingLaunchOptionsBySlotRoot.get(dir) === pendingOverride - ) { + if (pendingOverride !== undefined && !usePendingOverride) { pendingLaunchOptionsBySlotRoot.delete(dir); } const effectiveReceipt = usePendingOverride From af965503a2e4315c6fd647040423d69a03cd1749 Mon Sep 17 00:00:00 2001 From: Ahmed Bedair Date: Sun, 22 Nov 2026 23:40:00 +0000 Subject: [PATCH 28/28] test(acp-registry): verify old-chain pending options before cross-chain retirement --- .../src/server/AcpRegistrySupport.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 674e9aaa7eb9e..5cb231a61d208 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -7179,6 +7179,20 @@ describe("AcpRegistrySupport", () => { yield* cat.resolve(settings(), "/workspace"); } failSidecarWrite = false; + // Prove old-chain pending options are active on all three catalogs while chain Y is readable. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + for (const [cat, arg] of [ + [xcRetireCat, "--xc-stale-retire"], + [xcLockedCat, "--xc-stale-locked"], + [xcUnreadableCat, "--xc-stale-unreadable"], + ] as const) { + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* cat.resolve(settings(), "/workspace")).spawn.args).toEqual([arg]); + } // Corrupt sidecar and repair into chain Z at rev 1 (< old chain Y base rev 4). yield* fileSystem.writeFileString(xcSidecarPath, "{corrupt-xc"); upstream = makeBinary("1.0.0", {