From 84207d07a4a3ed048c653efcd02eed67e1b53754 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 19 Jun 2026 21:12:18 -0700 Subject: [PATCH] Tighten provider Effect service refactor Co-authored-by: codex --- .../OrchestrationEngineHarness.integration.ts | 31 ++++---- .../providerService.integration.test.ts | 4 +- .../Layers/CheckpointReactor.test.ts | 9 +-- .../orchestration/Layers/CheckpointReactor.ts | 4 +- .../Layers/ProviderCommandReactor.test.ts | 31 ++++---- .../Layers/ProviderCommandReactor.ts | 8 +- .../Layers/ProviderRuntimeIngestion.test.ts | 9 +-- .../Layers/ProviderRuntimeIngestion.ts | 4 +- .../Layers/ThreadDeletionReactor.ts | 4 +- .../provider/Layers/OpenCodeProvider.test.ts | 25 ++++++ .../provider/Layers/ProviderEventLoggers.ts | 6 -- .../src/provider/Layers/ProviderService.ts | 11 --- .../Layers/ProviderSessionDirectory.ts | 6 -- .../src/provider/ProviderAdapterRegistry.ts | 35 ++++++--- .../src/provider/ProviderInstanceRegistry.ts | 45 +++++++---- apps/server/src/provider/ProviderRegistry.ts | 42 +++++----- .../src/provider/ProviderService.test.ts | 35 +++++---- apps/server/src/provider/ProviderService.ts | 43 +++++++---- .../provider/ProviderSessionDirectory.test.ts | 4 +- .../src/provider/ProviderSessionDirectory.ts | 5 +- .../src/provider/ProviderSessionReaper.ts | 1 + .../Services/ProviderAdapterRegistry.ts | 3 - .../src/provider/Services/ProviderRegistry.ts | 2 - .../src/provider/Services/ProviderService.ts | 5 -- apps/server/src/provider/opencodeRuntime.ts | 13 +++- .../providerMaintenanceRunner.test.ts | 31 ++++++++ .../src/provider/providerMaintenanceRunner.ts | 76 +++++++++++++++---- docs/architecture/overview.md | 2 +- docs/operations/effect-fn-checklist.md | 32 ++++---- docs/reference/encyclopedia.md | 2 +- 30 files changed, 323 insertions(+), 205 deletions(-) delete mode 100644 apps/server/src/provider/Layers/ProviderEventLoggers.ts delete mode 100644 apps/server/src/provider/Layers/ProviderService.ts delete mode 100644 apps/server/src/provider/Layers/ProviderSessionDirectory.ts delete mode 100644 apps/server/src/provider/Services/ProviderAdapterRegistry.ts delete mode 100644 apps/server/src/provider/Services/ProviderRegistry.ts delete mode 100644 apps/server/src/provider/Services/ProviderService.ts diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index ebc4f984b8..50a9eeaa68 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -33,17 +33,13 @@ import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts"; import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts"; import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts"; import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts"; -import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; +import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts"; import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts"; -import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; +import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts"; import { ServerSettingsService } from "../src/serverSettings.ts"; -import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; +import * as ProviderService from "../src/provider/ProviderService.ts"; import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts"; -import { - NoOpProviderEventLoggers, - ProviderEventLoggers, -} from "../src/provider/Layers/ProviderEventLoggers.ts"; -import { ProviderService } from "../src/provider/Services/ProviderService.ts"; +import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts"; import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts"; import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts"; import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts"; @@ -178,7 +174,7 @@ export interface OrchestrationIntegrationHarness { readonly adapterHarness: TestProviderAdapterHarness | null; readonly engine: OrchestrationEngineShape; readonly snapshotQuery: ProjectionSnapshotQuery["Service"]; - readonly providerService: ProviderService["Service"]; + readonly providerService: ProviderService.ProviderService["Service"]; readonly checkpointStore: CheckpointStore.CheckpointStore["Service"]; readonly checkpointRepository: ProjectionCheckpointRepository["Service"]; readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"]; @@ -241,7 +237,7 @@ export const makeOrchestrationIntegrationHarness = ( }); const fakeRegistry = adapterHarness ? Layer.succeed( - ProviderAdapterRegistry, + ProviderAdapterRegistry.ProviderAdapterRegistry, makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }), ) : null; @@ -262,11 +258,11 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), ); - const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( + const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(ProviderSessionRuntimeRepositoryLive), ); const realCodexRegistry = Layer.effect( - ProviderAdapterRegistry, + ProviderAdapterRegistry.ProviderAdapterRegistry, Effect.gen(function* () { const codexSettings = yield* decodeCodexSettings({}); const codexAdapter = yield* makeCodexAdapter(codexSettings); @@ -279,15 +275,18 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provideMerge(NodeServices.layer), Layer.provideMerge(providerSessionDirectoryLayer), ); - const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers); + const providerEventLoggersLayer = Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ); const providerLayer = useRealCodex - ? makeProviderServiceLive().pipe( + ? ProviderService.layer.pipe( Layer.provide(providerSessionDirectoryLayer), Layer.provide(realCodexRegistry), Layer.provide(AnalyticsService.layerTest), Layer.provide(providerEventLoggersLayer), ) - : makeProviderServiceLive().pipe( + : ProviderService.layer.pipe( Layer.provide(providerSessionDirectoryLayer), Layer.provide(fakeRegistry!), Layer.provide(AnalyticsService.layerTest), @@ -395,7 +394,7 @@ export const makeOrchestrationIntegrationHarness = ( runtime.runPromise(Effect.service(ProjectionSnapshotQuery)), ).pipe(Effect.orDie); const providerService = yield* tryRuntimePromise("load ProviderService service", () => - runtime.runPromise(Effect.service(ProviderService)), + runtime.runPromise(Effect.service(ProviderService.ProviderService)), ).pipe(Effect.orDie); const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () => runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)), diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index 76522c12e1..c9026ab95a 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -70,9 +70,7 @@ const makeIntegrationFixture = Effect.gen(function* () { ), ).pipe(Layer.provide(SqlitePersistenceMemory)); - const layer = Layer.effect(ProviderService.ProviderService, ProviderService.make()).pipe( - Layer.provide(shared), - ); + const layer = ProviderService.layer.pipe(Layer.provide(shared)); return { cwd, diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 707c87c43c..68f7214e4a 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -49,10 +49,7 @@ import { } from "../Services/OrchestrationEngine.ts"; import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { - ProviderService, - type ProviderServiceShape, -} from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts"; import { ServerConfig } from "../../config.ts"; import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts"; @@ -102,7 +99,7 @@ function createProviderServiceHarness( }, ] satisfies ReadonlyArray) : Effect.succeed([] as ReadonlyArray); - const service: ProviderServiceShape = { + const service: ProviderService.ProviderService["Service"] = { startSession: () => unsupported(), sendTurn: () => unsupported(), interruptTurn: () => unsupported(), @@ -328,7 +325,7 @@ describe("CheckpointReactor", () => { Layer.provideMerge(orchestrationLayer), Layer.provideMerge(projectionSnapshotLayer), Layer.provideMerge(RuntimeReceiptBusLive), - Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), + Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)), Layer.provideMerge(vcsStatusBroadcasterLayer), Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))), Layer.provideMerge( diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 3ba244ddf2..a2423e54ad 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -25,7 +25,7 @@ import { resolveThreadWorkspaceCwd, } from "../../checkpointing/Utils.ts"; import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; @@ -80,7 +80,7 @@ const make = Effect.gen(function* () { randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`))); const orchestrationEngine = yield* OrchestrationEngineService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; + const providerService = yield* ProviderService.ProviderService; const checkpointStore = yield* CheckpointStore.CheckpointStore; const receiptBus = yield* RuntimeReceiptBus; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ce464565dc..4ebfc57eca 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -37,10 +37,7 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import { - ProviderService, - type ProviderServiceShape, -} from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts"; import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts"; import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; @@ -222,8 +219,12 @@ describe("ProviderCommandReactor", () => { }), ); const interruptTurn = vi.fn((_: unknown) => Effect.void); - const respondToRequest = vi.fn(() => Effect.void); - const respondToUserInput = vi.fn(() => Effect.void); + const respondToRequest = vi.fn( + () => Effect.void, + ); + const respondToUserInput = vi.fn< + ProviderService.ProviderService["Service"]["respondToUserInput"] + >(() => Effect.void); const stopSession = vi.fn((input: unknown) => Effect.sync(() => { const threadId = @@ -294,13 +295,15 @@ describe("ProviderCommandReactor", () => { ]; const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - const service: ProviderServiceShape = { - startSession: startSession as ProviderServiceShape["startSession"], - sendTurn: sendTurn as ProviderServiceShape["sendTurn"], - interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"], - respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"], - respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"], - stopSession: stopSession as ProviderServiceShape["stopSession"], + const service: ProviderService.ProviderService["Service"] = { + startSession: startSession as ProviderService.ProviderService["Service"]["startSession"], + sendTurn: sendTurn as ProviderService.ProviderService["Service"]["sendTurn"], + interruptTurn: interruptTurn as ProviderService.ProviderService["Service"]["interruptTurn"], + respondToRequest: + respondToRequest as ProviderService.ProviderService["Service"]["respondToRequest"], + respondToUserInput: + respondToUserInput as ProviderService.ProviderService["Service"]["respondToUserInput"], + stopSession: stopSession as ProviderService.ProviderService["Service"]["stopSession"], listSessions: () => Effect.succeed(runtimeSessions), getCapabilities: (_provider) => Effect.succeed({ @@ -346,7 +349,7 @@ describe("ProviderCommandReactor", () => { const layer = ProviderCommandReactorLive.pipe( Layer.provideMerge(orchestrationLayer), Layer.provideMerge(projectionSnapshotLayer), - Layer.provideMerge(Layer.succeed(ProviderService, service)), + Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, service)), Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)), Layer.provideMerge( Layer.mock(GitWorkflowService.GitWorkflowService)({ diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9c7a7c94bb..ec350d7e9e 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -30,8 +30,8 @@ import { increment, orchestrationEventsProcessedTotal } from "../../observabilit import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; import type { ProviderServiceError } from "../../provider/Errors.ts"; import { TextGeneration } from "../../textGeneration/TextGeneration.ts"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; -import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; +import * as ProviderRegistry from "../../provider/ProviderRegistry.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; import { @@ -190,8 +190,8 @@ const make = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const orchestrationEngine = yield* OrchestrationEngineService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; - const providerRegistry = yield* ProviderRegistry; + const providerService = yield* ProviderService.ProviderService; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const gitWorkflow = yield* GitWorkflowService; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster; const textGeneration = yield* TextGeneration; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 001ba38894..a518a20f82 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -35,10 +35,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import { - ProviderService, - type ProviderServiceShape, -} from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; @@ -97,7 +94,7 @@ function createProviderServiceHarness() { const runtimeSessions: ProviderSession[] = []; const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - const service: ProviderServiceShape = { + const service: ProviderService.ProviderService["Service"] = { startSession: () => unsupported(), sendTurn: () => unsupported(), interruptTurn: () => unsupported(), @@ -237,7 +234,7 @@ describe("ProviderRuntimeIngestion", () => { Layer.provideMerge(orchestrationLayer), Layer.provideMerge(projectionSnapshotLayer), Layer.provideMerge(SqlitePersistenceMemory), - Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), + Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)), Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(NodeServices.layer), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 3e5978f484..003e284093 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -27,7 +27,7 @@ import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { isGitRepository } from "../../git/Utils.ts"; @@ -631,7 +631,7 @@ const make = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const orchestrationEngine = yield* OrchestrationEngineService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; + const providerService = yield* ProviderService.ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; const serverSettingsService = yield* ServerSettingsService; const providerCommandId = (event: ProviderRuntimeEvent, tag: string) => diff --git a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts b/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts index 7d8a24069a..a584392292 100644 --- a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts +++ b/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts @@ -5,7 +5,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import * as ProviderService from "../../provider/ProviderService.ts"; import * as TerminalManager from "../../terminal/Manager.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { @@ -38,7 +38,7 @@ export const logCleanupCauseUnlessInterrupted = ({ const make = Effect.gen(function* () { const orchestrationEngine = yield* OrchestrationEngineService; - const providerService = yield* ProviderService; + const providerService = yield* ProviderService.ProviderService; const terminalManager = yield* TerminalManager.TerminalManager; const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) => diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index f754d4ab9b..4098cdd822 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -16,6 +16,31 @@ const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings); const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n"; +it("keeps OpenCode runtime causes separate from stable messages", () => { + const cause = new Error("sdk response included sensitive diagnostics"); + const error = new OpenCodeRuntime.OpenCodeRuntimeError({ + operation: "provider.list", + detail: cause.message, + cause, + }); + + assert.equal(error.cause, cause); + assert.equal(error.message, "OpenCode runtime operation provider.list failed."); + assert.doesNotMatch(error.message, /sensitive diagnostics/u); + + const processExit = new OpenCodeRuntime.OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: "OpenCode server exited before startup completed.", + exitCode: 1, + stdout: "startup output", + stderr: "startup failure", + }); + assert.equal(processExit.cause, undefined); + assert.equal(processExit.exitCode, 1); + assert.equal(processExit.stdout, "startup output"); + assert.equal(processExit.stderr, "startup failure"); +}); + /** * The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag * are deleted. The snapshot-producing logic they wrapped now lives in the diff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts deleted file mode 100644 index 37bc35ff95..0000000000 --- a/apps/server/src/provider/Layers/ProviderEventLoggers.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration harness. -import * as Canonical from "../ProviderEventLoggers.ts"; - -export const ProviderEventLoggersLive = Canonical.layer; -export const ProviderEventLoggers = Canonical.ProviderEventLoggers; -export const NoOpProviderEventLoggers = Canonical.NoOpProviderEventLoggers; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts deleted file mode 100644 index 93d3d24699..0000000000 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration harness. -import * as Layer from "effect/Layer"; - -import * as ProviderService from "../ProviderService.ts"; - -export type ProviderServiceLiveOptions = ProviderService.ProviderServiceOptions; - -export const ProviderServiceLive = ProviderService.layer; - -export const makeProviderServiceLive = (options?: ProviderService.ProviderServiceOptions) => - Layer.effect(ProviderService.ProviderService, ProviderService.make(options)); diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts deleted file mode 100644 index ffc06ee2b5..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration harness. -import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts"; - -export const ProviderSessionDirectoryLive = ProviderSessionDirectory.layer; - -export const makeProviderSessionDirectoryLive = () => ProviderSessionDirectory.layer; diff --git a/apps/server/src/provider/ProviderAdapterRegistry.ts b/apps/server/src/provider/ProviderAdapterRegistry.ts index d627e25c0f..b1653af368 100644 --- a/apps/server/src/provider/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/ProviderAdapterRegistry.ts @@ -12,11 +12,16 @@ * - `getByInstance` / `listInstances` — new per-instance routing. Callers * that already know an `instanceId` (threads, sessions, events) * should prefer these. + * - `listProviders` — legacy kind-keyed routing for default instances * (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D * behaviour. New code should not grow additional callers of the kind-keyed * methods; they exist so the settings UI, WS refresh RPC, and a handful * of legacy persisted rows can still be routed during the rollout. * + * Adapter lookups are resolved dynamically through `ProviderInstanceRegistry`. + * Settings-driven hot reload is therefore visible immediately without + * rebuilding this facade. + * * @module ProviderAdapterRegistry */ import { @@ -50,7 +55,10 @@ export class ProviderAdapterRegistry extends Context.Service< { /** * Resolve the adapter for a specific instance id. Returns - * `ProviderUnsupportedError` if no such live instance is registered. + * `ProviderUnsupportedError` if no such instance is currently registered + * (which covers "never configured" and "configured but the driver is + * unavailable in this build"; both surface the same failure to callers + * that expect a working adapter). */ readonly getByInstance: ( instanceId: ProviderInstanceId, @@ -62,28 +70,33 @@ export class ProviderAdapterRegistry extends Context.Service< ) => Effect.Effect; /** - * List every live instance id. Unavailable shadow instances are excluded - * because callers use these ids with `getByInstance`. + * List all live instance ids. Excludes unavailable/shadow instances because + * callers of this method want something they can pass to `getByInstance`. */ readonly listInstances: () => Effect.Effect>; /** * List provider kinds whose default instance is currently registered. * - * @deprecated Prefer `listInstances`; this remains for migration-era - * callers that still address providers by driver kind. + * @deprecated Prefer `listInstances`. Retained for migration-era call sites + * that iterate providers to build UI or metrics. */ readonly listProviders: () => Effect.Effect>; /** - * Emits whenever the live instance set changes. Consumers should re-read - * `listInstances` and reconcile their per-instance subscriptions. + * Change notification stream mirroring + * `ProviderInstanceRegistry.streamChanges`. Emits one `void` tick whenever + * the set of live instances changes. Consumers that fan out + * `adapter.streamEvents` per instance re-pull `listInstances` on each tick + * and fork subscriptions for instances they have not seen yet. */ readonly streamChanges: Stream.Stream; /** - * Acquire the change subscription synchronously in the caller's scope, - * avoiding the publish race inherent in forking `Stream.fromPubSub`. + * Acquire a change subscription synchronously in the caller's current + * fiber. Consumers that must avoid missing a publish between initial + * reconciliation and watcher startup should use this, then fork + * `Stream.fromSubscription`. */ readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; } @@ -130,6 +143,8 @@ export const make = Effect.gen(function* () { const kinds = new Set(); for (const instance of instances) { if (instance.instanceId === defaultInstanceIdForDriver(instance.driverKind)) { + // Only default instances appear through this legacy view; custom + // instances such as `codex_personal` have no driver-kind identity. kinds.add(instance.driverKind); } } @@ -142,6 +157,8 @@ export const make = Effect.gen(function* () { getInstanceInfo, listInstances, listProviders, + // The facade owns no state; the instance registry already coalesces + // add, remove, and rebuild notifications into a single change channel. streamChanges: registry.streamChanges, subscribeChanges: registry.subscribeChanges, }); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index cfd17b13b0..0d203b9ed7 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -58,38 +58,46 @@ export class ProviderInstanceRegistry extends Context.Service< ProviderInstanceRegistry, { /** - * Look up one instance by id. Unknown ids return `undefined`; callers map - * that absence to the appropriate domain error. + * Look up one instance by id. Returns `undefined` (not `Option`) when the + * id is unknown; callers branch on absence and emit the appropriate domain + * error. */ readonly getInstance: ( instanceId: ProviderInstanceId, ) => Effect.Effect; /** - * Every successfully materialized instance, in stable settings-author - * order. + * Every available (driver-registered, successfully created) instance, in + * stable settings-author order. */ readonly listInstances: Effect.Effect>; /** - * Shadow snapshots for unknown drivers or invalid configurations, ready - * to merge into `ProviderRegistry` output. + * Wire-shape shadow snapshots for instances whose driver is unknown to this + * build or whose config failed to decode. Suitable for merging directly + * into `ProviderRegistry` output. */ readonly listUnavailable: Effect.Effect>; /** - * Emits after the registry adds, removes, or rebuilds instances. The - * payload is `void` because consumers re-read both registry lists. + * Push notification stream emitted whenever the registry's contents change. + * The payload is `void` because consumers always re-pull `listInstances` + * and `listUnavailable` together. * - * `Stream.fromPubSub` subscribes only when execution begins, so a newly - * forked consumer can miss a publish. Consumers that cannot tolerate that - * gap should acquire `subscribeChanges` first. + * `Stream.fromPubSub` defers `PubSub.subscribe` until the stream starts + * running, so forking a consumer races the next publish. Hot-reload + * consumers that cannot miss a publish should use `subscribeChanges` + * instead, which acquires the subscription synchronously before the + * consumer loop is forked. */ readonly streamChanges: Stream.Stream; /** - * Acquire a scoped PubSub subscription synchronously before forking the - * consumer loop, ensuring subsequent publishes cannot land in a gap. + * Acquire a scoped subscription to the change channel synchronously in the + * caller's fiber. Consumers typically `yield*` this in the same fiber that + * forks their consumer loop, then drain it with `PubSub.take` or + * `Stream.fromSubscription`. Because the subscription is registered before + * this effect returns, no subsequent publish can land in a gap. */ readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; } @@ -107,9 +115,14 @@ export class ProviderInstanceRegistryMutator extends Context.Service< ProviderInstanceRegistryMutator, { /** - * Reconcile the live registry with a new configuration map. Individual - * driver creation failures become unavailable shadow snapshots so the - * settings watcher itself never fails. + * Bring the live registry in line with the supplied config map. The + * operation closes removed or replaced scopes before creating replacements + * and publishes a single change tick after the batch. Reapplying an + * unchanged map is a no-op. + * + * The effect never fails: individual driver creation failures become + * unavailable shadow snapshots, keeping settings-watcher loops alive when + * one entry is invalid. */ readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; } diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 593d856c9e..a631e11a73 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -64,13 +64,18 @@ export class ProviderRegistry extends Context.Service< ProviderRegistry, { /** - * Read the latest snapshot for every configured instance. Multiple - * snapshots can share a driver kind and are distinguished by instance id. + * Read the latest provider snapshots for every configured instance. + * Multiple snapshots may share the same driver kind and disambiguate via + * `instanceId`. */ readonly getProviders: Effect.Effect>; /** - * Refresh every provider, or the default instance for one driver kind. + * Refresh all providers, or the default instance of the specified kind + * when supplied. + * + * Retained for compatibility with legacy call sites such as the WS refresh + * RPC and orchestration metrics. * * @deprecated Prefer `refreshInstance` for new call sites. */ @@ -80,15 +85,16 @@ export class ProviderRegistry extends Context.Service< /** * Refresh one configured instance. Unknown ids resolve to the current - * cached list to preserve the legacy transport behavior. + * cached list, matching the legacy `refresh` behavior so transport layers + * do not have to special-case unknown ids. */ readonly refreshInstance: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; /** - * Resolve maintenance capabilities for a live instance, falling back to - * manual-only capabilities when that instance is unavailable. + * Resolve maintenance capabilities for one live provider instance, + * falling back to manual-only capabilities when it is unavailable. */ readonly getProviderMaintenanceCapabilitiesForInstance: ( instanceId: ProviderInstanceId, @@ -96,8 +102,10 @@ export class ProviderRegistry extends Context.Service< ) => Effect.Effect; /** - * Apply volatile maintenance state for one instance. This state is not - * persisted; update actions are projected onto `ServerProvider.updateState`. + * Apply volatile maintenance-action state to one configured instance. This + * state is never persisted. Today only update actions are projected onto + * `ServerProvider.updateState`; install/auth actions can extend this map + * without adding driver-scoped APIs. */ readonly setProviderMaintenanceActionState: (input: { readonly instanceId: ProviderInstanceId; @@ -105,7 +113,10 @@ export class ProviderRegistry extends Context.Service< readonly state: ServerProviderUpdateState | null; }) => Effect.Effect>; - /** Emits the full materialized provider list after each aggregated change. */ + /** + * Stream of provider snapshot updates, one emission per aggregated change. + * The array contains the full current state. + */ readonly streamChanges: Stream.Stream>; } >()("t3/provider/ProviderRegistry") {} @@ -671,19 +682,6 @@ export const make = Effect.gen(function* () { // and pending fallbacks fill the gaps. yield* upsertProviders(fallbackProviders, { publish: false }); // Subscribe to registry mutations BEFORE running the initial sync. - // `subscribeChanges` acquires the dequeue synchronously in this - // fibre; the subscription is active the instant this `yield*` - // returns. Forking the consumer loop later cannot lose a publish - // because no publish can reach a not-yet-subscribed dequeue. - // - // (Contrast with the pre-fix code that did - // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`. - // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start, - // and `forkScoped` only schedules the fibre — so a reconcile that - // published between "fibre scheduled" and "fibre starts running" - // was dropped, which made any settings change that replaced an - // instance never propagate to the aggregator's `providersRef`.) - // Subscribe to registry mutations BEFORE running the initial sync. // `subscribeChanges` acquires the `PubSub.Subscription` synchronously // in this fibre; the subscription is registered with the PubSub the // instant this `yield*` returns, so any subsequent publish is diff --git a/apps/server/src/provider/ProviderService.test.ts b/apps/server/src/provider/ProviderService.test.ts index 5bcc103b4f..8c020222e0 100644 --- a/apps/server/src/provider/ProviderService.test.ts +++ b/apps/server/src/provider/ProviderService.test.ts @@ -55,11 +55,14 @@ import { } from "../persistence/Layers/Sqlite.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; - -const makeProviderServiceLive = (options?: ProviderService.ProviderServiceOptions) => - Layer.effect(ProviderService.ProviderService, ProviderService.make(options)); import { makeAdapterRegistryMock } from "./testUtils/providerAdapterRegistryMock.ts"; +// Several tests build two ProviderService instances in one scope to simulate a +// process restart. Construct a fresh Layer for each build so Layer memoization +// cannot reuse the first service instance. +const makeFreshProviderServiceLayer = (options?: ProviderService.ProviderServiceOptions) => + Layer.effect(ProviderService.ProviderService, ProviderService.make(options)); + const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest(); const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); @@ -289,7 +292,7 @@ function makeProviderServiceLayer() { const layer = it.layer( Layer.mergeAll( - makeProviderServiceLive().pipe( + makeFreshProviderServiceLayer().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -342,7 +345,7 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () => Layer.provide(runtimeRepositoryLayer), ); const providerLayer = Layer.mergeAll( - makeProviderServiceLive().pipe( + makeFreshProviderServiceLayer().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -403,7 +406,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", () const directoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeFreshProviderServiceLayer().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -487,7 +490,7 @@ it.effect( const directoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeFreshProviderServiceLayer().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(serverSettingsLayer), @@ -559,7 +562,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance const directoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeFreshProviderServiceLayer().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -606,7 +609,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se const directoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive({ + const providerLayer = makeFreshProviderServiceLayer({ canonicalEventLogger: { filePath: "memory://provider-canonical-events", write: (event, threadId) => { @@ -678,7 +681,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( }); }).pipe(Effect.provide(directoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeFreshProviderServiceLayer().pipe( Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -742,7 +745,7 @@ it.effect( const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), ), @@ -801,7 +804,7 @@ it.effect( const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), ), @@ -1312,7 +1315,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), ), @@ -1350,7 +1353,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), ), @@ -1418,7 +1421,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), ), @@ -1451,7 +1454,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeFreshProviderServiceLayer().pipe( Layer.provide( Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), ), diff --git a/apps/server/src/provider/ProviderService.ts b/apps/server/src/provider/ProviderService.ts index 53fd2308b3..703b577396 100644 --- a/apps/server/src/provider/ProviderService.ts +++ b/apps/server/src/provider/ProviderService.ts @@ -6,6 +6,8 @@ * unified provider event stream for subscribers. * * It does not implement provider protocol details (adapter concern). + * Uses Effect `Context.Service` for dependency injection and returns typed + * domain errors for validation, session, codex, and checkpoint workflows. * * @module ProviderService */ @@ -61,14 +63,22 @@ import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts"; import { type EventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts"; import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; -import * as McpProviderSession from "../mcp/McpProviderSession.ts"; -import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import { + clearAllMcpProviderSessions, + clearMcpProviderSession, + setMcpProviderSession, +} from "../mcp/McpProviderSession.ts"; +import { + issueActiveMcpCredential, + revokeActiveMcpThread, + revokeAllActiveMcpCredentials, +} from "../mcp/McpSessionRegistry.ts"; const isModelSelection = Schema.is(ModelSelection); export class ProviderService extends Context.Service< ProviderService, { - /** Start a provider session for a thread. */ + /** Start a provider session. */ readonly startSession: ( threadId: ThreadId, input: ProviderSessionStartInput, @@ -99,10 +109,14 @@ export class ProviderService extends Context.Service< input: ProviderStopSessionInput, ) => Effect.Effect; - /** Aggregate the active sessions reported by all registered adapters. */ + /** + * List active provider sessions. + * + * Aggregates runtime session lists from all registered adapters. + */ readonly listSessions: () => Effect.Effect>; - /** Read capabilities for the adapter bound to an instance. */ + /** Read capabilities for the adapter bound to a configured provider instance. */ readonly getCapabilities: ( instanceId: ProviderInstanceId, ) => Effect.Effect; @@ -119,8 +133,9 @@ export class ProviderService extends Context.Service< }) => Effect.Effect; /** - * Canonical provider runtime event stream. ProviderService owns the - * per-instance fan-out rather than delegating it to a separate event bus. + * Canonical provider runtime event stream. + * + * Fan-out is owned by ProviderService (not by a standalone event-bus service). */ readonly streamEvents: Stream.Stream; } @@ -279,16 +294,14 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi const runtimeEventPubSub = yield* PubSub.unbounded(); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => - McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( + issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( Effect.tap((credential) => - credential - ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)) - : Effect.void, + credential ? Effect.sync(() => setMcpProviderSession(credential.config)) : Effect.void, ), ); const clearMcpSession = (threadId: ThreadId) => - McpSessionRegistry.revokeActiveMcpThread(threadId).pipe( - Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))), + revokeActiveMcpThread(threadId).pipe( + Effect.tap(() => Effect.sync(() => clearMcpProviderSession(threadId))), ); const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => @@ -1096,8 +1109,8 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi ), ).pipe(Effect.asVoid); yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid); - yield* McpSessionRegistry.revokeAllActiveMcpCredentials(); - McpProviderSession.clearAllMcpProviderSessions(); + yield* revokeAllActiveMcpCredentials(); + clearAllMcpProviderSessions(); const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => [])); yield* Effect.forEach(bindings, (binding) => Effect.gen(function* () { diff --git a/apps/server/src/provider/ProviderSessionDirectory.test.ts b/apps/server/src/provider/ProviderSessionDirectory.test.ts index 9def269b31..a51d0cf340 100644 --- a/apps/server/src/provider/ProviderSessionDirectory.test.ts +++ b/apps/server/src/provider/ProviderSessionDirectory.test.ts @@ -20,9 +20,7 @@ import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.t import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts"; function makeDirectoryLayer(persistenceLayer: Layer.Layer) { - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); + const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer)); return Layer.mergeAll( runtimeRepositoryLayer, ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer)), diff --git a/apps/server/src/provider/ProviderSessionDirectory.ts b/apps/server/src/provider/ProviderSessionDirectory.ts index 4045a5ab15..3161c8a4de 100644 --- a/apps/server/src/provider/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/ProviderSessionDirectory.ts @@ -14,7 +14,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "./Errors.ts"; -import * as ProviderSessionRuntime from "../persistence/Services/ProviderSessionRuntime.ts"; +import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; export interface ProviderRuntimeBinding { readonly threadId: ThreadId; @@ -119,6 +119,9 @@ function toRuntimeBinding( ({ threadId: runtime.threadId, provider, + // Migration boundary: rows written before provider instances had a + // nullable id. Promote them here so runtime routing never has to + // infer an instance from its driver kind. providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider), adapterKey: runtime.adapterKey, runtimeMode: runtime.runtimeMode, diff --git a/apps/server/src/provider/ProviderSessionReaper.ts b/apps/server/src/provider/ProviderSessionReaper.ts index 1a4ea8fbbb..1516a525ab 100644 --- a/apps/server/src/provider/ProviderSessionReaper.ts +++ b/apps/server/src/provider/ProviderSessionReaper.ts @@ -14,6 +14,7 @@ import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts"; export class ProviderSessionReaper extends Context.Service< ProviderSessionReaper, { + /** Start the background provider session reaper within the provided scope. */ readonly start: () => Effect.Effect; } >()("t3/provider/ProviderSessionReaper") {} diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts deleted file mode 100644 index c3841eadf2..0000000000 --- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration harness. -export { ProviderAdapterRegistry } from "../ProviderAdapterRegistry.ts"; -export type { ProviderInstanceRoutingInfo } from "../ProviderAdapterRegistry.ts"; diff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.ts deleted file mode 100644 index 96c841a8ad..0000000000 --- a/apps/server/src/provider/Services/ProviderRegistry.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration modules. -export * from "../ProviderRegistry.ts"; diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts deleted file mode 100644 index 4477887cd2..0000000000 --- a/apps/server/src/provider/Services/ProviderService.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Compatibility shim for the intentionally excluded orchestration modules and harness. -export * from "../ProviderService.ts"; - -/** @deprecated Use `ProviderService["Service"]` from the canonical module. */ -export type ProviderServiceShape = import("../ProviderService.ts").ProviderService["Service"]; diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 06f29944be..1b738a4c85 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -26,7 +26,7 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import * as ProcessRunner from "../processRunner.ts"; +import { isWindowsCommandNotFound } from "../processRunner.ts"; import { collectStreamAsString } from "./providerSnapshot.ts"; import * as NetService from "@t3tools/shared/Net"; import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; @@ -54,12 +54,15 @@ export class OpenCodeRuntimeError extends Schema.TaggedErrorClass Effect.fail(cause)), + ); +} + function makeRegistry( initialProviders: ServerProvider | ReadonlyArray = baseProvider, ) { @@ -320,6 +328,29 @@ describe("providerMaintenanceRunner", () => { }, ); + it.effect("preserves update spawn failure messages", () => { + const cause = PlatformError.systemError({ + _tag: "PermissionDenied", + module: "ChildProcess", + method: "spawn", + pathOrDescriptor: "npm", + description: "", + }); + return Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider); + const runner = yield* makeTestRunner(registry); + + const result = yield* runner.updateProvider(CODEX_DRIVER); + assert.strictEqual(result.providers[0]?.updateState?.status, "failed"); + assert.strictEqual( + result.providers[0]?.updateState?.message, + `Failed to run update command npm: ${cause.message}`, + ); + }).pipe( + Effect.provide(Layer.mergeAll(latestVersionHttpClient("0.0.0"), failingSpawnerLayer(cause))), + ); + }); + it.effect("updates a single provider instance without touching sibling instances", () => { const calls: Array<{ command: string; args: ReadonlyArray }> = []; return Effect.gen(function* () { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index bfb744f0cd..468009252a 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -14,6 +14,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import { HttpClient } from "effect/unstable/http"; @@ -52,20 +53,68 @@ export class ProviderMaintenanceRunner extends Context.Service< } >()("t3/provider/providerMaintenanceRunner") {} -class ProviderMaintenanceCommandError extends Schema.TaggedErrorClass()( - "ProviderMaintenanceCommandError", +const platformFailureFields = { + failureTag: Schema.NullOr(Schema.String), + failureModule: Schema.String, + failureMethod: Schema.String, + failureDescription: Schema.NullOr(Schema.String), + failurePathOrDescriptor: Schema.NullOr(Schema.Union([Schema.String, Schema.Number])), +} as const; + +interface PlatformFailureAttributes { + readonly failureTag: string | null; + readonly failureModule: string; + readonly failureMethod: string; + readonly failureDescription: string | null; + readonly failurePathOrDescriptor: string | number | null; +} + +function platformFailureAttributes(cause: PlatformError.PlatformError): PlatformFailureAttributes { + const { reason } = cause; + return { + failureTag: reason._tag === "BadArgument" ? null : reason._tag, + failureModule: reason.module, + failureMethod: reason.method, + failureDescription: reason.description || null, + failurePathOrDescriptor: + "pathOrDescriptor" in reason ? (reason.pathOrDescriptor ?? null) : null, + }; +} + +function formatPlatformFailure(attributes: PlatformFailureAttributes): string { + const tag = attributes.failureTag === null ? "" : `${attributes.failureTag}: `; + const path = + attributes.failurePathOrDescriptor === null + ? "" + : ` (${String(attributes.failurePathOrDescriptor)})`; + const description = + attributes.failureDescription === null ? "" : `: ${attributes.failureDescription}`; + return `${tag}${attributes.failureModule}.${attributes.failureMethod}${path}${description}`; +} + +class ProviderMaintenanceCommandSpawnError extends Schema.TaggedErrorClass()( + "ProviderMaintenanceCommandSpawnError", { - operation: Schema.Literals(["spawn", "collect"]), - command: Schema.optional(Schema.String), + command: Schema.String, + ...platformFailureFields, cause: Schema.Defect(), }, ) { override get message(): string { - const causeMessage = this.cause instanceof Error ? this.cause.message : undefined; - if (this.operation === "spawn") { - return `Failed to run update command ${this.command ?? "unknown"}${causeMessage ? `: ${causeMessage}` : "."}`; - } - return causeMessage ?? "Update command failed to run."; + return `Failed to run update command ${this.command}: ${formatPlatformFailure(this)}`; + } +} + +class ProviderMaintenanceCommandCollectError extends Schema.TaggedErrorClass()( + "ProviderMaintenanceCommandCollectError", + { + command: Schema.String, + ...platformFailureFields, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return formatPlatformFailure(this); } } @@ -89,9 +138,9 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR .pipe( Effect.mapError( (cause) => - new ProviderMaintenanceCommandError({ - operation: "spawn", + new ProviderMaintenanceCommandSpawnError({ command: input.command, + ...platformFailureAttributes(cause), cause, }), ), @@ -114,8 +163,9 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR ).pipe( Effect.mapError( (cause) => - new ProviderMaintenanceCommandError({ - operation: "collect", + new ProviderMaintenanceCommandCollectError({ + command: input.command, + ...platformFailureAttributes(cause), cause, }), ), diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index ce5a0afe92..607f061bf8 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -132,7 +132,7 @@ sequenceDiagram [5]: ../apps/server/src/wsServer/pushBus.ts [6]: ../packages/contracts/src/ws.ts [7]: ../apps/server/src/serverLayers.ts -[8]: ../apps/server/src/provider/Layers/ProviderService.ts +[8]: ../apps/server/src/provider/ProviderService.ts [9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts [10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts [11]: ../packages/contracts/src/orchestration.ts diff --git a/docs/operations/effect-fn-checklist.md b/docs/operations/effect-fn-checklist.md index 279b5646d3..add2ca9687 100644 --- a/docs/operations/effect-fn-checklist.md +++ b/docs/operations/effect-fn-checklist.md @@ -41,7 +41,7 @@ Effect.fn("name")( ## Suggested Order -- [ ] `apps/server/src/provider/Layers/ProviderService.ts` +- [ ] `apps/server/src/provider/ProviderService.ts` - [x] `apps/server/src/provider/Layers/ClaudeAdapter.ts` - [x] `apps/server/src/provider/Layers/CodexAdapter.ts` - [x] `apps/server/src/git/Layers/GitCore.ts` @@ -98,20 +98,20 @@ Effect.fn("name")( - [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305` - [x] Remaining apply helpers in this file -### `apps/server/src/provider/Layers/ProviderService.ts` (`24`) +### `apps/server/src/provider/ProviderService.ts` (`24`) -- [ ] [makeProviderService](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L134) -- [ ] [recoverSessionForThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L196) -- [ ] [resolveRoutableSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L255) -- [ ] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L284) -- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L347) -- [ ] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L393) -- [ ] [respondToRequest](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L411) -- [ ] [respondToUserInput](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L430) -- [ ] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L445) -- [ ] [listSessions](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L466) -- [ ] [rollbackConversation](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L516) -- [ ] [runStopAll](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L538) +- [ ] [makeProviderService](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L134) +- [ ] [recoverSessionForThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L196) +- [ ] [resolveRoutableSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L255) +- [ ] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L284) +- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L347) +- [ ] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L393) +- [ ] [respondToRequest](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L411) +- [ ] [respondToUserInput](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L430) +- [ ] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L445) +- [ ] [listSessions](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L466) +- [ ] [rollbackConversation](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L516) +- [ ] [runStopAll](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderService.ts#L538) ### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`) @@ -174,7 +174,7 @@ Effect.fn("name")( - [ ] [packages/shared/src/DrainableWorker.ts](/Users/julius/Development/Work/codething-mvp/packages/shared/src/DrainableWorker.ts) (`4`) - [ ] [apps/server/src/wsServer/pushBus.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer/pushBus.ts) (`4`) - [ ] [apps/server/src/wsServer.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer.ts) (`4`) -- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`) +- [ ] [apps/server/src/provider/ProviderRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderRegistry.ts) (`4`) - [ ] [apps/server/src/persistence/Layers/Sqlite.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Layers/Sqlite.ts) (`4`) - [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`) - [ ] [apps/server/src/main.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/main.ts) (`4`) @@ -183,7 +183,7 @@ Effect.fn("name")( - [ ] [apps/server/src/serverLayers.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/serverLayers.ts) (`3`) - [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`) - [ ] [apps/server/src/telemetry/Identify.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Identify.ts) (`2`) -- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`) +- [ ] [apps/server/src/provider/ProviderAdapterRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/ProviderAdapterRegistry.ts) (`2`) - [ ] [apps/server/src/provider/Layers/CodexProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexProvider.ts) (`2`) - [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`) - [ ] [apps/server/src/persistence/NodeSqliteClient.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/NodeSqliteClient.ts) (`2`) diff --git a/docs/reference/encyclopedia.md b/docs/reference/encyclopedia.md index 82a58fd959..e7f53c414b 100644 --- a/docs/reference/encyclopedia.md +++ b/docs/reference/encyclopedia.md @@ -167,7 +167,7 @@ The file patch and changed-file summary for one turn. It is usually computed in [11]: ../apps/server/src/orchestration/Layers/ProjectionPipeline.ts [12]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts [13]: ../apps/server/src/orchestration/Services/RuntimeReceiptBus.ts -[14]: ../apps/server/src/provider/Layers/ProviderService.ts +[14]: ../apps/server/src/provider/ProviderService.ts [15]: ../apps/server/src/provider/Services/ProviderAdapter.ts [16]: ./provider-architecture.md [17]: ../apps/server/src/provider/Layers/CodexAdapter.ts