Refactor provider Effect services

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-20 20:21:04 -07:00
1 parent 2a29de7502
commit 5f81c3a069
50 files changed
+3005 -3216

No files matched your search

@@ -10,20 +10,13 @@ import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
import * as ProviderService from "../src/provider/ProviderService.ts";
import * as ServerSettings from "../src/serverSettings.ts";
import * as AnalyticsService from "../src/telemetry/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
@@ -51,7 +44,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
readonly layer: Layer.Layer<ProviderService.ProviderService, unknown, never>;
}
const makeIntegrationFixture = Effect.gen(function* () {
@@ -62,19 +55,24 @@ const makeIntegrationFixture = Effect.gen(function* () {
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry),
ServerSettings.ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
const layer = Layer.effect(ProviderService.ProviderService, ProviderService.make()).pipe(
Layer.provide(shared),
);
return {
cwd,
@@ -105,7 +103,7 @@ const collectEventsDuring = <A, E, R>(
});
const runTurn = (input: {
readonly provider: ProviderServiceShape;
readonly provider: ProviderService.ProviderService["Service"];
readonly harness: TestProviderAdapterHarness;
readonly threadId: ThreadId;
readonly userText: string;
@@ -129,7 +127,7 @@ it.live("replays typed runtime fixture events", () =>
const fixture = yield* makeIntegrationFixture;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: ProviderDriverKind.make("codex"),
@@ -166,7 +164,7 @@ it.live("replays file-changing fixture turn events", () =>
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: ProviderDriverKind.make("codex"),
@@ -203,7 +201,7 @@ it.live("runs multi-turn tool/approval flow", () =>
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: ProviderDriverKind.make("codex"),
@@ -255,7 +253,7 @@ it.live("rolls back provider conversation state only", () =>
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: ProviderDriverKind.make("codex"),
@@ -24,8 +24,8 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
import {
@@ -33,7 +33,7 @@ import {
makePendingClaudeProvider,
probeClaudeCapabilities,
} from "../Layers/ClaudeProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -87,9 +87,9 @@ export type ClaudeDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig
| ServerSettingsService;
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -120,8 +120,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -32,12 +32,12 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
@@ -79,9 +79,9 @@ export type CodexDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig
| ServerSettingsService;
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
/**
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
@@ -117,8 +117,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const homeLayout = yield* resolveCodexHomeLayout(config);
const continuationIdentity = codexContinuationIdentity(homeLayout);
@@ -21,8 +21,8 @@ import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
@@ -31,7 +31,7 @@ import {
checkCursorProviderStatus,
enrichCursorSnapshot,
} from "../Layers/CursorProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -70,9 +70,9 @@ export type CursorDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig
| ServerSettingsService;
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -104,8 +104,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -8,8 +8,8 @@ import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
@@ -18,7 +18,7 @@ import {
checkGrokProviderStatus,
enrichGrokSnapshot,
} from "../Layers/GrokProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -54,9 +54,9 @@ export type GrokDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig
| ServerSettingsService;
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -86,8 +86,8 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -23,17 +23,17 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
checkOpenCodeProviderStatus,
makePendingOpenCodeProvider,
} from "../Layers/OpenCodeProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
@@ -82,11 +82,11 @@ export type OpenCodeDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| OpenCodeRuntime
| OpenCodeRuntime.OpenCodeRuntime
| Path.Path
| ProviderEventLoggers
| ServerConfig
| ServerSettingsService;
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -114,11 +114,11 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const openCodeRuntime = yield* OpenCodeRuntime;
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
const serverConfig = yield* ServerConfig.ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -147,7 +147,10 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
effectiveConfig,
serverConfig.cwd,
processEnv,
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
).pipe(
Effect.map(stampIdentity),
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
);
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
@@ -34,11 +34,11 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as CodexErrors from "effect-codex-app-server/errors";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
type CodexSessionRuntimeSendTurnInput,
@@ -211,14 +211,17 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
};
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const providerSessionDirectoryTestLayer = Layer.succeed(
ProviderSessionDirectory.ProviderSessionDirectory,
{
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
},
);
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
@@ -232,7 +235,7 @@ const validationLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -301,7 +304,7 @@ const sessionErrorLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -373,7 +376,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -427,7 +430,7 @@ const lifecycleLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1100,7 +1103,7 @@ const scopedLifecycleLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1144,7 +1147,7 @@ const scopedFailureLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1196,7 +1199,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -41,7 +41,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as Config from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterProcessError,
@@ -319,7 +319,7 @@ export function makeCursorAdapter(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverConfig = yield* Effect.service(Config.ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -32,7 +32,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as Config from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterProcessError,
@@ -176,7 +176,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverConfig = yield* Effect.service(Config.ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -20,15 +20,11 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import * as Config from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import {
appendOpenCodeAssistantTextDelta,
makeOpenCodeAdapter,
@@ -79,7 +75,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
runtimeMock.state.startCalls.push(binaryPath);
@@ -167,10 +163,12 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
})(),
}),
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
@@ -178,14 +176,17 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
),
};
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
});
const providerSessionDirectoryTestLayer = Layer.succeed(
ProviderSessionDirectory.ProviderSessionDirectory,
{
upsert: () => Effect.void,
getProvider: () =>
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
getBinding: () => Effect.succeed(Option.none()),
listThreadIds: () => Effect.succeed([]),
listBindings: () => Effect.succeed([]),
},
);
// The adapter now receives its settings as a plain argument (the old design
// read from `ServerSettingsService` internally). The test-only
@@ -203,10 +204,10 @@ const OpenCodeAdapterTestLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
ServerSettings.ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -334,9 +335,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -480,9 +483,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -527,9 +530,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -569,9 +572,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -792,10 +795,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
nativeEventLogger,
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettings.ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -874,10 +879,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
nativeEventLogger,
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettingsService.layerTest({
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettings.ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -8,14 +8,10 @@ import * as Schema from "effect/Schema";
import { beforeEach } from "vite-plus/test";
import { OpenCodeSettings } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import * as Config from "../../config.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
@@ -52,7 +48,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
startOpenCodeServerProcess: () =>
Effect.succeed({
url: "http://127.0.0.1:4301",
@@ -76,7 +72,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
runOpenCodeCommand: () =>
runtimeMock.state.runVersionError
? Effect.fail(
new OpenCodeRuntimeError({
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "runOpenCodeCommand",
detail: runtimeMock.state.runVersionError.message,
cause: runtimeMock.state.runVersionError,
@@ -84,25 +80,27 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
)
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
createOpenCodeSdkClient: () =>
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
({}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
loadOpenCodeInventory: () =>
runtimeMock.state.inventoryError
? Effect.fail(
new OpenCodeRuntimeError({
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: runtimeMock.state.inventoryError.message,
cause: runtimeMock.state.inventoryError,
}),
)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
: Effect.succeed(runtimeMock.state.inventory as OpenCodeRuntime.OpenCodeInventory),
};
beforeEach(() => {
runtimeMock.reset();
});
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
const testLayer = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -1,117 +0,0 @@
/**
* ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
*
* `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
* adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
* refactor moved adapter construction inside each `ProviderDriver.create()`:
* adapters are now bundled on the `ProviderInstance` that the
* `ProviderInstanceRegistry` owns.
*
* This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
* dynamic look-ups against `ProviderInstanceRegistry` on every call. That
* means settings-driven hot-reload shows up here automatically — adding a
* new instance via settings makes `getByInstance` resolve immediately
* without rebuilding the facade.
*
* @module ProviderAdapterRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ProviderUnsupportedError } from "../Errors.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
const registry = yield* ProviderInstanceRegistry;
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed(instance.adapter),
),
);
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
displayName: instance.displayName,
accentColor: instance.accentColor,
enabled: instance.enabled,
continuationIdentity: instance.continuationIdentity,
}),
),
);
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
);
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => {
const kinds = new Set<ProviderDriverKind>();
for (const instance of instances) {
const defaultId = defaultInstanceIdForDriver(instance.driverKind);
if (instance.instanceId === defaultId) {
// Only the default-instance rows show up through the legacy
// shim — custom instances like `codex_personal` have no
// `ProviderDriverKind` equivalent.
kinds.add(instance.driverKind);
}
}
return Array.from(kinds);
}),
);
return {
getByInstance,
getInstanceInfo,
listInstances,
listProviders,
// Proxy directly — the facade has no state of its own; the instance
// registry already coalesces adds/removes/rebuilds into one emission.
streamChanges: registry.streamChanges,
subscribeChanges: registry.subscribeChanges,
} satisfies ProviderAdapterRegistryShape;
});
export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
makeProviderAdapterRegistry(),
);
// Exposed for tests that want to build a facade over a pre-assembled
// `ProviderInstanceRegistry` without pulling in the whole boot graph.
export { makeProviderAdapterRegistry };
// Re-export for consumers that need the accessor shape. The service tag
// itself lives in `Services/ProviderAdapterRegistry.ts`.
export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
// Re-export for consumers (including tests) that construct a
// `ProviderInstanceId` before calling `getByInstance`.
export { ProviderInstanceId };
@@ -1,85 +1,6 @@
/**
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
* - `canonical` — runtime events after `ProviderService` has normalized
* them onto `ProviderRuntimeEvent`.
*
* Why a service tag and not constructor options?
*
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/Layers/ProviderEventLoggers
*/
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
// Compatibility shim for the intentionally excluded orchestration harness.
import * as Canonical from "../ProviderEventLoggers.ts";
import { ServerConfig } from "../../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger | undefined;
}
/**
* Shared logger pair for native + canonical provider event streams.
*
* Service value is intentionally a struct of two optional loggers rather
* than two parallel tags. Construction site is one place
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
* one tag and pluck the field they need.
*/
export class ProviderEventLoggers extends Context.Service<
ProviderEventLoggers,
ProviderEventLoggersShape
>()("t3/provider/Layers/ProviderEventLoggers") {}
/**
* Constant value used by tests / boot layers that want to opt out of native
* + canonical logging entirely. Keeps the tag non-optional in the type
* system while letting the runtime treat absence as a no-op.
*/
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
native: undefined,
canonical: undefined,
};
/**
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
return {
native,
canonical,
} satisfies ProviderEventLoggersShape;
}),
);
export const ProviderEventLoggersLive = Canonical.layer;
export const ProviderEventLoggers = Canonical.ProviderEventLoggers;
export const NoOpProviderEventLoggers = Canonical.NoOpProviderEventLoggers;
@@ -29,7 +29,7 @@
* ----------
* On layer build we:
* 1. Read the current `ServerSettings` once and use it to seed the
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
* registry's initial state via `ProviderInstanceRegistry.mutableLayer`.
* 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
* subscribes to `ServerSettingsService.streamChanges` and calls
* `ProviderInstanceRegistryMutator.reconcile` on every emission.
@@ -51,11 +51,9 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as ServerSettingsModule from "../../serverSettings.ts";
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
import * as ProviderInstanceRegistry from "../ProviderInstanceRegistry.ts";
/**
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
@@ -116,8 +114,8 @@ export const deriveProviderInstanceConfigMap = (
*/
const SettingsWatcherLive = Layer.effectDiscard(
Effect.gen(function* () {
const mutator = yield* ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsService;
const mutator = yield* ProviderInstanceRegistry.ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
yield* serverSettings.streamChanges.pipe(
Stream.runForEach((next) =>
mutator
@@ -138,7 +136,7 @@ const SettingsWatcherLive = Layer.effectDiscard(
* sync with subsequent `streamChanges` emissions.
*
* The Layer's two halves:
* - `ProviderInstanceRegistryMutableLayer` produces the registry +
* - `ProviderInstanceRegistry.mutableLayer` produces the registry +
* mutator from the initial config map. Its scope owns every
* per-instance child scope created during reconcile.
* - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
@@ -150,12 +148,12 @@ const SettingsWatcherLive = Layer.effectDiscard(
* it, so the visibility leak is harmless in practice.
*/
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
ProviderInstanceRegistry,
ProviderInstanceRegistry.ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsService
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
> = Layer.unwrap(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
Effect.orElseSucceed(() => undefined),
);
@@ -164,11 +162,15 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
? ({} as ProviderInstanceConfigMap)
: deriveProviderInstanceConfigMap(initialSettings);
const mutableLayer = ProviderInstanceRegistryMutableLayer({
const mutableLayer = ProviderInstanceRegistry.mutableLayer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
});
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
}),
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
) as Layer.Layer<
ProviderInstanceRegistry.ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
>;
@@ -1,698 +0,0 @@
/**
* ProviderRegistryLive — aggregates per-instance snapshot streams into a
* single materialized list.
*
* Historically this Layer composed four per-kind Live Layers
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
* `ServerProviderShape`. Those Lives were deleted during the driver /
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
* bundled onto the `ProviderInstance` the registry produces.
*
* Each configured instance (including multi-instance setups like
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
* keyed by `instanceId`. Instances whose driver is unavailable or whose
* config failed to decode are merged from `instanceRegistry.listUnavailable`
* as shadow snapshots so the UI can render their exact unavailable reason.
*
* Cache paths on disk are now keyed by `instanceId`. Because
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
* `<kind>.json` files remain the on-disk location for that driver's default
* instance. Identity-less legacy cache contents are ignored and replaced by
* the first live refresh.
*
* @module ProviderRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
type ServerProviderUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "../../config.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import {
hydrateCachedProvider,
isCachedProviderCorrelated,
orderProviderSnapshots,
readProviderStatusCache,
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "../providerStatusCache.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
const loadProviders = (
providerSources: ReadonlyArray<ProviderSnapshotSource>,
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
Effect.forEach(
providerSources,
(providerSource) =>
providerSource.getSnapshot.pipe(
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
),
{
concurrency: "unbounded",
},
);
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
makeManualOnlyProviderMaintenanceCapabilities({
provider,
packageName: null,
});
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
const mergeProviderModels = (
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
): ReadonlyArray<ServerProvider["models"][number]> => {
if (nextModels.length === 0 && previousModels.length > 0) {
return previousModels;
}
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
const mergedModels = nextModels.map((model) => {
const previousModel = previousBySlug.get(model.slug);
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
return model;
}
return {
...model,
capabilities: previousModel.capabilities,
};
});
const nextSlugs = new Set(nextModels.map((model) => model.slug));
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
};
export const mergeProviderSnapshot = (
previousProvider: ServerProvider | undefined,
nextProvider: ServerProvider,
): ServerProvider =>
!previousProvider
? nextProvider
: {
...nextProvider,
models: mergeProviderModels(previousProvider.models, nextProvider.models),
};
export const mergeProviderSnapshots = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): ReadonlyArray<ServerProvider> => {
const mergedProviders = new Map(
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
);
for (const provider of nextProviders) {
mergedProviders.set(
snapshotInstanceKey(provider),
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
);
}
return orderProviderSnapshots([...mergedProviders.values()]);
};
export const selectProvidersByKind = (
providers: ReadonlyArray<ServerProvider>,
providerKinds: ReadonlySet<ProviderDriverKind>,
): ReadonlyArray<ServerProvider> =>
providers.filter((provider) => providerKinds.has(provider.driver));
export const haveProvidersChanged = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): boolean => !Equal.equals(previousProviders, nextProviders);
const correlateSnapshotWithSource = (
source: ProviderSnapshotSource,
snapshot: ServerProvider,
): Effect.Effect<ServerProvider> => {
if (snapshot.instanceId !== source.instanceId) {
return Effect.die(
new Error(
`Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
),
);
}
if (snapshot.driver !== source.driverKind) {
return Effect.die(
new Error(
`Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
),
);
}
return Effect.succeed(snapshot);
};
/**
* Key a snapshot for aggregation and persistence. Snapshot sources
* must be correlated by instance id before reaching this map; missing
* identities are defects, not runtime routing fallbacks.
*/
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
return provider.instanceId;
};
// Project a live `ProviderInstance` into the aggregator's consumption
// shape. Each call re-captures the instance's `snapshot` closures, so
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
// its settings changed), a fresh source rides the new PubSub instead
// of a closed one.
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
getSnapshot: instance.snapshot.getSnapshot,
refresh: instance.snapshot.refresh,
streamChanges: instance.snapshot.streamChanges,
});
export const ProviderRegistryLive = Layer.effect(
ProviderRegistry,
Effect.gen(function* () {
const instanceRegistry = yield* ProviderInstanceRegistry;
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
// coalesced updates across every instance.
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
// Boot-only: hydrate `providersRef` from the on-disk per-instance
// cache so the UI has something to render during the first refresh.
// Instances added post-boot skip this path; their first entry in
// `providersRef` comes from the reactive `syncLiveSources` pass
// below.
const bootInstances = yield* instanceRegistry.listInstances;
const bootSources = bootInstances.map(buildSnapshotSource);
const fallbackProviders = yield* loadProviders(bootSources);
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
for (let index = 0; index < fallbackProviders.length; index++) {
const provider = fallbackProviders[index];
const source = bootSources[index];
if (provider === undefined || source === undefined) {
continue;
}
fallbackByInstance.set(source.instanceId, provider);
}
const cachedProviders = yield* Effect.forEach(
bootSources,
(source) =>
Effect.gen(function* () {
// One cache file per configured instance. For the default
// instance of a built-in kind the path equals `<kind>.json` —
// identical to the legacy filename. We still require the cache
// payload to carry matching instance id + driver kind; old
// identity-less payloads are discarded and the awaited refresh
// below repopulates the cache.
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: source.instanceId,
}).pipe(Effect.provideService(Path.Path, path));
const fallbackProvider = fallbackByInstance.get(source.instanceId);
if (fallbackProvider === undefined) {
return undefined;
}
return yield* readProviderStatusCache(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.flatMap((cachedProvider) => {
if (cachedProvider === undefined) {
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
}
const correlation = {
cachedProvider,
fallbackProvider,
} as const;
if (!isCachedProviderCorrelated(correlation)) {
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
path: filePath,
instanceId: source.instanceId,
cachedInstanceId: cachedProvider.instanceId ?? null,
driver: source.driverKind,
cachedDriver: cachedProvider.driver ?? null,
}).pipe(Effect.as(undefined as ServerProvider | undefined));
}
return Effect.succeed(hydrateCachedProvider(correlation));
}),
);
}),
{ concurrency: "unbounded" },
).pipe(
Effect.map((providers) =>
orderProviderSnapshots(
providers.filter((provider): provider is ServerProvider => provider !== undefined),
),
),
);
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
const maintenanceActionStatesRef = yield* Ref.make<
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
>(new Map());
// Live-source registry — the dynamic counterpart to the boot-time
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
// reference is used for identity equality so "no-op" reconciles
// (settings unchanged) skip re-subscribing + re-probing.
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
new Map(),
);
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
// interleave two passes clobbering each other's fiber bookkeeping.
const syncSemaphore = yield* Semaphore.make(1);
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
liveSubsRef,
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
const persistProvider = (provider: ServerProvider) =>
Effect.gen(function* () {
// Persist every instance — the file name is the instance id, so
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
// get their own cache. We resolve the path fresh so snapshots
// produced by newly-added instances post-boot still land on disk
// without the aggregator holding a stale `cachePathByInstance`
// entry.
const key = snapshotInstanceKey(provider);
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: key,
}).pipe(Effect.provideService(Path.Path, path));
yield* writeProviderStatusCache({ filePath, provider }).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.tapError(Effect.logError),
Effect.ignore,
);
});
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
provider: ServerProvider,
) {
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
if (!updateState) {
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
return providerWithoutUpdateState;
}
return {
...provider,
updateState,
};
});
const upsertProviders = Effect.fn("upsertProviders")(function* (
nextProviders: ReadonlyArray<ServerProvider>,
options?: {
readonly publish?: boolean;
readonly persist?: boolean;
readonly replace?: boolean;
},
) {
const nextProvidersWithUpdateState = yield* Effect.forEach(
nextProviders,
applyProviderUpdateState,
{
concurrency: "unbounded",
},
);
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const mergedProviders = new Map(
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
);
const updatedKeys = new Set<ProviderInstanceId>();
for (const provider of nextProvidersWithUpdateState) {
const key = snapshotInstanceKey(provider);
updatedKeys.add(key);
mergedProviders.set(
key,
options?.replace === true
? provider
: mergeProviderSnapshot(mergedProviders.get(key), provider),
);
}
const providers = orderProviderSnapshots([...mergedProviders.values()]);
const providersToPersist = providers.filter((provider) =>
updatedKeys.has(snapshotInstanceKey(provider)),
);
return [[previousProviders, providers, providersToPersist] as const, providers];
},
);
if (haveProvidersChanged(previousProviders, providers)) {
if (options?.persist !== false) {
yield* Effect.forEach(providersToPersist, persistProvider, {
concurrency: "unbounded",
discard: true,
});
}
if (options?.publish !== false) {
yield* PubSub.publish(changesPubSub, providers);
}
}
return providers;
});
const syncProvider = Effect.fn("syncProvider")(function* (
provider: ServerProvider,
options?: {
readonly publish?: boolean;
},
) {
return yield* upsertProviders([provider], options);
});
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
function* (input: {
readonly instanceId: ProviderInstanceId;
readonly action: "update";
readonly state: ServerProviderUpdateState | null;
}) {
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
const previousActions = previous.get(input.instanceId);
const nextActions = { ...previousActions };
if (input.state === null || input.state.status === "idle") {
delete nextActions[input.action];
} else {
nextActions[input.action] = input.state;
}
const next = new Map(previous);
if (Object.keys(nextActions).length === 0) {
next.delete(input.instanceId);
} else {
next.set(input.instanceId, nextActions);
}
return next;
});
const existingProviders = yield* Ref.get(providersRef);
const matchingProvider = existingProviders.find(
(candidate) => candidate.instanceId === input.instanceId,
);
if (!matchingProvider) {
return existingProviders;
}
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
return yield* upsertProviders([nextProvider], {
persist: false,
});
},
);
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
providerSource: ProviderSnapshotSource,
) {
return yield* providerSource.refresh.pipe(
Effect.flatMap((nextProvider) =>
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
Effect.flatMap(syncProvider),
),
),
);
});
const refreshAll = Effect.fn("refreshAll")(function* () {
const sources = yield* getLiveSources;
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.andThen(Ref.get(providersRef)));
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
if (provider === undefined) {
return yield* refreshAll();
}
// Kind-scoped refreshes target the default instance for that driver.
const defaultInstanceId = defaultInstanceIdForDriver(provider);
const sources = yield* getLiveSources;
const providerSource = sources.find(
(candidate) => candidate.instanceId === defaultInstanceId,
);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
const refreshInstance = Effect.fn("refreshInstance")(function* (
instanceId: ProviderInstanceId,
) {
const sources = yield* getLiveSources;
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
"getProviderMaintenanceCapabilitiesForInstance",
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
(candidate) => candidate.instanceId === instanceId,
);
return (
instance?.snapshot.maintenanceCapabilities ??
makeManualProviderMaintenanceCapabilities(provider)
);
});
/**
* Diff the aggregator's live-source set against the current
* `ProviderInstanceRegistry` and:
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - prune `providersRef` of instances that no longer exist.
*
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
* down and our `Stream.runForEach` fiber exits naturally.
*/
const syncLiveSources = syncSemaphore.withPermits(1)(
Effect.gen(function* () {
const instances = yield* instanceRegistry.listInstances;
const unavailableProviders = yield* instanceRegistry.listUnavailable;
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
instances.map((instance) => [instance.instanceId, instance] as const),
);
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
for (const provider of unavailableProviders) {
knownInstanceIds.add(snapshotInstanceKey(provider));
}
const previousSubs = yield* Ref.get(liveSubsRef);
// Carry over subscriptions for instances whose identity is
// unchanged (reconcile treated them as no-op). Instances that
// disappeared, or were rebuilt with a different reference,
// fall through to the "newly-added" branch below.
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
for (const [instanceId, previousInstance] of previousSubs) {
const nextInstance = nextByInstance.get(instanceId);
if (nextInstance !== undefined && nextInstance === previousInstance) {
carriedOver.set(instanceId, previousInstance);
}
}
// Collect new/rebuilt instances in `nextByInstance` insertion
// order (which preserves settings-author order).
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
for (const [instanceId, instance] of nextByInstance) {
if (carriedOver.has(instanceId)) {
continue;
}
newlyAdded.push([instanceId, instance] as const);
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
persist: false,
replace: true,
});
const nextSubs = new Map(carriedOver);
for (const [instanceId, instance] of newlyAdded) {
nextSubs.set(instanceId, instance);
}
yield* Ref.set(liveSubsRef, nextSubs);
// Drop aggregator state for instances that have disappeared —
// otherwise the UI would keep rendering ghosts.
const [previousProviders, providers] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const providers = orderProviderSnapshots(
previousProviders.filter((provider) =>
knownInstanceIds.has(snapshotInstanceKey(provider)),
),
);
return [[previousProviders, providers] as const, providers];
},
);
if (haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
const next = new Map(previous);
for (const instanceId of previous.keys()) {
if (!knownInstanceIds.has(instanceId)) {
next.delete(instanceId);
}
}
return next;
});
}),
);
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
}
return Effect.logError(
"provider registry instance sync failed; keeping subscription alive",
{
cause: Cause.pretty(cause),
},
);
}),
);
// Seed `providersRef` with the boot-time fallback snapshots so
// consumers calling `getProviders` immediately after layer build see
// a populated list — even before the first `syncLiveSources` refresh
// resolves. Cached snapshots (already in `providersRef`) merge with
// these via `upsertProviders` so on-disk state wins where present
// 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
// buffered in the subscription regardless of when the consumer
// fibre below actually starts running.
//
// (Contrast with the pre-fix code that did
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
// schedules the consumer fibre — so a reconcile that published
// between "fibre scheduled" and "fibre starts running + subscribes"
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
// subscription rather than subscribing on stream start, which is
// what closes the race.
yield* Stream.runForEach(
Stream.fromSubscription(instanceChanges),
() => syncLiveSourcesAndContinue,
).pipe(Effect.forkScoped);
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
cause: Cause.Cause<unknown>,
) {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.interrupt;
}
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
cause: Cause.pretty(cause),
});
return yield* Ref.get(providersRef);
});
return {
getProviders: Ref.get(providersRef),
refresh: (provider?: ProviderDriverKind) =>
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
refreshInstance: (instanceId: ProviderInstanceId) =>
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
getProviderMaintenanceCapabilitiesForInstance,
setProviderMaintenanceActionState,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ProviderRegistryShape;
}),
);
File diff suppressed because it is too large. Load diff
@@ -1,201 +1,6 @@
import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
// Compatibility shim for the intentionally excluded orchestration harness.
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
type ProviderRuntimeBindingWithMetadata,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
export const ProviderSessionDirectoryLive = ProviderSessionDirectory.layer;
function toPersistenceError(operation: string) {
return (cause: unknown) =>
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Failed to execute ${operation}.`,
cause,
});
}
function decodeProviderDriverKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
return decodeProviderDriverKindValue(providerName).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Unknown persisted provider '${providerName}'.`,
cause,
}),
),
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function mergeRuntimePayload(
existing: unknown | null,
next: unknown | null | undefined,
): unknown | null {
if (next === undefined) {
return existing ?? null;
}
if (isRecord(existing) && isRecord(next)) {
return { ...existing, ...next };
}
return next;
}
function toRuntimeBinding(
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
// Migration boundary only: rows written before the instance split
// have a null provider_instance_id. Promote them as they leave
// persistence so hot routing code never has to infer an instance
// from a driver kind.
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
resumeCursor: runtime.resumeCursor,
runtimePayload: runtime.runtimePayload,
lastSeenAt: runtime.lastSeenAt,
}) satisfies ProviderRuntimeBindingWithMetadata,
),
);
}
const makeProviderSessionDirectory = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const getBinding = (threadId: ThreadId) =>
repository.getByThreadId({ threadId }).pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
Effect.flatMap((runtime) =>
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((binding) => Option.some(binding)),
),
}),
),
);
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
const existing = yield* repository
.getByThreadId({ threadId: binding.threadId })
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
const existingRuntime = Option.getOrUndefined(existing);
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
if (!resolvedThreadId) {
return yield* new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "threadId must be a non-empty string.",
});
}
const now = DateTime.formatIso(yield* DateTime.now);
const providerChanged =
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
const providerInstanceId =
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
if (providerInstanceId === null || providerInstanceId === undefined) {
return yield* new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "providerInstanceId is required for provider session runtime bindings.",
});
}
yield* repository
.upsert({
threadId: resolvedThreadId,
providerName: binding.provider,
providerInstanceId,
adapterKey:
binding.adapterKey ??
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
status: binding.status ?? existingRuntime?.status ?? "running",
lastSeenAt: now,
resumeCursor:
binding.resumeCursor !== undefined
? binding.resumeCursor
: (existingRuntime?.resumeCursor ?? null),
runtimePayload: mergeRuntimePayload(
existingRuntime?.runtimePayload ?? null,
binding.runtimePayload,
),
})
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
});
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
getBinding(threadId).pipe(
Effect.flatMap((binding) =>
Option.match(binding, {
onSome: (value) => Effect.succeed(value.provider),
onNone: () =>
Effect.fail(
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.getProvider",
detail: `No persisted provider binding found for thread '${threadId}'.`,
}),
),
}),
),
);
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
{ concurrency: "unbounded" },
),
),
);
return {
upsert,
getProvider,
getBinding,
listThreadIds,
listBindings,
} satisfies ProviderSessionDirectoryShape;
});
export const ProviderSessionDirectoryLive = Layer.effect(
ProviderSessionDirectory,
makeProviderSessionDirectory,
);
export function makeProviderSessionDirectoryLive() {
return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);
}
export const makeProviderSessionDirectoryLive = () => ProviderSessionDirectory.layer;
@@ -10,16 +10,15 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import type * as ClaudeAdapter from "../Services/ClaudeAdapter.ts";
import type * as CodexAdapter from "../Services/CodexAdapter.ts";
import type * as CursorAdapter from "../Services/CursorAdapter.ts";
import type * as OpenCodeAdapter from "../Services/OpenCodeAdapter.ts";
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";
import * as ProviderAdapterRegistryLayer from "./ProviderAdapterRegistry.ts";
import type { ClaudeAdapterShape } from "./Services/ClaudeAdapter.ts";
import type { CodexAdapterShape } from "./Services/CodexAdapter.ts";
import type { CursorAdapterShape } from "./Services/CursorAdapter.ts";
import type { OpenCodeAdapterShape } from "./Services/OpenCodeAdapter.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "./ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
@@ -27,7 +26,7 @@ const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
const fakeCodexAdapter: CodexAdapterShape = {
provider: CODEX_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -44,7 +43,7 @@ const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: CLAUDE_AGENT_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -61,7 +60,7 @@ const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: OPENCODE_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -78,7 +77,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
const fakeCursorAdapter: CursorAdapterShape = {
provider: CURSOR_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -95,7 +94,7 @@ const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
streamEvents: Stream.empty,
};
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
// ProviderAdapterRegistry is a facade over ProviderInstanceRegistry —
// it walks `listInstances` once at boot and surfaces the default-instance
// adapter keyed by its driver kind. To test the facade we supply four fake
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
@@ -147,14 +146,11 @@ const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.Provide
});
const layer = Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
fakeInstanceRegistryLayer,
),
Layer.provide(ProviderAdapterRegistry.layer, fakeInstanceRegistryLayer),
NodeServices.layer,
);
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
it.layer(layer)("ProviderAdapterRegistry", (it) => {
it("resolves adapters and routing metadata from provider instances", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
@@ -0,0 +1,150 @@
/**
* ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.
*
* Maps a `ProviderInstanceId` (the new per-instance routing key) or a
* `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete
* adapter service (Codex, Claude, etc). It does not own session lifecycle
* or routing rules; `ProviderService` uses this registry together with
* `ProviderSessionDirectory`.
*
* During the driver/instance migration this tag exposes both flavours:
*
* - `getByInstance` / `listInstances` — new per-instance routing. Callers
* that already know an `instanceId` (threads, sessions, events)
* should prefer these.
* (`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.
*
* @module ProviderAdapterRegistry
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderDriverKind,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as PubSub from "effect/PubSub";
import type * as Scope from "effect/Scope";
import type * as Stream from "effect/Stream";
import { ProviderUnsupportedError, type ProviderAdapterError } from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import type { ProviderContinuationIdentity } from "./ProviderDriver.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
export interface ProviderInstanceRoutingInfo {
readonly instanceId: ProviderInstanceId;
readonly driverKind: ProviderDriverKind;
readonly displayName: string | undefined;
readonly accentColor?: string | undefined;
readonly enabled: boolean;
readonly continuationIdentity: ProviderContinuationIdentity;
}
export class ProviderAdapterRegistry extends Context.Service<
ProviderAdapterRegistry,
{
/**
* Resolve the adapter for a specific instance id. Returns
* `ProviderUnsupportedError` if no such live instance is registered.
*/
readonly getByInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;
/** Resolve routing metadata for a specific live provider instance. */
readonly getInstanceInfo: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
/**
* List every live instance id. Unavailable shadow instances are excluded
* because callers use these ids with `getByInstance`.
*/
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
/**
* 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.
*/
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
/**
* Emits whenever the live instance set changes. Consumers should re-read
* `listInstances` and reconcile their per-instance subscriptions.
*/
readonly streamChanges: Stream.Stream<void>;
/**
* Acquire the change subscription synchronously in the caller's scope,
* avoiding the publish race inherent in forking `Stream.fromPubSub`.
*/
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
}
>()("t3/provider/ProviderAdapterRegistry") {}
export const make = Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
const getByInstance: ProviderAdapterRegistry["Service"]["getByInstance"] = (instanceId) =>
registry
.getInstance(instanceId)
.pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(new ProviderUnsupportedError({ provider: instanceId }))
: Effect.succeed(instance.adapter),
),
);
const getInstanceInfo: ProviderAdapterRegistry["Service"]["getInstanceInfo"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(new ProviderUnsupportedError({ provider: instanceId }))
: Effect.succeed({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
displayName: instance.displayName,
accentColor: instance.accentColor,
enabled: instance.enabled,
continuationIdentity: instance.continuationIdentity,
}),
),
);
const listInstances: ProviderAdapterRegistry["Service"]["listInstances"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
);
const listProviders: ProviderAdapterRegistry["Service"]["listProviders"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => {
const kinds = new Set<ProviderDriverKind>();
for (const instance of instances) {
if (instance.instanceId === defaultInstanceIdForDriver(instance.driverKind)) {
kinds.add(instance.driverKind);
}
}
return Array.from(kinds);
}),
);
return ProviderAdapterRegistry.of({
getByInstance,
getInstanceInfo,
listInstances,
listProviders,
streamChanges: registry.streamChanges,
subscribeChanges: registry.subscribeChanges,
});
});
export const layer = Layer.effect(ProviderAdapterRegistry, make);
@@ -0,0 +1,79 @@
/**
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
* - `canonical` — runtime events after `ProviderService` has normalized
* them onto `ProviderRuntimeEvent`.
*
* Why a service tag and not constructor options?
*
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/ProviderEventLoggers
*/
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Config from "../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
/**
* Shared logger pair for native + canonical provider event streams.
*
* Service value is intentionally a struct of two optional loggers rather
* than two parallel tags. Construction site is one place
* (`layer`); consumers (drivers, `ProviderService`) read
* one tag and pluck the field they need.
*/
export class ProviderEventLoggers extends Context.Service<
ProviderEventLoggers,
{
readonly native: EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger | undefined;
}
>()("t3/provider/ProviderEventLoggers") {}
/**
* Constant value used by tests / boot layers that want to opt out of native
* + canonical logging entirely. Keeps the tag non-optional in the type
* system while letting the runtime treat absence as a no-op.
*/
export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
native: undefined,
canonical: undefined,
};
/**
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
*/
export const make = Effect.gen(function* () {
const { providerEventLogPath } = yield* Config.ServerConfig;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
return ProviderEventLoggers.of({ native, canonical });
});
export const layer = Layer.effect(ProviderEventLoggers, make);
@@ -1,5 +1,5 @@
/**
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
* Multi-instance validation slices for `ProviderInstanceRegistry`.
*
* Two axes of the driver/registry refactor are exercised here:
*
@@ -38,16 +38,16 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { GrokDriver } from "../Drivers/GrokDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
import * as Config from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { ClaudeDriver } from "./Drivers/ClaudeDriver.ts";
import { CodexDriver } from "./Drivers/CodexDriver.ts";
import { CursorDriver } from "./Drivers/CursorDriver.ts";
import { GrokDriver } from "./Drivers/GrokDriver.ts";
import { OpenCodeDriver } from "./Drivers/OpenCodeDriver.ts";
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
const TestHttpClientLive = Layer.succeed(
HttpClient.HttpClient,
@@ -98,19 +98,24 @@ const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSetti
...overrides,
});
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
// directory. `Layer.merge` just unions requirements, so we have to push
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
// dependency while still surfacing NodeServices to the test body (the
// codex driver's `create` yields `ChildProcessSpawner` directly).
const testLayer = ServerConfig.layerTest(process.cwd(), {
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
);
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
@@ -142,7 +147,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* ProviderInstanceRegistry.make({
drivers: [CodexDriver],
configMap,
});
@@ -208,7 +213,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* ProviderInstanceRegistry.make({
drivers: [CodexDriver],
configMap,
});
@@ -228,27 +233,32 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
);
});
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
describe("ProviderInstanceRegistry — all drivers slice", () => {
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
// at construction time, so we wire `OpenCodeRuntime.layer` into the stack.
// `OpenCodeRuntime.layer` bundles its own `NetService.layer` via
// `Layer.provide`, so the only external requirement it still exposes is
// `ChildProcessSpawner` — resolved here by piping it through
// `provideMerge(NodeServices.layer)`.
//
// The nested `provideMerge`s read bottom-up: `NodeServices.layer`
// provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
// provides `OpenCodeRuntime.layer`'s deps while keeping its own outputs
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
// `FileSystem` dep while keeping everything else surfaced to the test.
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = ServerConfig.layerTest(process.cwd(), {
const infraLayer = OpenCodeRuntime.layer.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
);
it.live("boots one instance of every shipped driver from a single config map", () =>
@@ -301,7 +311,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* ProviderInstanceRegistry.make({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
configMap,
});
@@ -1,5 +1,5 @@
/**
* ProviderInstanceRegistryLive — runtime implementation of
* ProviderInstanceRegistry — runtime implementation of
* `ProviderInstanceRegistry` plus its sibling mutator.
*
* Materializes every entry in a `ProviderInstanceConfigMap`:
@@ -30,7 +30,7 @@
* tears every instance down in reverse order; closing a single instance
* (via `reconcile` removing it) leaves the rest untouched.
*
* @module provider/Layers/ProviderInstanceRegistryLive
* @module provider/ProviderInstanceRegistry
*/
import {
defaultInstanceIdForDriver,
@@ -51,16 +51,69 @@ import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
import {
import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts";
import type { AnyProviderDriver, ProviderInstance } from "./ProviderDriver.ts";
export class ProviderInstanceRegistry extends Context.Service<
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../Services/ProviderInstanceRegistry.ts";
import {
{
/**
* Look up one instance by id. Unknown ids return `undefined`; callers map
* that absence to the appropriate domain error.
*/
readonly getInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstance | undefined>;
/**
* Every successfully materialized instance, in stable settings-author
* order.
*/
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
/**
* Shadow snapshots for unknown drivers or invalid configurations, ready
* to merge into `ProviderRegistry` output.
*/
readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Emits after the registry adds, removes, or rebuilds instances. The
* payload is `void` because consumers re-read both registry lists.
*
* `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.
*/
readonly streamChanges: Stream.Stream<void>;
/**
* Acquire a scoped PubSub subscription synchronously before forking the
* consumer loop, ensuring subsequent publishes cannot land in a gap.
*/
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
}
>()("t3/provider/ProviderInstanceRegistry") {}
/**
* Internal mutation boundary used only by registry hydration.
*
* `reconcile` diffs by instance id, closes removed or replaced child scopes
* before creating replacements, materializes additions in fresh child scopes,
* and publishes one change tick after the batch. Reapplying an unchanged map
* is a no-op.
*/
export class ProviderInstanceRegistryMutator extends Context.Service<
ProviderInstanceRegistryMutator,
type ProviderInstanceRegistryMutatorShape,
} from "../Services/ProviderInstanceRegistryMutator.ts";
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
{
/**
* Reconcile the live registry with a new configuration map. Individual
* driver creation failures become unavailable shadow snapshots so the
* settings watcher itself never fails.
*/
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
}
>()("t3/provider/ProviderInstanceRegistry/ProviderInstanceRegistryMutator") {}
/**
* Live registry entry: the materialized `ProviderInstance` + the fresh
@@ -315,9 +368,9 @@ const makeReconcile = <R>(input: {
* Build the registry's runtime state from a concrete configMap. Returns a
* record containing:
*
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
* - `registry`: the read-only `ProviderInstanceRegistry["Service"]` to expose
* under `ProviderInstanceRegistry`.
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
* - `mutator`: the `ProviderInstanceRegistryMutator["Service"]` to expose
* under `ProviderInstanceRegistryMutator`.
* - `reconcile`: the raw reconcile function, provided for convenience so
* boot-time layers can hydrate an initial map before publishing the
@@ -327,13 +380,13 @@ const makeReconcile = <R>(input: {
* created during `reconcile`. Closing that scope closes every live
* instance.
*/
export const makeProviderInstanceRegistry = <R>(input: {
export const make = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Effect.Effect<
{
readonly registry: ProviderInstanceRegistryShape;
readonly mutator: ProviderInstanceRegistryMutatorShape;
readonly registry: ProviderInstanceRegistry["Service"];
readonly mutator: ProviderInstanceRegistryMutator["Service"];
},
never,
R | Scope.Scope
@@ -362,14 +415,14 @@ export const makeProviderInstanceRegistry = <R>(input: {
const state: RegistryState = { entries, unavailable, changes };
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
const reconcile: ProviderInstanceRegistryMutator["Service"]["reconcile"] = (configMap) =>
reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
// Hydrate the initial configMap synchronously so callers can read
// `listInstances` immediately after this effect completes.
yield* reconcile(input.configMap);
const registry: ProviderInstanceRegistryShape = {
const registry = ProviderInstanceRegistry.of({
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
listInstances: Ref.get(entries).pipe(
Effect.map(
@@ -395,9 +448,9 @@ export const makeProviderInstanceRegistry = <R>(input: {
get subscribeChanges() {
return PubSub.subscribe(changes);
},
};
});
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
const mutator = ProviderInstanceRegistryMutator.of({ reconcile });
return { registry, mutator };
});
@@ -409,15 +462,15 @@ export const makeProviderInstanceRegistry = <R>(input: {
* wiring up the settings watcher.
*
* Only exposes the public registry tag — hot-reload consumers should use
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
* `mutableLayer` (below) or the hydration layer.
*/
export const ProviderInstanceRegistryLayer = <R>(input: {
export const layer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
Layer.effect(
ProviderInstanceRegistry,
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
make(input).pipe(Effect.map((built) => built.registry)),
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
/**
@@ -426,12 +479,12 @@ export const ProviderInstanceRegistryLayer = <R>(input: {
* changes. Tests that exercise the mutator directly can pair this Layer
* with a test-local `ServerSettingsService`.
*/
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
export const mutableLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
Layer.effectContext(
makeProviderInstanceRegistry(input).pipe(
make(input).pipe(
Effect.map(({ registry, mutator }) =>
Context.make(ProviderInstanceRegistry, registry).pipe(
Context.add(ProviderInstanceRegistryMutator, mutator),
@@ -30,25 +30,21 @@ import { deepMerge } from "@t3tools/shared/Struct";
import { createModelCapabilities } from "@t3tools/shared/model";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
import {
haveProvidersChanged,
mergeProviderSnapshot,
mergeProviderSnapshots,
ProviderRegistryLive,
selectProvidersByKind,
} from "./ProviderRegistry.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettingsModule from "../../serverSettings.ts";
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
import * as ProviderRegistry from "../Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
checkCodexProviderStatus,
type CodexAppServerProviderSnapshot,
} from "./Layers/CodexProvider.ts";
import { checkClaudeProviderStatus } from "./Layers/ClaudeProvider.ts";
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
import { ProviderInstanceRegistryHydrationLive } from "./Layers/ProviderInstanceRegistryHydration.ts";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import * as ServerConfig from "../config.ts";
import * as ServerSettingsModule from "../serverSettings.ts";
import { readProviderStatusCache, resolveProviderStatusCachePath } from "./providerStatusCache.ts";
import type { ProviderInstance } from "./ProviderDriver.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
@@ -471,7 +467,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
});
describe("ProviderRegistryLive", () => {
describe("ProviderRegistry", () => {
it("treats equal provider snapshots as unchanged", () => {
const providers = [
{
@@ -502,7 +498,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
},
] as const satisfies ReadonlyArray<ServerProvider>;
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
assert.strictEqual(ProviderRegistry.haveProvidersChanged(providers, [...providers]), false);
});
it("preserves previously discovered provider models when a refresh returns none", () => {
@@ -540,9 +536,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
models: [],
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
assert.deepStrictEqual(
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
[...previousProvider.models],
);
});
it("fills missing capabilities from the previous provider snapshot", () => {
@@ -589,9 +586,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
],
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
assert.deepStrictEqual(
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
[...previousProvider.models],
);
});
it.effect("does not run provider probes during layer construction", () =>
@@ -650,10 +648,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
@@ -718,8 +716,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
models: [],
} satisfies ServerProvider;
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
const persistedProviders = selectProvidersByKind(
const mergedProviders = ProviderRegistry.mergeProviderSnapshots(previousProviders, [
refreshedCursor,
]);
const persistedProviders = ProviderRegistry.selectProvidersByKind(
mergedProviders,
new Set([ProviderDriverKind.make("cursor")]),
);
@@ -805,10 +805,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-merged-persist-",
}),
),
@@ -902,10 +902,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-refresh-failure-",
}),
),
@@ -1009,10 +1009,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-sync-failure-",
}),
),
@@ -1102,13 +1102,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
const providerRegistryLayer = ProviderRegistry.layer.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1119,7 +1119,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(OpenCodeRuntime.layer),
// NO spawner mock — `ChildProcessSpawner` is supplied by the
// outer `NodeServices.layer` on `it.layer(...)` and will
// genuinely spawn a subprocess. The missing-binary ENOENT is
@@ -1194,13 +1194,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
const providerRegistryLayer = ProviderRegistry.layer.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1211,7 +1211,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
ChildProcessSpawner.make((command) => {
spawnedCommands.push((command as { readonly command: string }).command);
@@ -1315,13 +1315,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
const providerRegistryLayer = ProviderRegistry.layer.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1332,7 +1332,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
@@ -1376,13 +1376,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
let cursorSpawned = false;
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
const providerRegistryLayer = ProviderRegistry.layer.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1393,7 +1393,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
@@ -0,0 +1,741 @@
/**
* ProviderRegistry aggregates per-instance snapshot streams into a
* single materialized list.
*
* Historically this Layer composed four per-kind Live Layers
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
* `ServerProviderShape`. Those Lives were deleted during the driver /
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
* bundled onto the `ProviderInstance` the registry produces.
*
* Each configured instance (including multi-instance setups like
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
* keyed by `instanceId`. Instances whose driver is unavailable or whose
* config failed to decode are merged from `instanceRegistry.listUnavailable`
* as shadow snapshots so the UI can render their exact unavailable reason.
*
* Cache paths on disk are now keyed by `instanceId`. Because
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
* `<kind>.json` files remain the on-disk location for that driver's default
* instance. Identity-less legacy cache contents are ignored and replaced by
* the first live refresh.
*
* @module ProviderRegistry
*/
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
type ServerProviderUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as Semaphore from "effect/Semaphore";
import * as Config from "../config.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
import {
hydrateCachedProvider,
isCachedProviderCorrelated,
orderProviderSnapshots,
readProviderStatusCache,
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "./providerStatusCache.ts";
import type { ProviderInstance } from "./ProviderDriver.ts";
import {
makeManualOnlyProviderMaintenanceCapabilities,
type ProviderMaintenanceCapabilities,
} from "./providerMaintenance.ts";
import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
export type ProviderMaintenanceActionKind = "update";
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.
*/
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh every provider, or the default instance for one driver kind.
*
* @deprecated Prefer `refreshInstance` for new call sites.
*/
readonly refresh: (
provider?: ProviderDriverKind,
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh one configured instance. Unknown ids resolve to the current
* cached list to preserve the legacy transport behavior.
*/
readonly refreshInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Resolve maintenance capabilities for a live instance, falling back to
* manual-only capabilities when that instance is unavailable.
*/
readonly getProviderMaintenanceCapabilitiesForInstance: (
instanceId: ProviderInstanceId,
provider: ProviderDriverKind,
) => Effect.Effect<ProviderMaintenanceCapabilities>;
/**
* Apply volatile maintenance state for one instance. This state is not
* persisted; update actions are projected onto `ServerProvider.updateState`.
*/
readonly setProviderMaintenanceActionState: (input: {
readonly instanceId: ProviderInstanceId;
readonly action: ProviderMaintenanceActionKind;
readonly state: ServerProviderUpdateState | null;
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/** Emits the full materialized provider list after each aggregated change. */
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
}
>()("t3/provider/ProviderRegistry") {}
const loadProviders = (
providerSources: ReadonlyArray<ProviderSnapshotSource>,
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
Effect.forEach(
providerSources,
(providerSource) =>
providerSource.getSnapshot.pipe(
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
),
{
concurrency: "unbounded",
},
);
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
makeManualOnlyProviderMaintenanceCapabilities({
provider,
packageName: null,
});
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
const mergeProviderModels = (
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
): ReadonlyArray<ServerProvider["models"][number]> => {
if (nextModels.length === 0 && previousModels.length > 0) {
return previousModels;
}
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
const mergedModels = nextModels.map((model) => {
const previousModel = previousBySlug.get(model.slug);
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
return model;
}
return {
...model,
capabilities: previousModel.capabilities,
};
});
const nextSlugs = new Set(nextModels.map((model) => model.slug));
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
};
export const mergeProviderSnapshot = (
previousProvider: ServerProvider | undefined,
nextProvider: ServerProvider,
): ServerProvider =>
!previousProvider
? nextProvider
: {
...nextProvider,
models: mergeProviderModels(previousProvider.models, nextProvider.models),
};
export const mergeProviderSnapshots = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): ReadonlyArray<ServerProvider> => {
const mergedProviders = new Map(
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
);
for (const provider of nextProviders) {
mergedProviders.set(
snapshotInstanceKey(provider),
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
);
}
return orderProviderSnapshots([...mergedProviders.values()]);
};
export const selectProvidersByKind = (
providers: ReadonlyArray<ServerProvider>,
providerKinds: ReadonlySet<ProviderDriverKind>,
): ReadonlyArray<ServerProvider> =>
providers.filter((provider) => providerKinds.has(provider.driver));
export const haveProvidersChanged = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): boolean => !Equal.equals(previousProviders, nextProviders);
const correlateSnapshotWithSource = (
source: ProviderSnapshotSource,
snapshot: ServerProvider,
): Effect.Effect<ServerProvider> => {
if (snapshot.instanceId !== source.instanceId) {
return Effect.die(
new Error(
`Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
),
);
}
if (snapshot.driver !== source.driverKind) {
return Effect.die(
new Error(
`Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
),
);
}
return Effect.succeed(snapshot);
};
/**
* Key a snapshot for aggregation and persistence. Snapshot sources
* must be correlated by instance id before reaching this map; missing
* identities are defects, not runtime routing fallbacks.
*/
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
return provider.instanceId;
};
// Project a live `ProviderInstance` into the aggregator's consumption
// shape. Each call re-captures the instance's `snapshot` closures, so
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
// its settings changed), a fresh source rides the new PubSub instead
// of a closed one.
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
getSnapshot: instance.snapshot.getSnapshot,
refresh: instance.snapshot.refresh,
streamChanges: instance.snapshot.streamChanges,
});
export const make = Effect.gen(function* () {
const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
const config = yield* Config.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
// coalesced updates across every instance.
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
// Boot-only: hydrate `providersRef` from the on-disk per-instance
// cache so the UI has something to render during the first refresh.
// Instances added post-boot skip this path; their first entry in
// `providersRef` comes from the reactive `syncLiveSources` pass
// below.
const bootInstances = yield* instanceRegistry.listInstances;
const bootSources = bootInstances.map(buildSnapshotSource);
const fallbackProviders = yield* loadProviders(bootSources);
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
for (let index = 0; index < fallbackProviders.length; index++) {
const provider = fallbackProviders[index];
const source = bootSources[index];
if (provider === undefined || source === undefined) {
continue;
}
fallbackByInstance.set(source.instanceId, provider);
}
const cachedProviders = yield* Effect.forEach(
bootSources,
(source) =>
Effect.gen(function* () {
// One cache file per configured instance. For the default
// instance of a built-in kind the path equals `<kind>.json` —
// identical to the legacy filename. We still require the cache
// payload to carry matching instance id + driver kind; old
// identity-less payloads are discarded and the awaited refresh
// below repopulates the cache.
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: source.instanceId,
}).pipe(Effect.provideService(Path.Path, path));
const fallbackProvider = fallbackByInstance.get(source.instanceId);
if (fallbackProvider === undefined) {
return undefined;
}
return yield* readProviderStatusCache(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.flatMap((cachedProvider) => {
if (cachedProvider === undefined) {
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
}
const correlation = {
cachedProvider,
fallbackProvider,
} as const;
if (!isCachedProviderCorrelated(correlation)) {
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
path: filePath,
instanceId: source.instanceId,
cachedInstanceId: cachedProvider.instanceId ?? null,
driver: source.driverKind,
cachedDriver: cachedProvider.driver ?? null,
}).pipe(Effect.as(undefined as ServerProvider | undefined));
}
return Effect.succeed(hydrateCachedProvider(correlation));
}),
);
}),
{ concurrency: "unbounded" },
).pipe(
Effect.map((providers) =>
orderProviderSnapshots(
providers.filter((provider): provider is ServerProvider => provider !== undefined),
),
),
);
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
const maintenanceActionStatesRef = yield* Ref.make<
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
>(new Map());
// Live-source registry — the dynamic counterpart to the boot-time
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
// reference is used for identity equality so "no-op" reconciles
// (settings unchanged) skip re-subscribing + re-probing.
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(new Map());
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
// interleave two passes clobbering each other's fiber bookkeeping.
const syncSemaphore = yield* Semaphore.make(1);
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
liveSubsRef,
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
const persistProvider = (provider: ServerProvider) =>
Effect.gen(function* () {
// Persist every instance — the file name is the instance id, so
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
// get their own cache. We resolve the path fresh so snapshots
// produced by newly-added instances post-boot still land on disk
// without the aggregator holding a stale `cachePathByInstance`
// entry.
const key = snapshotInstanceKey(provider);
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: key,
}).pipe(Effect.provideService(Path.Path, path));
yield* writeProviderStatusCache({ filePath, provider }).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.tapError(Effect.logError),
Effect.ignore,
);
});
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
provider: ServerProvider,
) {
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
if (!updateState) {
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
return providerWithoutUpdateState;
}
return {
...provider,
updateState,
};
});
const upsertProviders = Effect.fn("upsertProviders")(function* (
nextProviders: ReadonlyArray<ServerProvider>,
options?: {
readonly publish?: boolean;
readonly persist?: boolean;
readonly replace?: boolean;
},
) {
const nextProvidersWithUpdateState = yield* Effect.forEach(
nextProviders,
applyProviderUpdateState,
{
concurrency: "unbounded",
},
);
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const mergedProviders = new Map(
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
);
const updatedKeys = new Set<ProviderInstanceId>();
for (const provider of nextProvidersWithUpdateState) {
const key = snapshotInstanceKey(provider);
updatedKeys.add(key);
mergedProviders.set(
key,
options?.replace === true
? provider
: mergeProviderSnapshot(mergedProviders.get(key), provider),
);
}
const providers = orderProviderSnapshots([...mergedProviders.values()]);
const providersToPersist = providers.filter((provider) =>
updatedKeys.has(snapshotInstanceKey(provider)),
);
return [[previousProviders, providers, providersToPersist] as const, providers];
},
);
if (haveProvidersChanged(previousProviders, providers)) {
if (options?.persist !== false) {
yield* Effect.forEach(providersToPersist, persistProvider, {
concurrency: "unbounded",
discard: true,
});
}
if (options?.publish !== false) {
yield* PubSub.publish(changesPubSub, providers);
}
}
return providers;
});
const syncProvider = Effect.fn("syncProvider")(function* (
provider: ServerProvider,
options?: {
readonly publish?: boolean;
},
) {
return yield* upsertProviders([provider], options);
});
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
function* (input: {
readonly instanceId: ProviderInstanceId;
readonly action: "update";
readonly state: ServerProviderUpdateState | null;
}) {
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
const previousActions = previous.get(input.instanceId);
const nextActions = { ...previousActions };
if (input.state === null || input.state.status === "idle") {
delete nextActions[input.action];
} else {
nextActions[input.action] = input.state;
}
const next = new Map(previous);
if (Object.keys(nextActions).length === 0) {
next.delete(input.instanceId);
} else {
next.set(input.instanceId, nextActions);
}
return next;
});
const existingProviders = yield* Ref.get(providersRef);
const matchingProvider = existingProviders.find(
(candidate) => candidate.instanceId === input.instanceId,
);
if (!matchingProvider) {
return existingProviders;
}
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
return yield* upsertProviders([nextProvider], {
persist: false,
});
},
);
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
providerSource: ProviderSnapshotSource,
) {
return yield* providerSource.refresh.pipe(
Effect.flatMap((nextProvider) =>
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
Effect.flatMap(syncProvider),
),
),
);
});
const refreshAll = Effect.fn("refreshAll")(function* () {
const sources = yield* getLiveSources;
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.andThen(Ref.get(providersRef)));
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
if (provider === undefined) {
return yield* refreshAll();
}
// Kind-scoped refreshes target the default instance for that driver.
const defaultInstanceId = defaultInstanceIdForDriver(provider);
const sources = yield* getLiveSources;
const providerSource = sources.find((candidate) => candidate.instanceId === defaultInstanceId);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
const refreshInstance = Effect.fn("refreshInstance")(function* (instanceId: ProviderInstanceId) {
const sources = yield* getLiveSources;
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
"getProviderMaintenanceCapabilitiesForInstance",
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
(candidate) => candidate.instanceId === instanceId,
);
return (
instance?.snapshot.maintenanceCapabilities ??
makeManualProviderMaintenanceCapabilities(provider)
);
});
/**
* Diff the aggregator's live-source set against the current
* `ProviderInstanceRegistry` and:
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - prune `providersRef` of instances that no longer exist.
*
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
* down and our `Stream.runForEach` fiber exits naturally.
*/
const syncLiveSources = syncSemaphore.withPermits(1)(
Effect.gen(function* () {
const instances = yield* instanceRegistry.listInstances;
const unavailableProviders = yield* instanceRegistry.listUnavailable;
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
instances.map((instance) => [instance.instanceId, instance] as const),
);
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
for (const provider of unavailableProviders) {
knownInstanceIds.add(snapshotInstanceKey(provider));
}
const previousSubs = yield* Ref.get(liveSubsRef);
// Carry over subscriptions for instances whose identity is
// unchanged (reconcile treated them as no-op). Instances that
// disappeared, or were rebuilt with a different reference,
// fall through to the "newly-added" branch below.
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
for (const [instanceId, previousInstance] of previousSubs) {
const nextInstance = nextByInstance.get(instanceId);
if (nextInstance !== undefined && nextInstance === previousInstance) {
carriedOver.set(instanceId, previousInstance);
}
}
// Collect new/rebuilt instances in `nextByInstance` insertion
// order (which preserves settings-author order).
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
for (const [instanceId, instance] of nextByInstance) {
if (carriedOver.has(instanceId)) {
continue;
}
newlyAdded.push([instanceId, instance] as const);
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider));
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
persist: false,
replace: true,
});
const nextSubs = new Map(carriedOver);
for (const [instanceId, instance] of newlyAdded) {
nextSubs.set(instanceId, instance);
}
yield* Ref.set(liveSubsRef, nextSubs);
// Drop aggregator state for instances that have disappeared —
// otherwise the UI would keep rendering ghosts.
const [previousProviders, providers] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const providers = orderProviderSnapshots(
previousProviders.filter((provider) =>
knownInstanceIds.has(snapshotInstanceKey(provider)),
),
);
return [[previousProviders, providers] as const, providers];
},
);
if (haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
const next = new Map(previous);
for (const instanceId of previous.keys()) {
if (!knownInstanceIds.has(instanceId)) {
next.delete(instanceId);
}
}
return next;
});
}),
);
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
}
return Effect.logError("provider registry instance sync failed; keeping subscription alive", {
cause: Cause.pretty(cause),
});
}),
);
// Seed `providersRef` with the boot-time fallback snapshots so
// consumers calling `getProviders` immediately after layer build see
// a populated list — even before the first `syncLiveSources` refresh
// resolves. Cached snapshots (already in `providersRef`) merge with
// these via `upsertProviders` so on-disk state wins where present
// 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
// buffered in the subscription regardless of when the consumer
// fibre below actually starts running.
//
// (Contrast with the pre-fix code that did
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
// schedules the consumer fibre — so a reconcile that published
// between "fibre scheduled" and "fibre starts running + subscribes"
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
// subscription rather than subscribing on stream start, which is
// what closes the race.
yield* Stream.runForEach(
Stream.fromSubscription(instanceChanges),
() => syncLiveSourcesAndContinue,
).pipe(Effect.forkScoped);
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
cause: Cause.Cause<unknown>,
) {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.interrupt;
}
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
cause: Cause.pretty(cause),
});
return yield* Ref.get(providersRef);
});
return ProviderRegistry.of({
getProviders: Ref.get(providersRef),
refresh: (provider?: ProviderDriverKind) =>
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
refreshInstance: (instanceId: ProviderInstanceId) =>
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
getProviderMaintenanceCapabilitiesForInstance,
setProviderMaintenanceActionState,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
});
});
export const layer = Layer.effect(ProviderRegistry, make);
@@ -41,23 +41,24 @@ import {
ProviderUnsupportedError,
ProviderValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
import * as ProviderService from "../Services/ProviderService.ts";
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
import { makeProviderServiceLive } from "./ProviderService.ts";
} from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProviderService from "./ProviderService.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
} 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";
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
@@ -284,7 +285,7 @@ function makeProviderServiceLayer() {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer));
const layer = it.layer(
Layer.mergeAll(
@@ -337,7 +338,9 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = Layer.mergeAll(
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
@@ -397,7 +400,9 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
@@ -479,7 +484,7 @@ it.effect(
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeProviderServiceLive().pipe(
@@ -551,7 +556,9 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
@@ -596,7 +603,9 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeProviderServiceLive({
canonicalEventLogger: {
filePath: "memory://provider-canonical-events",
@@ -656,7 +665,9 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(persistenceLayer),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
@@ -728,7 +739,7 @@ it.effect(
[ProviderDriverKind.make("codex")]: firstCodex.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
@@ -787,7 +798,7 @@ it.effect(
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: secondCodex.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
@@ -1298,7 +1309,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
const firstRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
@@ -1336,7 +1347,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
@@ -1404,7 +1415,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
const firstRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
@@ -1437,7 +1448,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
File diff suppressed because it is too large. Load diff
@@ -15,16 +15,17 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
} from "../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(persistenceLayer),
);
return Layer.mergeAll(
runtimeRepositoryLayer,
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer)),
NodeServices.layer,
);
}
@@ -32,7 +33,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
it("upserts and reads thread bindings", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const initialThreadId = ThreadId.make("thread-1");
@@ -79,7 +80,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
it("persists runtime fields and merges payload updates", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const threadId = ThreadId.make("thread-runtime");
@@ -124,7 +125,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
it("lists persisted bindings with metadata in oldest-first order", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const olderThreadId = ThreadId.make("thread-runtime-older");
@@ -198,7 +199,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const threadId = ThreadId.make("thread-provider-change");
@@ -236,7 +237,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const threadId = ThreadId.make("thread-restart");
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
yield* directory.upsert({
provider: ProviderDriverKind.make("codex"),
threadId,
@@ -244,7 +245,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}).pipe(Effect.provide(directoryLayer));
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const sql = yield* SqlClient.SqlClient;
const provider = yield* directory.getProvider(threadId);
assert.equal(provider, "codex");
@@ -0,0 +1,244 @@
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ProviderInstanceId,
type ProviderSessionRuntimeStatus,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
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";
export interface ProviderRuntimeBinding {
readonly threadId: ThreadId;
readonly provider: ProviderDriverKind;
/**
* Routing key for the configured provider instance that owns this
* session. The persistence layer promotes legacy null rows before
* exposing bindings; runtime callers must not infer this from `provider`.
*/
readonly providerInstanceId?: ProviderInstanceId;
readonly adapterKey?: string;
readonly status?: ProviderSessionRuntimeStatus;
readonly resumeCursor?: unknown | null;
readonly runtimePayload?: unknown | null;
readonly runtimeMode?: RuntimeMode;
}
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
readonly lastSeenAt: string;
}
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryWriteError =
| ProviderValidationError
| ProviderSessionDirectoryPersistenceError;
export class ProviderSessionDirectory extends Context.Service<
ProviderSessionDirectory,
{
readonly upsert: (
binding: ProviderRuntimeBinding,
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
readonly getProvider: (
threadId: ThreadId,
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
readonly getBinding: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
readonly listThreadIds: () => Effect.Effect<
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
>()("t3/provider/ProviderSessionDirectory") {}
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
function toPersistenceError(operation: string) {
return (cause: unknown) =>
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Failed to execute ${operation}.`,
cause,
});
}
function decodeProviderDriverKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
return decodeProviderDriverKindValue(providerName).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation,
detail: `Unknown persisted provider '${providerName}'.`,
cause,
}),
),
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function mergeRuntimePayload(
existing: unknown | null,
next: unknown | null | undefined,
): unknown | null {
if (next === undefined) {
return existing ?? null;
}
if (isRecord(existing) && isRecord(next)) {
return { ...existing, ...next };
}
return next;
}
function toRuntimeBinding(
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
resumeCursor: runtime.resumeCursor,
runtimePayload: runtime.runtimePayload,
lastSeenAt: runtime.lastSeenAt,
}) satisfies ProviderRuntimeBindingWithMetadata,
),
);
}
export const make = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const getBinding: ProviderSessionDirectory["Service"]["getBinding"] = (threadId) =>
repository.getByThreadId({ threadId }).pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
Effect.flatMap((runtime) =>
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
Effect.map(Option.some),
),
}),
),
);
const upsert: ProviderSessionDirectory["Service"]["upsert"] = Effect.fn(
"ProviderSessionDirectory.upsert",
)(function* (binding) {
const existing = yield* repository
.getByThreadId({ threadId: binding.threadId })
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
const existingRuntime = Option.getOrUndefined(existing);
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
if (!resolvedThreadId) {
return yield* new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "threadId must be a non-empty string.",
});
}
const now = DateTime.formatIso(yield* DateTime.now);
const providerChanged =
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
const providerInstanceId =
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
if (providerInstanceId === null || providerInstanceId === undefined) {
return yield* new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "providerInstanceId is required for provider session runtime bindings.",
});
}
yield* repository
.upsert({
threadId: resolvedThreadId,
providerName: binding.provider,
providerInstanceId,
adapterKey:
binding.adapterKey ??
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
status: binding.status ?? existingRuntime?.status ?? "running",
lastSeenAt: now,
resumeCursor:
binding.resumeCursor !== undefined
? binding.resumeCursor
: (existingRuntime?.resumeCursor ?? null),
runtimePayload: mergeRuntimePayload(
existingRuntime?.runtimePayload ?? null,
binding.runtimePayload,
),
})
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
});
const getProvider: ProviderSessionDirectory["Service"]["getProvider"] = (threadId) =>
getBinding(threadId).pipe(
Effect.flatMap(
Option.match({
onSome: (value) => Effect.succeed(value.provider),
onNone: () =>
Effect.fail(
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.getProvider",
detail: `No persisted provider binding found for thread '${threadId}'.`,
}),
),
}),
),
);
const listThreadIds: ProviderSessionDirectory["Service"]["listThreadIds"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectory["Service"]["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
{ concurrency: "unbounded" },
),
),
);
return ProviderSessionDirectory.of({
upsert,
getProvider,
getBinding,
listThreadIds,
listBindings,
});
});
export const layer = Layer.effect(ProviderSessionDirectory, make);
@@ -17,14 +17,13 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "./Errors.ts";
import * as ProviderSessionReaper from "./ProviderSessionReaper.ts";
import * as ProviderService from "./ProviderService.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
const defaultModelSelection = {
instanceId: ProviderInstanceId.make("codex"),
@@ -117,7 +116,8 @@ function makeReadModel(
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
| ProviderSessionReaper.ProviderSessionReaper
| ProviderSessionRuntime.ProviderSessionRuntimeRepository,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -137,19 +137,19 @@ describe("ProviderSessionReaper", () => {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) => ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
const stopSession = vi.fn<ProviderService.ProviderService["Service"]["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderServiceShape["stopSession"]>,
})) as ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>,
);
const providerService: ProviderServiceShape = {
const providerService: ProviderService.ProviderService["Service"] = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
@@ -178,18 +178,21 @@ describe("ProviderSessionReaper", () => {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
const layer = Layer.effect(
ProviderSessionReaper.ProviderSessionReaper,
ProviderSessionReaper.make({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}),
).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, providerService)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
@@ -257,7 +260,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -307,7 +312,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -356,7 +363,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -405,7 +414,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -491,7 +502,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -574,7 +587,9 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -1,31 +1,36 @@
import * as Context from "effect/Context";
import * as Clock from "effect/Clock";
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 Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ProviderService from "./ProviderService.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
export class ProviderSessionReaper extends Context.Service<
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { ProviderService } from "../Services/ProviderService.ts";
{
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
>()("t3/provider/ProviderSessionReaper") {}
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperLiveOptions {
export interface ProviderSessionReaperOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
export const make = (options?: ProviderSessionReaperOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService.ProviderService;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const inactivityThresholdMs = Math.max(
1,
@@ -103,19 +108,15 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
}
});
const start: ProviderSessionReaperShape["start"] = () =>
const start: ProviderSessionReaper["Service"]["start"] = () =>
Effect.gen(function* () {
yield* Effect.forkScoped(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
error,
}),
Effect.logWarning("provider.session.reaper.sweep-failed", { error }),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-defect", {
defect,
}),
Effect.logWarning("provider.session.reaper.sweep-defect", { defect }),
),
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
),
@@ -127,12 +128,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
});
});
return {
start,
} satisfies ProviderSessionReaperShape;
return ProviderSessionReaper.of({ start });
});
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
export const layer = Layer.effect(ProviderSessionReaper, make());
@@ -1,100 +1,3 @@
/**
* ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.
*
* Maps a `ProviderInstanceId` (the new per-instance routing key) or a
* `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete
* adapter service (Codex, Claude, etc). It does not own session lifecycle
* or routing rules; `ProviderService` uses this registry together with
* `ProviderSessionDirectory`.
*
* During the driver/instance migration this tag exposes both flavours:
*
* - `getByInstance` / `listInstances` — new per-instance routing. Callers
* that already know an `instanceId` (threads, sessions, events)
* should prefer these.
* (`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.
*
* @module ProviderAdapterRegistry
*/
import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as PubSub from "effect/PubSub";
import type * as Scope from "effect/Scope";
import type * as Stream from "effect/Stream";
import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
import type { ProviderContinuationIdentity } from "../ProviderDriver.ts";
export interface ProviderInstanceRoutingInfo {
readonly instanceId: ProviderInstanceId;
readonly driverKind: ProviderDriverKind;
readonly displayName: string | undefined;
readonly accentColor?: string | undefined;
readonly enabled: boolean;
readonly continuationIdentity: ProviderContinuationIdentity;
}
/**
* ProviderAdapterRegistryShape - Service API for adapter lookup.
*/
export interface ProviderAdapterRegistryShape {
/**
* Resolve the adapter for a specific instance id. Returns
* `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,
) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;
readonly getInstanceInfo: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
/**
* List all live instance ids. Excludes unavailable/shadow instances —
* callers of this method want something they can pass to `getByInstance`.
*/
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
/**
* Legacy: list provider kinds whose default instance is currently
* registered.
*
* @deprecated Prefer `listInstances`. Retained for migration-era call
* sites that iterate providers to build UI/metrics.
*/
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
/**
* Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.
* Emits one `void` tick whenever the set of live instances changes
* (instance added, removed, or rebuilt after a settings edit). Consumers
* that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s
* runtime event bus — re-pull `listInstances` on each tick and fork new
* subscriptions for instances they haven't seen yet.
*/
readonly streamChanges: Stream.Stream<void>;
/**
* 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<PubSub.Subscription<void>, never, Scope.Scope>;
}
/**
* ProviderAdapterRegistry - Service tag for provider adapter lookup.
*/
export class ProviderAdapterRegistry extends Context.Service<
ProviderAdapterRegistry,
ProviderAdapterRegistryShape
>()("t3/provider/Services/ProviderAdapterRegistry") {}
// Compatibility shim for the intentionally excluded orchestration harness.
export { ProviderAdapterRegistry } from "../ProviderAdapterRegistry.ts";
export type { ProviderInstanceRoutingInfo } from "../ProviderAdapterRegistry.ts";
@@ -1,87 +0,0 @@
/**
* ProviderInstanceRegistry — the single Effect service in the new model.
*
* Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running
* registered driver factories against `ServerSettings.providerInstances`.
* The registry watches settings; when an instance's config changes (or
* the entry disappears), the registry tears down the affected instance's
* scope and rebuilds — that's the entire hot-reload story.
*
* What rest-of-server reads from here:
* - `getInstance(instanceId)` — for routing turn/session calls.
* - `listInstances` — for snapshot aggregation in `ProviderRegistry`.
* - `listUnavailable` — `ServerProvider` shadows for instances whose
* driver is not registered in this build (rollback / fork tolerance).
* - `streamChanges` — coalesced "registry mutated" pings so consumers
* can re-pull lists or re-broadcast.
*
* @module provider/Services/ProviderInstanceRegistry
*/
import type { ProviderInstanceId, ServerProvider } from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as PubSub from "effect/PubSub";
import type * as Scope from "effect/Scope";
import type * as Stream from "effect/Stream";
import type { ProviderInstance } from "../ProviderDriver.ts";
export interface ProviderInstanceRegistryShape {
/**
* Look up one instance by id. Returns `undefined` (not Option) when the
* id is unknown — callers branch on falsy and emit
* `ProviderInstanceNotFoundError`.
*/
readonly getInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstance | undefined>;
/**
* Every available (driver-registered, successfully created) instance,
* in stable settings-author order.
*/
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
/**
* 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<ReadonlyArray<ServerProvider>>;
/**
* Push notification stream emitted whenever the registry's contents
* change — instance added, removed, or rebuilt. The payload is `void`
* because consumers always want to re-pull `listInstances` /
* `listUnavailable` together.
*
* NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the
* stream starts running, forking a consumer via
* `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next
* publish — the forked fiber may not have subscribed yet when the
* publish lands. Hot-reload consumers that must not miss a publish
* should use `subscribeChanges` below instead, which acquires the
* subscription synchronously in the caller's fiber before the consumer
* loop is forked.
*/
readonly streamChanges: Stream.Stream<void>;
/**
* Acquire a subscription to the registry's change channel synchronously
* in the caller's fiber. Returns a `PubSub.Subscription<void>` whose
* lifetime is scoped to the provided `Scope` (the subscription is
* released when the scope closes). Consumers typically `yield*` this
* in the same fiber that forks their consumer loop, then drain with
* `PubSub.take(subscription)` inside `Effect.forever`. Because the
* subscription is registered with the PubSub before this `yield*`
* returns, no subsequent publish can land in a gap.
*
* This exists because the `ProviderInstanceRegistry` publishes on a
* PubSub and `Stream.fromPubSub` defers subscription until the stream
* starts executing — a consumer that `forkScoped`s the stream
* consumption can miss a publish that lands in the narrow window
* between "fiber scheduled" and "fiber starts running".
*/
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
}
export class ProviderInstanceRegistry extends Context.Service<
ProviderInstanceRegistry,
ProviderInstanceRegistryShape
>()("t3/provider/Services/ProviderInstanceRegistry") {}
@@ -1,52 +0,0 @@
/**
* ProviderInstanceRegistryMutator — internal handle used by the hydration
* layer to reconcile the live registry with a fresh
* `ProviderInstanceConfigMap`.
*
* Kept separate from the public `ProviderInstanceRegistry` service tag so
* downstream consumers (drivers, reactors, `ProviderService`) can only read
* from the registry. Only the hydration layer — which watches
* `ServerSettingsService.streamChanges` and applies diffs — imports this
* tag.
*
* The mutator exposes a single entry point, `reconcile(configMap)`, which:
*
* 1. Diffs the incoming map against the live one keyed by instance id.
* 2. Closes the per-instance `Scope` of every removed or replaced entry
* (tearing down adapter processes, refresh fibres, temp files) BEFORE
* creating the replacement — `reconcile` guarantees "at most one live
* instance per id" at all times.
* 3. Opens a fresh child `Scope` for every added or replaced entry, runs
* the driver's `create`, and stores the resulting `ProviderInstance`
* plus its scope.
* 4. Publishes one `void` tick on the registry's `streamChanges` PubSub at
* the end of the batch — consumers re-pull `listInstances` /
* `listUnavailable`.
*
* `reconcile` is idempotent: calling it with an unchanged config map is a
* no-op (no scope churn, no pubsub emission).
*
* @module provider/Services/ProviderInstanceRegistryMutator
*/
import type { ProviderInstanceConfigMap } from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export interface ProviderInstanceRegistryMutatorShape {
/**
* Bring the live registry in line with the supplied config map. See
* module docs for the add / remove / replace semantics.
*
* The effect never fails: individual driver `create` failures are
* captured as "unavailable" shadow snapshots inside the registry, the
* same way boot-time failures are handled by
* `makeProviderInstanceRegistry`. This keeps settings-watcher loops from
* erroring out on a single bad entry.
*/
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
}
export class ProviderInstanceRegistryMutator extends Context.Service<
ProviderInstanceRegistryMutator,
ProviderInstanceRegistryMutatorShape
>()("t3/provider/Services/ProviderInstanceRegistryMutator") {}
@@ -1,81 +1,2 @@
/**
* ProviderRegistry - Provider snapshot service.
*
* Owns provider install/auth/version/model snapshots and exposes the latest
* provider state to transport layers.
*
* @module ProviderRegistry
*/
import type {
ProviderInstanceId,
ProviderDriverKind,
ServerProvider,
ServerProviderUpdateState,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Stream from "effect/Stream";
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
export type ProviderMaintenanceActionKind = "update";
export interface ProviderRegistryShape {
/**
* Read the latest provider snapshots for every configured instance.
* Multiple snapshots may share the same `provider` kind (multiple
* instances of the same driver) and disambiguate via `instanceId`.
*/
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh all providers, or the default instance of the specified
* kind when supplied.
*
* Retained for back-compat with legacy call sites (WS refresh RPC,
* orchestration metrics). New code should prefer `refreshInstance`.
*
* @deprecated prefer `refreshInstance` for new call sites.
*/
readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh the specific configured instance. Returns the updated snapshot
* list. When the instance id is unknown the call resolves with the
* currently cached list (no error) — matching the legacy `refresh` shim
* behaviour so transport layers don't have to special-case unknowns.
*/
readonly refreshInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Resolve the maintenance capabilities owned by one live provider instance.
* Falls back to manual-only capabilities when the instance is not live.
*/
readonly getProviderMaintenanceCapabilitiesForInstance: (
instanceId: ProviderInstanceId,
provider: ProviderDriverKind,
) => Effect.Effect<ProviderMaintenanceCapabilities>;
/**
* Apply volatile maintenance-action state to one configured instance.
* This state is never persisted to disk. Today only update actions are
* projected onto `ServerProvider.updateState`; install/auth actions can
* extend this action map without adding driver-scoped APIs.
*/
readonly setProviderMaintenanceActionState: (input: {
readonly instanceId: ProviderInstanceId;
readonly action: ProviderMaintenanceActionKind;
readonly state: ServerProviderUpdateState | null;
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Stream of provider snapshot updates — one emission per aggregated
* change. The array contains the full current state.
*/
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
}
export class ProviderRegistry extends Context.Service<ProviderRegistry, ProviderRegistryShape>()(
"t3/provider/Services/ProviderRegistry",
) {}
// Compatibility shim for the intentionally excluded orchestration modules.
export * from "../ProviderRegistry.ts";
@@ -1,121 +1,5 @@
/**
* ProviderService - Service interface for provider sessions, turns, and checkpoints.
*
* Acts as the cross-provider facade used by transports (WebSocket/RPC). It
* resolves provider adapters through `ProviderAdapterRegistry`, routes
* session-scoped calls via `ProviderSessionDirectory`, and exposes one unified
* provider event stream to callers.
*
* Uses Effect `Context.Service` for dependency injection and returns typed
* domain errors for validation, session, codex, and checkpoint workflows.
*
* @module ProviderService
*/
import type {
ProviderInterruptTurnInput,
ProviderInstanceId,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
ProviderRuntimeEvent,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionStartInput,
ProviderStopSessionInput,
ThreadId,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Stream from "effect/Stream";
// Compatibility shim for the intentionally excluded orchestration modules and harness.
export * from "../ProviderService.ts";
import type { ProviderServiceError } from "../Errors.ts";
import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";
import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts";
/**
* ProviderServiceShape - Service API for provider session and turn orchestration.
*/
export interface ProviderServiceShape {
/**
* Start a provider session.
*/
readonly startSession: (
threadId: ThreadId,
input: ProviderSessionStartInput,
) => Effect.Effect<ProviderSession, ProviderServiceError>;
/**
* Send a provider turn.
*/
readonly sendTurn: (
input: ProviderSendTurnInput,
) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;
/**
* Interrupt a running provider turn.
*/
readonly interruptTurn: (
input: ProviderInterruptTurnInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Respond to a provider approval request.
*/
readonly respondToRequest: (
input: ProviderRespondToRequestInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Respond to a provider structured user-input request.
*/
readonly respondToUserInput: (
input: ProviderRespondToUserInputInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop a provider session.
*/
readonly stopSession: (
input: ProviderStopSessionInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* List active provider sessions.
*
* Aggregates runtime session lists from all registered adapters.
*/
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
/**
* Read capabilities for the adapter bound to a configured provider instance.
*/
readonly getCapabilities: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;
readonly getInstanceInfo: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;
/**
* Roll back provider conversation state by a number of turns.
*/
readonly rollbackConversation: (input: {
readonly threadId: ThreadId;
readonly numTurns: number;
}) => Effect.Effect<void, ProviderServiceError>;
/**
* Canonical provider runtime event stream.
*
* Fan-out is owned by ProviderService (not by a standalone event-bus service).
*/
readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;
}
/**
* ProviderService - Service tag for provider orchestration.
*/
export class ProviderService extends Context.Service<ProviderService, ProviderServiceShape>()(
"t3/provider/Services/ProviderService",
) {}
/** @deprecated Use `ProviderService["Service"]` from the canonical module. */
export type ProviderServiceShape = import("../ProviderService.ts").ProviderService["Service"];
@@ -1,70 +0,0 @@
import type {
ProviderInstanceId,
ProviderDriverKind,
ProviderSessionRuntimeStatus,
RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type {
ProviderSessionDirectoryPersistenceError,
ProviderValidationError,
} from "../Errors.ts";
export interface ProviderRuntimeBinding {
readonly threadId: ThreadId;
readonly provider: ProviderDriverKind;
/**
* Routing key for the configured provider instance that owns this
* session. The persistence layer promotes legacy null rows before
* exposing bindings; runtime callers must not infer this from `provider`.
*/
readonly providerInstanceId?: ProviderInstanceId;
readonly adapterKey?: string;
readonly status?: ProviderSessionRuntimeStatus;
readonly resumeCursor?: unknown | null;
readonly runtimePayload?: unknown | null;
readonly runtimeMode?: RuntimeMode;
}
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
readonly lastSeenAt: string;
}
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryWriteError =
| ProviderValidationError
| ProviderSessionDirectoryPersistenceError;
export interface ProviderSessionDirectoryShape {
readonly upsert: (
binding: ProviderRuntimeBinding,
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
readonly getProvider: (
threadId: ThreadId,
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
readonly getBinding: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
readonly listThreadIds: () => Effect.Effect<
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
export class ProviderSessionDirectory extends Context.Service<
ProviderSessionDirectory,
ProviderSessionDirectoryShape
>()("t3/provider/Services/ProviderSessionDirectory") {}
@@ -1,15 +0,0 @@
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Scope from "effect/Scope";
export interface ProviderSessionReaperShape {
/**
* Start the background provider session reaper within the provided scope.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
export class ProviderSessionReaper extends Context.Service<
ProviderSessionReaper,
ProviderSessionReaperShape
>()("t3/provider/Services/ProviderSessionReaper") {}
+72 -68
View File
@@ -13,14 +13,12 @@ import {
} from "@opencode-ai/sdk/v2";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
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 Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as P from "effect/Predicate";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
@@ -28,7 +26,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import * as ProcessRunner from "../processRunner.ts";
import { collectStreamAsString } from "./providerSnapshot.ts";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
@@ -50,14 +48,19 @@ export interface OpenCodeServerConnection {
readonly external: boolean;
}
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
readonly operation: string;
readonly cause?: unknown;
readonly detail: string;
}> {
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
export class OpenCodeRuntimeError extends Schema.TaggedErrorClass<OpenCodeRuntimeError>()(
"OpenCodeRuntimeError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
static readonly is = Schema.is(OpenCodeRuntimeError);
override get message(): string {
return `${this.operation}: ${this.detail}`;
}
}
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
@@ -107,47 +110,50 @@ export interface ParsedOpenCodeModelSlug {
readonly modelID: string;
}
export interface OpenCodeRuntimeShape {
/**
* Spawns a local OpenCode server process. Its lifetime is bound to the caller's
* `Scope.Scope` — the child is killed automatically when that scope closes.
* Consumers that want a long-lived server must create and hold a scope explicitly
* (see {@link Scope.make}) and close it when done.
*/
readonly startOpenCodeServerProcess: (input: {
readonly binaryPath: string;
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
/**
* Returns a handle to either an externally-managed OpenCode server (when
* `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
* freshly spawned local server whose lifetime is bound to the caller's scope.
*/
readonly connectToOpenCodeServer: (input: {
readonly binaryPath: string;
readonly serverUrl?: string | null;
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
readonly runOpenCodeCommand: (input: {
readonly binaryPath: string;
readonly args: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
readonly createOpenCodeSdkClient: (input: {
readonly baseUrl: string;
readonly directory: string;
readonly serverPassword?: string;
}) => OpencodeClient;
readonly loadOpenCodeInventory: (
client: OpencodeClient,
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
}
export class OpenCodeRuntime extends Context.Service<
OpenCodeRuntime,
{
/**
* Spawns a local OpenCode server process. Its lifetime is bound to the caller's
* `Scope.Scope` — the child is killed automatically when that scope closes.
* Consumers that want a long-lived server must create and hold a scope explicitly
* (see {@link Scope.make}) and close it when done.
*/
readonly startOpenCodeServerProcess: (input: {
readonly binaryPath: string;
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
/**
* Returns a handle to either an externally-managed OpenCode server (when
* `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
* freshly spawned local server whose lifetime is bound to the caller's scope.
*/
readonly connectToOpenCodeServer: (input: {
readonly binaryPath: string;
readonly serverUrl?: string | null;
readonly environment?: NodeJS.ProcessEnv;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
readonly runOpenCodeCommand: (input: {
readonly binaryPath: string;
readonly args: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
readonly createOpenCodeSdkClient: (input: {
readonly baseUrl: string;
readonly directory: string;
readonly serverPassword?: string;
}) => OpencodeClient;
readonly loadOpenCodeInventory: (
client: OpencodeClient,
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
}
>()("t3/provider/opencodeRuntime") {}
function parseServerUrlFromOutput(output: string): string | null {
for (const line of output.split("\n")) {
@@ -275,14 +281,14 @@ function ensureRuntimeError(
: new OpenCodeRuntimeError({ operation, detail, cause });
}
const makeOpenCodeRuntime = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const netService = yield* NetService.NetService;
const hostPlatform = yield* HostProcessPlatform;
const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
resolveSpawnCommand(command, args, env ? { env } : {});
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>
Effect.gen(function* () {
const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
const child = yield* spawner.spawn(
@@ -296,7 +302,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
{ concurrency: "unbounded" },
);
const exitCode = Number(code);
if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
if (yield* ProcessRunner.isWindowsCommandNotFound(exitCode, stderr)) {
return yield* new OpenCodeRuntimeError({
operation: "runOpenCodeCommand",
detail: `spawn ${input.binaryPath} ENOENT`,
@@ -318,7 +324,9 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
),
);
const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (
input,
) =>
Effect.gen(function* () {
// Bind this server's lifetime to the caller's scope. When the caller's
// scope closes, the spawned child is killed and all associated fibers
@@ -476,7 +484,9 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
} satisfies OpenCodeServerProcess;
});
const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
input,
) => {
const serverUrl = input.serverUrl?.trim();
if (serverUrl) {
// We don't own externally-configured servers — no scope interaction.
@@ -502,7 +512,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
);
};
const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>
createOpencodeClient({
baseUrl: input.baseUrl,
directory: input.directory,
@@ -537,24 +547,18 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
Effect.map((result) => result.data ?? []),
);
const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) =>
Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
Effect.map(([providerList, agents]) => ({ providerList, agents })),
);
return {
return OpenCodeRuntime.of({
startOpenCodeServerProcess,
connectToOpenCodeServer,
runOpenCodeCommand,
createOpenCodeSdkClient,
loadOpenCodeInventory,
} satisfies OpenCodeRuntimeShape;
});
});
export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
"t3/provider/opencodeRuntime",
) {}
export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
Layer.provide(NetService.layer),
);
export const layer = Layer.effect(OpenCodeRuntime, make).pipe(Layer.provide(NetService.layer));
@@ -18,7 +18,7 @@ import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
import {
makeProviderMaintenanceCapabilities,
@@ -177,7 +177,7 @@ function makeRegistry(
);
});
const registry: ProviderRegistryShape = {
const registry: ProviderRegistry.ProviderRegistry["Service"] = {
getProviders: Ref.get(providersRef),
refresh: () => Ref.get(providersRef),
refreshInstance: () => Ref.get(providersRef),
@@ -194,13 +194,13 @@ function makeRegistry(
});
}
const makeTestRunner = (registry: ProviderRegistryShape) =>
const makeTestRunner = (registry: ProviderRegistry.ProviderRegistry["Service"]) =>
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
Effect.provide(
ProviderMaintenanceRunner.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(ProviderRegistry, registry),
Layer.succeed(ProviderRegistry.ProviderRegistry, registry),
Layer.succeed(ProviderVersionCache, new Map()),
),
),
@@ -9,7 +9,6 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -20,7 +19,7 @@ import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
@@ -39,26 +38,36 @@ export interface ProviderMaintenanceCommandResult {
readonly stderrTruncated: boolean;
}
export interface ProviderMaintenanceRunnerShape {
readonly updateProvider: (
target:
| ProviderDriverKind
| {
readonly provider: ProviderDriverKind;
readonly instanceId?: ProviderInstanceId | undefined;
},
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
}
export class ProviderMaintenanceRunner extends Context.Service<
ProviderMaintenanceRunner,
ProviderMaintenanceRunnerShape
{
readonly updateProvider: (
target:
| ProviderDriverKind
| {
readonly provider: ProviderDriverKind;
readonly instanceId?: ProviderInstanceId | undefined;
},
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
}
>()("t3/provider/providerMaintenanceRunner") {}
class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
class ProviderMaintenanceCommandError extends Schema.TaggedErrorClass<ProviderMaintenanceCommandError>()(
"ProviderMaintenanceCommandError",
{
operation: Schema.Literals(["spawn", "collect"]),
command: Schema.optional(Schema.String),
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.";
}
}
interface VerifiedProviderRefresh {
readonly providers: ReadonlyArray<ServerProvider>;
@@ -81,7 +90,8 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
Effect.mapError(
(cause) =>
new ProviderMaintenanceCommandError({
message: `Failed to run update command ${input.command}: ${cause.message}`,
operation: "spawn",
command: input.command,
cause,
}),
),
@@ -105,7 +115,7 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
Effect.mapError(
(cause) =>
new ProviderMaintenanceCommandError({
message: cause instanceof Error ? cause.message : "Update command failed to run.",
operation: "collect",
cause,
}),
),
@@ -191,7 +201,7 @@ function makeUpdateState(input: {
}
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
const providerRegistry = yield* ProviderRegistry;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
@@ -277,7 +287,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
}),
);
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
const updateProvider: ProviderMaintenanceRunner["Service"]["updateProvider"] = Effect.fn(
"ProviderMaintenanceRunner.updateProvider",
)(function* (target) {
const provider = typeof target === "string" ? target : target.provider;
@@ -1,5 +1,5 @@
/**
* Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a
* Test helpers for constructing a `ProviderAdapterRegistry["Service"]` mock from a
* kind-keyed adapter map.
*
* Tests historically assembled a `registry` object with only `getByProvider`
@@ -26,19 +26,21 @@ import * as Stream from "effect/Stream";
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts";
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
export type KindAdapterMap = Partial<
Record<ProviderDriverKind, ProviderAdapterShape<ProviderAdapterError>>
>;
/**
* Build a `ProviderAdapterRegistryShape` from a kind-keyed adapter map.
* Build a `ProviderAdapterRegistry["Service"]` from a kind-keyed adapter map.
* Every adapter present in the map is addressable via both the legacy
* `getByProvider(kind)` path and the new `getByInstance(id)` path (where
* `id = defaultInstanceIdForDriver(kind)`).
*/
export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => {
export const makeAdapterRegistryMock = (
adapters: KindAdapterMap,
): ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] => {
const byInstanceId = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
for (const [kind, adapter] of Object.entries(adapters)) {
if (!adapter) continue;
@@ -46,16 +48,17 @@ export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapt
byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter);
}
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => {
const adapter = byInstanceId.get(instanceId);
return adapter
? Effect.succeed(adapter)
: Effect.fail(
new ProviderUnsupportedError({
provider: ProviderDriverKind.make(instanceId),
}),
);
};
const getByInstance: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"]["getByInstance"] =
(instanceId) => {
const adapter = byInstanceId.get(instanceId);
return adapter
? Effect.succeed(adapter)
: Effect.fail(
new ProviderUnsupportedError({
provider: ProviderDriverKind.make(instanceId),
}),
);
};
return {
getByInstance,
@@ -1,4 +1,4 @@
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import * as ProviderRegistry from "../ProviderRegistry.ts";
import type { ServerProvider } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -7,7 +7,7 @@ import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMainte
export const makeProviderRegistryMock = (
providers: ReadonlyArray<ServerProvider> = [],
): ProviderRegistryShape => ({
): ProviderRegistry.ProviderRegistry["Service"] => ({
getProviders: Effect.succeed(providers),
refresh: () => Effect.succeed(providers),
refreshInstance: () => Effect.succeed(providers),
@@ -18,4 +18,4 @@ export const makeProviderRegistryMock = (
});
export const makeProviderRegistryLayer = (providers: ReadonlyArray<ServerProvider> = []) =>
Layer.succeed(ProviderRegistry, makeProviderRegistryMock(providers));
Layer.succeed(ProviderRegistry.ProviderRegistry, makeProviderRegistryMock(providers));
+1 -1
View File
@@ -81,7 +81,7 @@ import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import { PersistenceSqlError } from "./persistence/Errors.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
+16 -16
View File
@@ -18,12 +18,12 @@ import * as ExternalLauncher from "./process/externalLauncher.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
import * as ProviderSessionDirectory from "./provider/ProviderSessionDirectory.ts";
import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
import * as ProviderAdapterRegistry from "./provider/ProviderAdapterRegistry.ts";
import * as ProviderEventLoggers from "./provider/ProviderEventLoggers.ts";
import * as ProviderService from "./provider/ProviderService.ts";
import * as ProviderSessionReaper from "./provider/ProviderSessionReaper.ts";
import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
@@ -50,7 +50,7 @@ import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
@@ -165,18 +165,18 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectory.layer.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
// `ProviderAdapterRegistry.layer` is a facade that resolves kind → adapter
// by looking up the default `ProviderInstance` per driver in the instance
// registry. Adapter construction itself moved inside each driver's
// `create()`; `ProviderEventLoggersLive` owns the shared native/canonical
// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical
// NDJSON writers and is provided at the outer runtime layer so both
// `ProviderService` and the per-instance drivers read the same logger pair.
const ProviderLayerLive = ProviderServiceLive.pipe(
Layer.provide(ProviderAdapterRegistryLive),
const ProviderLayerLive = ProviderService.layer.pipe(
Layer.provide(ProviderAdapterRegistry.layer),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
@@ -278,7 +278,7 @@ const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
),
);
const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
const ProviderRuntimeLayerLive = ProviderSessionReaper.layer.pipe(
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
);
@@ -293,7 +293,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(Keybindings.layer),
Layer.provideMerge(ProviderRegistryLive),
Layer.provideMerge(ProviderRegistry.layer),
// The instance registry is the new routing keystone — text generation,
// adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
// through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
@@ -305,13 +305,13 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// `ProviderService` (canonical stream, written after event normalization).
// Provided once at the runtime level so every consumer sees the same
// logger instances.
Layer.provideMerge(ProviderEventLoggers.ProviderEventLoggersLive),
Layer.provideMerge(ProviderEventLoggers.layer),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
// The old provider registry Layer pulled `OpenCodeRuntime.layer` in for itself, but
// the rewritten registry reads snapshots off the instance registry and
// no longer transitively provides it. Exposing it at the runtime level
// keeps a single Live for all opencode consumers.
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(ProjectFaviconResolverLayerLive),
+1 -1
View File
@@ -33,7 +33,7 @@ import * as ServerSettings from "./serverSettings.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
import * as ProviderSessionReaper from "./provider/ProviderSessionReaper.ts";
import {
formatHeadlessServeOutput,
formatHostForUrl,
@@ -39,7 +39,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
@@ -98,7 +98,9 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
);
},
},
}) as unknown as ReturnType<OpenCodeRuntime.OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
@@ -9,7 +9,7 @@ import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
import * as TextGeneration from "./TextGeneration.ts";
const makeStubTextGeneration = (
@@ -4,7 +4,7 @@ import * as Layer from "effect/Layer";
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import { TextGenerationError } from "@t3tools/contracts";
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
+1 -1
View File
@@ -73,7 +73,7 @@ import {
observeRpcStream as instrumentRpcStream,
observeRpcStreamEffect as instrumentRpcStreamEffect,
} from "./observability/RpcInstrumentation.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
@@ -40,8 +40,8 @@ const LEGACY_BASELINE = new Map<string, number>([
["apps/server/src/provider/Layers/CodexSessionRuntime.test.ts", 5],
["apps/server/src/provider/Layers/CursorAdapter.test.ts", 1],
["apps/server/src/provider/Layers/CursorProvider.test.ts", 4],
["apps/server/src/provider/Layers/ProviderService.test.ts", 2],
["apps/server/src/provider/Layers/ProviderSessionReaper.test.ts", 21],
["apps/server/src/provider/ProviderService.test.ts", 2],
["apps/server/src/provider/ProviderSessionReaper.test.ts", 21],
["apps/server/src/relay/AgentAwarenessRelay.test.ts", 4],
["apps/server/src/server.test.ts", 1],
["apps/web/src/cloud/dpop.test.ts", 2],