Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex d7849fa702 refactor(connection): preserve persistence failure causes
Co-authored-by: codex <[email protected]>
2026-06-20 18:10:46 -07:00
136 changed files with 3660 additions and 6820 deletions

No files matched your search

+2 -1
View File
@@ -18,7 +18,8 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
+58 -49
View File
@@ -58,23 +58,8 @@ const LegacyStoredShellSnapshot = Schema.Struct({
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
@@ -100,7 +85,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
},
);
@@ -117,16 +102,6 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
@@ -163,7 +138,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
});
@@ -184,18 +159,29 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -283,15 +269,19 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -303,15 +293,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -326,7 +320,11 @@ export const connectionStorageLayer = Layer.effectContext(
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -334,7 +332,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
});
}),
loadThread: (environmentId, threadId) =>
@@ -345,15 +343,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -368,7 +370,11 @@ export const connectionStorageLayer = Layer.effectContext(
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -376,7 +382,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
});
}),
removeThread: (environmentId, threadId) =>
@@ -389,7 +395,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
),
),
clear: (environmentId) =>
@@ -398,14 +404,16 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -415,7 +423,8 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
}),
@@ -33,13 +33,17 @@ import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import * as ProviderService from "../src/provider/ProviderService.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
@@ -174,7 +178,7 @@ export interface OrchestrationIntegrationHarness {
readonly adapterHarness: TestProviderAdapterHarness | null;
readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService.ProviderService["Service"];
readonly providerService: ProviderService["Service"];
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
@@ -237,7 +241,7 @@ export const makeOrchestrationIntegrationHarness = (
});
const fakeRegistry = adapterHarness
? Layer.succeed(
ProviderAdapterRegistry.ProviderAdapterRegistry,
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
: null;
@@ -258,11 +262,11 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
);
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry.ProviderAdapterRegistry,
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = yield* decodeCodexSettings({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
@@ -275,18 +279,15 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
const providerEventLoggersLayer = Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
);
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
const providerLayer = useRealCodex
? ProviderService.layer.pipe(
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
)
: ProviderService.layer.pipe(
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
@@ -394,7 +395,7 @@ export const makeOrchestrationIntegrationHarness = (
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
).pipe(Effect.orDie);
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
runtime.runPromise(Effect.service(ProviderService.ProviderService)),
runtime.runPromise(Effect.service(ProviderService)),
).pipe(Effect.orDie);
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
@@ -206,16 +206,21 @@ function nowIso(): string {
return "2026-01-01T00:00:00.000Z";
}
function sessionNotFound(
provider: ProviderDriverKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider,
threadId: String(threadId),
});
}
function missingSessionEffect(
provider: ProviderDriverKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(
new ProviderAdapterSessionNotFoundError({
provider,
threadId: String(threadId),
}),
);
return Effect.fail(sessionNotFound(provider, threadId));
}
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
@@ -512,12 +517,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(
new ProviderAdapterSessionNotFoundError({
provider,
threadId: String(threadId),
}),
),
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
@@ -10,13 +10,20 @@ import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.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 { 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 { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
@@ -44,7 +51,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService.ProviderService, unknown, never>;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
const makeIntegrationFixture = Effect.gen(function* () {
@@ -55,22 +62,19 @@ const makeIntegrationFixture = Effect.gen(function* () {
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectory.layer.pipe(
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry),
ServerSettings.ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = ProviderService.layer.pipe(Layer.provide(shared));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
@@ -101,7 +105,7 @@ const collectEventsDuring = <A, E, R>(
});
const runTurn = (input: {
readonly provider: ProviderService.ProviderService["Service"];
readonly provider: ProviderServiceShape;
readonly harness: TestProviderAdapterHarness;
readonly threadId: ThreadId;
readonly userText: string;
@@ -125,7 +129,7 @@ it.live("replays typed runtime fixture events", () =>
const fixture = yield* makeIntegrationFixture;
yield* Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: ProviderDriverKind.make("codex"),
@@ -162,7 +166,7 @@ it.live("replays file-changing fixture turn events", () =>
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: ProviderDriverKind.make("codex"),
@@ -199,7 +203,7 @@ it.live("runs multi-turn tool/approval flow", () =>
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: ProviderDriverKind.make("codex"),
@@ -251,7 +255,7 @@ it.live("rolls back provider conversation state only", () =>
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: ProviderDriverKind.make("codex"),
+4 -9
View File
@@ -2,11 +2,7 @@ import { assert, it } from "@effect/vitest";
import { EnvironmentInternalError } from "@t3tools/contracts";
import {
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerRequestError,
projectCommandErrorFromLiveServerRequest,
} from "./project.ts";
import { ProjectCommandError } from "./project.ts";
it("maps declared server failures into structural project command errors", () => {
const cause = new EnvironmentInternalError({
@@ -15,9 +11,8 @@ it("maps declared server failures into structural project command errors", () =>
traceId: "trace-123",
});
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.code, "internal_error");
assert.strictEqual(error.traceId, "trace-123");
@@ -28,10 +23,10 @@ it("maps declared server failures into structural project command errors", () =>
it("preserves unexpected server failures without deriving the message from them", () => {
const cause = new Error("credential abc123 was rejected");
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerRequestError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.detail, "Failed to call the running server.");
assert.strictEqual(error.message, "Failed to call the running server.");
assert.strictEqual(error.cause, cause);
});
+49 -138
View File
@@ -51,148 +51,62 @@ type ProjectCliDispatchCommand = Extract<
>;
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
const ProjectCommandOperation = Schema.Literals([
"generateProjectCommandId",
"callLiveServer",
"validateProjectTitle",
"resolveProjectTarget",
"addProject",
]);
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
"ProjectCommandIdGenerationError",
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
"ProjectCommandError",
{
operation: Schema.Literal("generateProjectCommandId"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to generate a project command identifier.";
}
}
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
"ProjectLiveServerDeclaredResponseError",
{
operation: Schema.Literal("callLiveServer"),
code: Schema.String,
traceId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed (${this.code}, trace ${this.traceId}).`;
}
}
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
"ProjectLiveServerUndeclaredStatusError",
{
operation: Schema.Literal("callLiveServer"),
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed with undeclared status ${this.status}.`;
}
}
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
"ProjectLiveServerRequestError",
{
operation: Schema.Literal("callLiveServer"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to call the running server.";
}
}
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
"ProjectTitleEmptyError",
{
operation: Schema.Literal("validateProjectTitle"),
title: Schema.String,
},
) {
override get message(): string {
return "Project title cannot be empty.";
}
}
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
"ProjectIdentifierEmptyError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
},
) {
override get message(): string {
return "Project identifier cannot be empty.";
}
}
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
normalizedWorkspaceRoot: Schema.optional(Schema.String),
activeProjectCount: Schema.Number,
operation: ProjectCommandOperation,
detail: Schema.String,
code: Schema.optional(Schema.String),
traceId: Schema.optional(Schema.String),
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `No active project found for '${this.identifier}'.`;
}
}
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
"ProjectAlreadyExistsError",
{
operation: Schema.Literal("addProject"),
projectId: ProjectId,
workspaceRoot: Schema.String,
},
) {
override get message(): string {
return `An active project already exists for '${this.workspaceRoot}'.`;
}
}
export const ProjectCommandError = Schema.Union([
ProjectCommandIdGenerationError,
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerUndeclaredStatusError,
ProjectLiveServerRequestError,
ProjectTitleEmptyError,
ProjectIdentifierEmptyError,
ProjectNotFoundError,
ProjectAlreadyExistsError,
]);
export type ProjectCommandError = typeof ProjectCommandError.Type;
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectLiveServerDeclaredResponseError({
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed with undeclared status ${cause.response.status}.`,
status: cause.response.status,
cause,
});
}
return new ProjectCommandError({
operation: "callLiveServer",
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectLiveServerUndeclaredStatusError({
operation: "callLiveServer",
status: cause.response.status,
detail: "Failed to call the running server.",
cause,
});
}
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
override get message(): string {
return this.detail;
}
}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
(cause) =>
new ProjectCommandIdGenerationError({
new ProjectCommandError({
operation: "generateProjectCommandId",
detail: "Failed to generate a project command identifier.",
cause,
}),
),
@@ -244,9 +158,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
if (trimmed.length > 0) {
return trimmed;
}
return yield* new ProjectTitleEmptyError({
return yield* new ProjectCommandError({
operation: "validateProjectTitle",
title: explicitTitle,
detail: "Project title cannot be empty.",
});
}
@@ -261,9 +175,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* new ProjectIdentifierEmptyError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: input.identifier,
detail: "Project identifier cannot be empty.",
});
}
@@ -290,11 +204,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* new ProjectNotFoundError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: trimmedIdentifier,
activeProjectCount: activeProjects.length,
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
detail: `No active project found for '${trimmedIdentifier}'.`,
...(normalizedWorkspaceRootResult._tag === "Failure"
? { cause: normalizedWorkspaceRootResult.failure }
: {}),
@@ -316,7 +228,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
});
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const dispatchLiveOrchestrationCommand = (
@@ -332,7 +244,7 @@ const dispatchLiveOrchestrationCommand = (
} as Parameters<typeof client.orchestration.dispatch>[0]);
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
@@ -464,10 +376,9 @@ const projectAddCommand = Command.make("add", {
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* new ProjectAlreadyExistsError({
return yield* new ProjectCommandError({
operation: "addProject",
projectId: existingProject.id,
workspaceRoot,
detail: `An active project already exists for '${workspaceRoot}'.`,
});
}
+39 -17
View File
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
if (result.status === 0) {
return;
}
throw new Error(
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
throw new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd,
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
});
}
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
(error as { _tag?: unknown })._tag === "GitHubCliError"
);
}
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return fakeGhOutput("");
},
catch: (error) =>
GitHubCli.isGitHubCliError(error)
isGitHubCliError(error)
? error
: new GitHubCli.GitHubCliCommandError({
: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: error,
detail:
error instanceof Error
? `Failed to simulate gh checkout: ${error.message}`
: "Failed to simulate gh checkout.",
}),
});
}
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
if (!cloneUrls) {
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository lookup: ${repository}`),
detail: `Unexpected repository lookup: ${repository}`,
}),
);
}
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
detail: `Unexpected gh command: ${args.join(" ")}`,
}),
);
};
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "createRepository",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository create: ${input.repository}`),
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2463,10 +2483,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2493,10 +2514,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliAuthenticationError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not authenticated"),
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
},
});
@@ -1,39 +0,0 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as McpInvocationContext from "./McpInvocationContext.ts";
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(),
issuedAt: 1,
expiresAt: 2,
};
return Effect.gen(function* () {
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.flip,
);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
expect(error).toMatchObject({
capability: "preview",
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
expect(error.message).toBe("MCP credential does not grant the preview capability.");
});
});
+3 -11
View File
@@ -1,9 +1,5 @@
import {
type EnvironmentId,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -30,11 +26,7 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
capability,
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
message: `MCP credential does not grant the ${capability} capability.`,
});
}
return invocation;
@@ -49,7 +49,10 @@ import {
} from "../Services/OrchestrationEngine.ts";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import * as ProviderService from "../../provider/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
@@ -99,7 +102,7 @@ function createProviderServiceHarness(
},
] satisfies ReadonlyArray<ProviderSession>)
: Effect.succeed([] as ReadonlyArray<ProviderSession>);
const service: ProviderService.ProviderService["Service"] = {
const service: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
@@ -325,7 +328,7 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
Layer.provideMerge(
@@ -25,7 +25,7 @@ import {
resolveThreadWorkspaceCwd,
} from "../../checkpointing/Utils.ts";
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
import * as ProviderService from "../../provider/ProviderService.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
@@ -80,7 +80,7 @@ const make = Effect.gen(function* () {
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService.ProviderService;
const providerService = yield* ProviderService;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
@@ -37,7 +37,10 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as ProviderService from "../../provider/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
@@ -219,12 +222,8 @@ describe("ProviderCommandReactor", () => {
}),
);
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn<ProviderService.ProviderService["Service"]["respondToRequest"]>(
() => Effect.void,
);
const respondToUserInput = vi.fn<
ProviderService.ProviderService["Service"]["respondToUserInput"]
>(() => Effect.void);
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
const stopSession = vi.fn((input: unknown) =>
Effect.sync(() => {
const threadId =
@@ -295,15 +294,13 @@ describe("ProviderCommandReactor", () => {
];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderService.ProviderService["Service"] = {
startSession: startSession as ProviderService.ProviderService["Service"]["startSession"],
sendTurn: sendTurn as ProviderService.ProviderService["Service"]["sendTurn"],
interruptTurn: interruptTurn as ProviderService.ProviderService["Service"]["interruptTurn"],
respondToRequest:
respondToRequest as ProviderService.ProviderService["Service"]["respondToRequest"],
respondToUserInput:
respondToUserInput as ProviderService.ProviderService["Service"]["respondToUserInput"],
stopSession: stopSession as ProviderService.ProviderService["Service"]["stopSession"],
const service: ProviderServiceShape = {
startSession: startSession as ProviderServiceShape["startSession"],
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (_provider) =>
Effect.succeed({
@@ -349,7 +346,7 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, service)),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
Layer.provideMerge(
Layer.mock(GitWorkflowService.GitWorkflowService)({
@@ -30,8 +30,8 @@ import { increment, orchestrationEventsProcessedTotal } from "../../observabilit
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import * as ProviderService from "../../provider/ProviderService.ts";
import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
@@ -190,8 +190,8 @@ const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService.ProviderService;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
@@ -35,7 +35,10 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as ProviderService from "../../provider/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -94,7 +97,7 @@ function createProviderServiceHarness() {
const runtimeSessions: ProviderSession[] = [];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderService.ProviderService["Service"] = {
const service: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
@@ -234,7 +237,7 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -27,7 +27,7 @@ import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import * as ProviderService from "../../provider/ProviderService.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { isGitRepository } from "../../git/Utils.ts";
@@ -631,7 +631,7 @@ const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService.ProviderService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as ProviderService from "../../provider/ProviderService.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import * as TerminalManager from "../../terminal/Manager.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -38,7 +38,7 @@ export const logCleanupCauseUnlessInterrupted = <R, E>({
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService.ProviderService;
const providerService = yield* ProviderService;
const terminalManager = yield* TerminalManager.TerminalManager;
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
@@ -20,12 +20,12 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } 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 * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -87,9 +87,9 @@ export type ClaudeDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
| ProviderEventLoggers
| ServerConfig
| 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* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -193,7 +193,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build the Claude provider snapshot.",
detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
+12 -12
View File
@@ -28,16 +28,16 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { ProviderEventLoggers } from "../Layers/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.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
| ProviderEventLoggers
| ServerConfig
| 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* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const homeLayout = yield* resolveCodexHomeLayout(config);
const continuationIdentity = codexContinuationIdentity(homeLayout);
@@ -134,7 +134,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to materialize the Codex shadow home.",
detail: cause.message,
cause,
}),
),
@@ -193,7 +193,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build the Codex provider snapshot.",
detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
@@ -18,11 +18,11 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } 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 * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -70,9 +70,9 @@ export type CursorDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
| ProviderEventLoggers
| ServerConfig
| 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* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -165,7 +165,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build the Cursor provider snapshot.",
detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
+11 -11
View File
@@ -5,11 +5,11 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } 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 * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
@@ -54,9 +54,9 @@ export type GrokDriverEnv =
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
| ProviderEventLoggers
| ServerConfig
| 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* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -141,7 +141,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build the Grok provider snapshot.",
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
@@ -19,21 +19,21 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
checkOpenCodeProviderStatus,
makePendingOpenCodeProvider,
} from "../Layers/OpenCodeProvider.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import { 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.ProviderEventLoggers
| ServerConfig.ServerConfig
| ServerSettings.ServerSettingsService;
| ProviderEventLoggers
| ServerConfig
| 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.OpenCodeRuntime;
const serverConfig = yield* ServerConfig.ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const serverConfig = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -147,10 +147,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
effectiveConfig,
serverConfig.cwd,
processEnv,
).pipe(
Effect.map(stampIdentity),
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
);
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
@@ -177,7 +174,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build the OpenCode provider snapshot.",
detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
+2 -5
View File
@@ -64,7 +64,7 @@ export class ProviderAdapterRequestError extends Schema.TaggedErrorClass<Provide
},
) {
override get message(): string {
return `Provider adapter request failed (${this.provider}) for ${this.method}.`;
return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;
}
}
@@ -76,13 +76,12 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
{
provider: Schema.String,
threadId: Schema.String,
stage: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Provider adapter process failed (${this.provider}) during ${this.stage} for thread ${this.threadId}.`;
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
}
}
@@ -172,8 +171,6 @@ export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<Provid
}
}
export const isProviderSessionNotFoundError = Schema.is(ProviderSessionNotFoundError);
/**
* ProviderSessionDirectoryPersistenceError - Session directory persistence failure.
*/
@@ -327,7 +327,6 @@ describe("ClaudeAdapterLive", () => {
.pipe(Effect.flip);
assert.instanceOf(error, ProviderAdapterProcessError);
assert.equal(error.stage, "session-start");
assert.equal(error.detail, "Failed to start Claude runtime session.");
assert.strictEqual(error.cause, cause);
assert.notMatch(error.message, /credential material/u);
@@ -2893,7 +2893,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
stage: "runtime-stream",
detail: "Claude runtime stream failed.",
cause,
}),
@@ -2906,7 +2905,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
stage: "runtime-event",
detail: "Failed to process Claude runtime event.",
cause,
}),
@@ -2994,7 +2992,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
stage: "runtime-query-close",
detail: "Failed to close Claude runtime query.",
cause,
}),
@@ -3518,7 +3515,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
stage: "session-start",
detail: "Failed to start Claude runtime session.",
cause,
}),
@@ -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 * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
type CodexSessionRuntimeSendTurnInput,
@@ -211,17 +211,14 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
};
}
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 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 validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
@@ -235,7 +232,7 @@ const validationLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -304,7 +301,7 @@ const sessionErrorLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -376,7 +373,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -430,7 +427,7 @@ const lifecycleLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1103,7 +1100,7 @@ const scopedLifecycleLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1147,7 +1144,7 @@ const scopedFailureLayer = it.layer(
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -1199,7 +1196,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -116,7 +116,7 @@ function mapCodexRuntimeError(
return new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: "Codex runtime request failed.",
detail: error.message,
cause: error,
});
}
@@ -1432,8 +1432,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
stage: "session-runtime-create",
detail: "Failed to create Codex runtime session.",
detail: cause.message,
cause,
}),
),
@@ -1462,8 +1461,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
stage: "session-start",
detail: "Failed to start Codex runtime session.",
detail: cause.message,
cause,
}),
),
@@ -1510,7 +1508,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: "Failed to read attachment file.",
detail: `Failed to read attachment file: ${cause.message}.`,
cause,
}),
),
@@ -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 * as Config from "../../config.ts";
import { ServerConfig } 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(Config.ServerConfig);
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -564,8 +564,7 @@ export function makeCursorAdapter(
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
stage: "session-start",
detail: "Failed to start the Cursor ACP session process.",
detail: cause.message,
cause,
}),
),
@@ -980,7 +979,7 @@ export function makeCursorAdapter(
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Failed to read attachment '${attachment.id}'.`,
detail: cause.message,
cause,
}),
),
@@ -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 * as Config from "../../config.ts";
import { ServerConfig } 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(Config.ServerConfig);
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -408,8 +408,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
stage: "session-start",
detail: "Failed to start the Grok ACP session process.",
detail: cause.message,
cause,
}),
),
@@ -737,7 +736,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Failed to read attachment '${attachment.id}'.`,
detail: cause.message,
cause,
}),
),
@@ -20,11 +20,15 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import * as Config from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import {
appendOpenCodeAssistantTextDelta,
makeOpenCodeAdapter,
@@ -75,7 +79,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
runtimeMock.state.startCalls.push(binaryPath);
@@ -163,12 +167,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
})(),
}),
},
}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
@@ -176,17 +178,14 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
),
};
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 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([]),
});
// The adapter now receives its settings as a plain argument (the old design
// read from `ServerSettingsService` internally). The test-only
@@ -204,10 +203,10 @@ const OpenCodeAdapterTestLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerSettings.ServerSettingsService.layerTest({
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -335,11 +334,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -369,8 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
runtimeMode: "full-access",
});
const promptFailure = new Error("prompt failed");
runtimeMock.state.promptAsyncError = promptFailure;
runtimeMock.state.promptAsyncError = new Error("prompt failed");
const error = yield* adapter
.sendTurn({
threadId: asThreadId("thread-send-turn-failure"),
@@ -387,17 +383,15 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
if (error._tag !== "ProviderAdapterRequestError") {
throw new Error("Unexpected error type");
}
NodeAssert.equal(error.detail, "OpenCode SDK request failed.");
NodeAssert.equal(error.detail, "prompt failed");
NodeAssert.equal(
error.message,
"Provider adapter request failed (opencode) for session.promptAsync.",
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
);
NodeAssert.ok(OpenCodeRuntime.isOpenCodeRuntimeError(error.cause));
NodeAssert.strictEqual(error.cause.cause, promptFailure);
NodeAssert.equal(sessions.length, 1);
NodeAssert.equal(sessions[0]?.status, "ready");
NodeAssert.equal(sessions[0]?.activeTurnId, undefined);
NodeAssert.equal(sessions[0]?.lastError, "OpenCode SDK request failed.");
NodeAssert.equal(sessions[0]?.lastError, "prompt failed");
}),
);
@@ -486,9 +480,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -533,9 +527,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -575,9 +569,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -798,12 +792,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
nativeEventLogger,
}),
).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(
ServerSettings.ServerSettingsService.layerTest({
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -882,12 +874,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
nativeEventLogger,
}),
).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(
ServerSettings.ServerSettingsService.layerTest({
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
@@ -25,7 +25,7 @@ import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
@@ -36,7 +36,19 @@ import {
ProviderAdapterValidationError,
} from "../Errors.ts";
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import {
buildOpenCodePermissionRules,
OpenCodeRuntime,
OpenCodeRuntimeError,
openCodeQuestionId,
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
runOpenCodeSdk,
toOpenCodeFileParts,
toOpenCodePermissionReply,
toOpenCodeQuestionAnswers,
type OpenCodeServerConnection,
} from "../opencodeRuntime.ts";
import * as Option from "effect/Option";
const PROVIDER = ProviderDriverKind.make("opencode");
@@ -56,7 +68,7 @@ type OpenCodeSubscribedEvent =
interface OpenCodeSessionContext {
session: ProviderSession;
readonly client: OpencodeClient;
readonly server: OpenCodeRuntime.OpenCodeServerConnection;
readonly server: OpenCodeServerConnection;
readonly directory: string;
readonly openCodeSessionId: string;
readonly pendingPermissions: Map<string, PermissionRequest>;
@@ -96,16 +108,30 @@ export interface OpenCodeAdapterLiveOptions {
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
/**
* Map a tagged OpenCodeRuntimeError produced by {@link OpenCodeRuntime.runOpenCodeSdk} into
* Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
* the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call
* sites pipe through this in `Effect.mapError` so they never build the error
* shape by hand.
*/
const toRequestError = (cause: OpenCodeRuntime.OpenCodeRuntimeError): ProviderAdapterRequestError =>
const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: cause.operation,
detail: "OpenCode SDK request failed.",
detail: cause.detail,
cause: cause.cause,
});
/**
* Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The
* typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),
* in which case we preserve its `detail`; otherwise we fall back to
* {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).
*/
const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
cause,
});
@@ -227,7 +253,7 @@ function ensureSessionContext(
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
return request.questions.map((question, index) => ({
id: OpenCodeRuntime.openCodeQuestionId(index, question),
id: openCodeQuestionId(index, question),
header: question.header,
question: question.question,
options: question.options.map((option) => ({
@@ -387,7 +413,7 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (
// Best-effort remote abort. The scope close below tears down the local
// handles (event-pump fiber, server-exit fiber, event-subscribe fetch),
// but we still want to tell OpenCode that this session is done.
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
yield* runOpenCodeSdk("session.abort", () =>
context.client.session.abort({ sessionID: context.openCodeSessionId }),
).pipe(Effect.ignore({ log: true }));
@@ -404,8 +430,8 @@ export function makeOpenCodeAdapter(
) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");
const serverConfig = yield* ServerConfig.ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -543,7 +569,7 @@ export function makeOpenCodeAdapter(
// Inline the teardown that `stopOpenCodeContext` would do; we can't
// delegate to it because our `getAndSet` above already flipped the
// one-shot guard, so the call would no-op.
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
yield* runOpenCodeSdk("session.abort", () =>
context.client.session.abort({ sessionID: context.openCodeSessionId }),
).pipe(Effect.ignore({ log: true }));
yield* Scope.close(context.sessionScope, Exit.void);
@@ -815,7 +841,7 @@ export function makeOpenCodeAdapter(
context.pendingQuestions.delete(event.properties.requestID);
const answers = Object.fromEntries(
(request?.questions ?? []).map((question, index) => [
OpenCodeRuntime.openCodeQuestionId(index, question),
openCodeQuestionId(index, question),
event.properties.answers[index]?.join(", ") ?? "",
]),
);
@@ -949,18 +975,20 @@ export function makeOpenCodeAdapter(
// Fibers forked into `context.sessionScope` are interrupted
// automatically when the scope closes — no bookkeeping required.
yield* Effect.flatMap(
OpenCodeRuntime.runOpenCodeSdk("event.subscribe", () =>
runOpenCodeSdk("event.subscribe", () =>
context.client.event.subscribe(undefined, {
signal: eventsAbortController.signal,
}),
),
(subscription) =>
Stream.fromAsyncIterable(subscription.stream, (cause) =>
OpenCodeRuntime.OpenCodeRuntimeError.fromCause({
operation: "event.subscribe",
detail: "OpenCode event subscription failed.",
cause,
}),
Stream.fromAsyncIterable(
subscription.stream,
(cause) =>
new OpenCodeRuntimeError({
operation: "event.subscribe",
detail: openCodeRuntimeErrorDetail(cause),
cause,
}),
).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
).pipe(
Effect.exit,
@@ -974,7 +1002,7 @@ export function makeOpenCodeAdapter(
if (Exit.isFailure(exit)) {
yield* emitUnexpectedExit(
context,
OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(Cause.squash(exit.cause)),
openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),
);
}
}),
@@ -1028,7 +1056,7 @@ export function makeOpenCodeAdapter(
});
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
if (mcpSession && !server.external) {
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
yield* runOpenCodeSdk("mcp.add", () =>
client.mcp.add({
name: "t3-code",
config: {
@@ -1042,14 +1070,14 @@ export function makeOpenCodeAdapter(
}),
);
}
const openCodeSession = yield* OpenCodeRuntime.runOpenCodeSdk("session.create", () =>
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
client.session.create({
title: `T3 Code ${input.threadId}`,
permission: OpenCodeRuntime.buildOpenCodePermissionRules(input.runtimeMode),
permission: buildOpenCodePermissionRules(input.runtimeMode),
}),
);
if (!openCodeSession.data) {
return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
return yield* new OpenCodeRuntimeError({
operation: "session.create",
detail: "OpenCode session.create returned no session payload.",
});
@@ -1064,14 +1092,7 @@ export function makeOpenCodeAdapter(
);
if (Exit.isFailure(startedExit)) {
yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);
const cause = Cause.squash(startedExit.cause);
return yield* new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
stage: "session-start",
detail: "Failed to start OpenCode runtime session.",
cause,
});
return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));
}
return startedExit.value;
});
@@ -1082,7 +1103,7 @@ export function makeOpenCodeAdapter(
if (raceWinner) {
// Another call won the race – clean up the session we just created
// (including the remote SDK session) and return the existing one.
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
yield* runOpenCodeSdk("session.abort", () =>
started.client.session.abort({
sessionID: started.openCodeSession.id,
}),
@@ -1164,7 +1185,7 @@ export function makeOpenCodeAdapter(
issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,
});
}
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(modelSelection?.model);
const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);
if (!parsedModel) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
@@ -1174,7 +1195,7 @@ export function makeOpenCodeAdapter(
}
const text = input.input?.trim();
const fileParts = OpenCodeRuntime.toOpenCodeFileParts({
const fileParts = toOpenCodeFileParts({
attachments: input.attachments,
resolveAttachmentPath: (attachment) =>
resolveAttachmentPath({
@@ -1217,7 +1238,7 @@ export function makeOpenCodeAdapter(
});
}
yield* OpenCodeRuntime.runOpenCodeSdk("session.promptAsync", () =>
yield* runOpenCodeSdk("session.promptAsync", () =>
context.client.session.promptAsync({
sessionID: context.openCodeSessionId,
model: parsedModel,
@@ -1271,7 +1292,7 @@ export function makeOpenCodeAdapter(
const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, turnId) {
const context = ensureSessionContext(sessions, threadId);
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
yield* runOpenCodeSdk("session.abort", () =>
context.client.session.abort({ sessionID: context.openCodeSessionId }),
).pipe(Effect.mapError(toRequestError));
if (turnId ?? context.activeTurnId) {
@@ -1301,10 +1322,10 @@ export function makeOpenCodeAdapter(
});
}
yield* OpenCodeRuntime.runOpenCodeSdk("permission.reply", () =>
yield* runOpenCodeSdk("permission.reply", () =>
context.client.permission.reply({
requestID: requestId,
reply: OpenCodeRuntime.toOpenCodePermissionReply(decision),
reply: toOpenCodePermissionReply(decision),
}),
).pipe(Effect.mapError(toRequestError));
});
@@ -1322,10 +1343,10 @@ export function makeOpenCodeAdapter(
});
}
yield* OpenCodeRuntime.runOpenCodeSdk("question.reply", () =>
yield* runOpenCodeSdk("question.reply", () =>
context.client.question.reply({
requestID: requestId,
answers: OpenCodeRuntime.toOpenCodeQuestionAnswers(request, answers),
answers: toOpenCodeQuestionAnswers(request, answers),
}),
).pipe(Effect.mapError(toRequestError));
});
@@ -1365,7 +1386,7 @@ export function makeOpenCodeAdapter(
const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
function* (threadId) {
const context = ensureSessionContext(sessions, threadId);
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
const messages = yield* runOpenCodeSdk("session.messages", () =>
context.client.session.messages({
sessionID: context.openCodeSessionId,
}),
@@ -1391,7 +1412,7 @@ export function makeOpenCodeAdapter(
const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
function* (threadId, numTurns) {
const context = ensureSessionContext(sessions, threadId);
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
const messages = yield* runOpenCodeSdk("session.messages", () =>
context.client.session.messages({
sessionID: context.openCodeSessionId,
}),
@@ -1402,7 +1423,7 @@ export function makeOpenCodeAdapter(
);
const targetIndex = assistantMessages.length - numTurns - 1;
const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;
yield* OpenCodeRuntime.runOpenCodeSdk("session.revert", () =>
yield* runOpenCodeSdk("session.revert", () =>
context.client.session.revert({
sessionID: context.openCodeSessionId,
...(target ? { messageID: target.info.id } : {}),
@@ -8,10 +8,14 @@ import * as Schema from "effect/Schema";
import { beforeEach } from "vite-plus/test";
import { OpenCodeSettings } from "@t3tools/contracts";
import * as Config from "../../config.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import { checkOpenCodeProviderStatus, OpenCodeProbeError } from "./OpenCodeProvider.ts";
import { ServerConfig } from "../../config.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} 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";
@@ -48,7 +52,7 @@ const runtimeMock = {
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: () =>
Effect.succeed({
url: "http://127.0.0.1:4301",
@@ -72,7 +76,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
runOpenCodeCommand: () =>
runtimeMock.state.runVersionError
? Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
new OpenCodeRuntimeError({
operation: "runOpenCodeCommand",
detail: runtimeMock.state.runVersionError.message,
cause: runtimeMock.state.runVersionError,
@@ -80,27 +84,25 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
)
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
createOpenCodeSdkClient: () =>
({}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
runtimeMock.state.inventoryError
? Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: runtimeMock.state.inventoryError.message,
cause: runtimeMock.state.inventoryError,
}),
)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeRuntime.OpenCodeInventory),
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
};
beforeEach(() => {
runtimeMock.reset();
});
const testLayer = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -114,24 +116,6 @@ const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSe
...overrides,
});
it("structures OpenCode probe failures without deriving messages from causes", () => {
const cause = new Error("401 Unauthorized");
const runtimeError = new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: cause.message,
cause,
});
const probeError = OpenCodeProbeError.fromCause("load-inventory")(runtimeError);
const versionProbeError = OpenCodeProbeError.fromCause("probe-version")(runtimeError);
NodeAssert.equal(probeError.operation, "load-inventory");
NodeAssert.equal(probeError.detail, "401 Unauthorized");
NodeAssert.strictEqual(probeError.cause, runtimeError);
NodeAssert.strictEqual(runtimeError.cause, cause);
NodeAssert.equal(probeError.message, "OpenCode probe failed during load-inventory.");
NodeAssert.equal(versionProbeError.message, "OpenCode probe failed during probe-version.");
});
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
it.effect("shows a codex-style missing binary message", () =>
Effect.gen(function* () {
@@ -228,7 +212,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://url-user:[email protected]:9999/private?token=secret#fragment",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
}),
process.cwd(),
@@ -262,28 +246,6 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
snapshot.message,
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
);
NodeAssert.doesNotMatch(
snapshot.message ?? "",
/url-user|url-password|private|token|secret|fragment/,
);
}),
);
it.effect("keeps IPv6 brackets in configured server diagnostics", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("fetch failed: connect ECONNREFUSED ::1:9999");
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://[::1]:9999/private",
serverPassword: "secret-password",
}),
process.cwd(),
);
NodeAssert.equal(
snapshot.message,
"Couldn't reach the configured OpenCode server at http://[::1]:9999. Check that the server is running and the URL is correct.",
);
}),
);
});
@@ -5,9 +5,9 @@ import {
type ServerProviderModel,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { createModelCapabilities } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -18,7 +18,11 @@ import {
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
type OpenCodeInventory,
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = ProviderDriverKind.make("opencode");
@@ -28,29 +32,10 @@ const OPENCODE_PRESENTATION = {
} as const;
const MINIMUM_OPENCODE_VERSION = "1.14.19";
export class OpenCodeProbeError extends Schema.TaggedErrorClass<OpenCodeProbeError>()(
"OpenCodeProbeError",
{
operation: Schema.Literals(["probe-version", "load-inventory"]),
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `OpenCode probe failed during ${this.operation}.`;
}
static fromCause(operation: "probe-version" | "load-inventory") {
return (cause: unknown): OpenCodeProbeError =>
new OpenCodeProbeError({
operation,
detail: OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(cause),
cause,
});
}
}
export const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
readonly cause: unknown;
readonly detail: string;
}> {}
function normalizeProbeMessage(message: string): string | undefined {
const trimmed = message.trim();
@@ -67,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined {
}
function normalizedErrorMessage(cause: unknown): string | undefined {
if (isOpenCodeProbeError(cause)) {
if (cause instanceof OpenCodeProbeError) {
return normalizeProbeMessage(cause.detail);
}
@@ -78,15 +63,6 @@ function normalizedErrorMessage(cause: unknown): string | undefined {
return normalizeProbeMessage(cause.message);
}
function openCodeServerDisplayTarget(input: string): string | undefined {
try {
const url = new URL(input);
return `${url.protocol}//${url.host}`;
} catch {
return undefined;
}
}
function formatOpenCodeProbeError(input: {
readonly cause: unknown;
readonly isExternalServer: boolean;
@@ -117,13 +93,9 @@ function formatOpenCodeProbeError(input: {
lower.includes("timeout") ||
lower.includes("socket hang up")
) {
const serverTarget = openCodeServerDisplayTarget(input.serverUrl);
return {
installed: true,
message:
serverTarget === undefined
? "Couldn't reach the configured OpenCode server. Check that the server is running and the URL is correct."
: `Couldn't reach the configured OpenCode server at ${serverTarget}. Check that the server is running and the URL is correct.`,
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
};
}
@@ -247,9 +219,7 @@ function openCodeCapabilitiesForModel(input: {
});
}
function flattenOpenCodeModels(
input: OpenCodeRuntime.OpenCodeInventory,
): ReadonlyArray<ServerProviderModel> {
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
const connected = new Set(input.providerList.connected);
const models: Array<ServerProviderModel> = [];
@@ -332,18 +302,20 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
openCodeSettings: OpenCodeSettings,
cwd: string,
environment?: NodeJS.ProcessEnv,
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime.OpenCodeRuntime> {
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
const openCodeRuntime = yield* OpenCodeRuntime;
const resolvedEnvironment = environment ?? process.env;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const customModels = openCodeSettings.customModels;
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
const buildFailureSnapshot = (
failure: { readonly installed: boolean; readonly message: string },
version: string | null,
) =>
buildServerProvider({
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: openCodeSettings.serverUrl,
});
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
@@ -361,16 +333,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
message: failure.message,
},
});
const fallback = (cause: unknown, version: string | null = null) =>
buildFailureSnapshot(
formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: openCodeSettings.serverUrl,
}),
version,
);
};
if (!openCodeSettings.enabled) {
return buildServerProvider({
@@ -404,7 +367,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
args: ["--version"],
environment: resolvedEnvironment,
})
.pipe(Effect.mapError(OpenCodeProbeError.fromCause("probe-version"))),
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
@@ -412,11 +379,10 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return buildFailureSnapshot(
{
installed: true,
message: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
}
@@ -459,7 +425,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
: {}),
}),
);
}).pipe(Effect.mapError(OpenCodeProbeError.fromCause("load-inventory"))),
}).pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
),
);
if (inventoryExit._tag === "Failure") {
@@ -10,15 +10,16 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
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 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 * as NodeServices from "@effect/platform-node/NodeServices";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
@@ -26,7 +27,7 @@ const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
const fakeCodexAdapter: CodexAdapterShape = {
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
provider: CODEX_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -43,7 +44,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeAdapterShape = {
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
provider: CLAUDE_AGENT_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -60,7 +61,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
provider: OPENCODE_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -77,7 +78,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapterShape = {
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
provider: CURSOR_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
@@ -94,7 +95,7 @@ const fakeCursorAdapter: CursorAdapterShape = {
streamEvents: Stream.empty,
};
// ProviderAdapterRegistry is a facade over ProviderInstanceRegistry —
// ProviderAdapterRegistryLive is now 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
@@ -146,11 +147,14 @@ const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.Provide
});
const layer = Layer.mergeAll(
Layer.provide(ProviderAdapterRegistry.layer, fakeInstanceRegistryLayer),
Layer.provide(
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
fakeInstanceRegistryLayer,
),
NodeServices.layer,
);
it.layer(layer)("ProviderAdapterRegistry", (it) => {
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
it("resolves adapters and routing metadata from provider instances", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
@@ -0,0 +1,117 @@
/**
* 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 };
@@ -25,37 +25,39 @@
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/ProviderEventLoggers
* @module provider/Layers/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";
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
* (`layer`); consumers (drivers, `ProviderService`) read
* (`ProviderEventLoggersLive`); 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") {}
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: ProviderEventLoggers["Service"] = {
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
native: undefined,
canonical: undefined,
};
@@ -65,15 +67,19 @@ export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
* 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);
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;
}),
);
@@ -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 `ProviderInstanceRegistry.mutableLayer`.
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
* 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,9 +51,11 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as ServerSettingsModule from "../../serverSettings.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
import * as ProviderInstanceRegistry from "../ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
/**
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
@@ -114,8 +116,8 @@ export const deriveProviderInstanceConfigMap = (
*/
const SettingsWatcherLive = Layer.effectDiscard(
Effect.gen(function* () {
const mutator = yield* ProviderInstanceRegistry.ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const mutator = yield* ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.streamChanges.pipe(
Stream.runForEach((next) =>
mutator
@@ -136,7 +138,7 @@ const SettingsWatcherLive = Layer.effectDiscard(
* sync with subsequent `streamChanges` emissions.
*
* The Layer's two halves:
* - `ProviderInstanceRegistry.mutableLayer` produces the registry +
* - `ProviderInstanceRegistryMutableLayer` 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
@@ -148,12 +150,12 @@ const SettingsWatcherLive = Layer.effectDiscard(
* it, so the visibility leak is harmless in practice.
*/
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
ProviderInstanceRegistry.ProviderInstanceRegistry,
ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
BuiltInDriversEnv | ServerSettingsService
> = Layer.unwrap(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const serverSettings = yield* ServerSettingsService;
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
Effect.orElseSucceed(() => undefined),
);
@@ -162,15 +164,11 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
? ({} as ProviderInstanceConfigMap)
: deriveProviderInstanceConfigMap(initialSettings);
const mutableLayer = ProviderInstanceRegistry.mutableLayer({
const mutableLayer = ProviderInstanceRegistryMutableLayer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
});
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
}),
) as Layer.Layer<
ProviderInstanceRegistry.ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
>;
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
@@ -1,5 +1,5 @@
/**
* Multi-instance validation slices for `ProviderInstanceRegistry`.
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
*
* Two axes of the driver/registry refactor are exercised here:
*
@@ -36,19 +36,18 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
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";
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";
const TestHttpClientLive = Layer.succeed(
HttpClient.HttpClient,
@@ -99,24 +98,19 @@ const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSetti
...overrides,
});
describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
describe("ProviderInstanceRegistryLive — 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 = Config.ServerConfig.layerTest(process.cwd(), {
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
@@ -148,7 +142,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
},
};
const { registry } = yield* ProviderInstanceRegistry.make({
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
@@ -214,7 +208,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
},
};
const { registry } = yield* ProviderInstanceRegistry.make({
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
@@ -234,32 +228,27 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
);
});
describe("ProviderInstanceRegistry — all drivers slice", () => {
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntime.layer` into the stack.
// `OpenCodeRuntime.layer` bundles its own `NetService.layer` via
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` 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 `OpenCodeRuntime.layer`'s deps while keeping its own outputs
// provides `OpenCodeRuntimeLive`'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 = OpenCodeRuntime.layer.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots one instance of every shipped driver from a single config map", () =>
@@ -312,7 +301,7 @@ describe("ProviderInstanceRegistry — all drivers slice", () => {
},
};
const { registry } = yield* ProviderInstanceRegistry.make({
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
configMap,
});
@@ -1,5 +1,5 @@
/**
* ProviderInstanceRegistry — runtime implementation of
* ProviderInstanceRegistryLive — 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/ProviderInstanceRegistry
* @module provider/Layers/ProviderInstanceRegistryLive
*/
import {
defaultInstanceIdForDriver,
@@ -48,86 +48,19 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts";
import type { AnyProviderDriver, ProviderInstance } from "./ProviderDriver.ts";
export class ProviderInstanceRegistry extends Context.Service<
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
import {
ProviderInstanceRegistry,
{
/**
* Look up one instance by id. Returns `undefined` (not `Option`) when the
* id is unknown; callers branch on absence and emit the appropriate domain
* error.
*/
readonly getInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<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.
* The payload is `void` because consumers always re-pull `listInstances`
* and `listUnavailable` together.
*
* `Stream.fromPubSub` defers `PubSub.subscribe` until the stream starts
* running, so forking a consumer races the next publish. Hot-reload
* consumers that cannot miss a publish should use `subscribeChanges`
* instead, which acquires the subscription synchronously before the
* consumer loop is forked.
*/
readonly streamChanges: Stream.Stream<void>;
/**
* Acquire a scoped subscription to the change channel synchronously in the
* caller's fiber. Consumers typically `yield*` this in the same fiber that
* forks their consumer loop, then drain it with `PubSub.take` or
* `Stream.fromSubscription`. Because the subscription is registered before
* this effect returns, no subsequent publish can land in a gap.
*/
readonly subscribeChanges: Effect.Effect<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<
type ProviderInstanceRegistryShape,
} from "../Services/ProviderInstanceRegistry.ts";
import {
ProviderInstanceRegistryMutator,
{
/**
* Bring the live registry in line with the supplied config map. The
* operation closes removed or replaced scopes before creating replacements
* and publishes a single change tick after the batch. Reapplying an
* unchanged map is a no-op.
*
* The effect never fails: individual driver creation failures become
* unavailable shadow snapshots, keeping settings-watcher loops alive when
* one entry is invalid.
*/
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
}
>()("t3/provider/ProviderInstanceRegistry/ProviderInstanceRegistryMutator") {}
type ProviderInstanceRegistryMutatorShape,
} from "../Services/ProviderInstanceRegistryMutator.ts";
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
/**
* Live registry entry: the materialized `ProviderInstance` + the fresh
@@ -160,8 +93,6 @@ interface RegistryState {
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
Equal.equals(a, b);
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
return undefined;
@@ -206,13 +137,12 @@ const buildEntry = <R>(input: {
const decoder = Schema.decodeUnknownEffect(driver.configSchema);
const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
if (decodeResult._tag === "Failure") {
const cause = decodeResult.failure;
const detail = formatSchemaIssue(cause.issue);
const issue = decodeResult.failure;
const detail = issue.message ?? String(issue);
yield* Effect.logError("Failed to decode provider instance config", {
instanceId: rawInstanceId,
driver: entry.driver,
detail,
cause,
});
return {
kind: "unavailable" as const,
@@ -250,7 +180,6 @@ const buildEntry = <R>(input: {
instanceId: rawInstanceId,
driver: entry.driver,
detail: createResult.failure.detail,
cause: createResult.failure,
});
yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
return {
@@ -386,9 +315,9 @@ const makeReconcile = <R>(input: {
* Build the registry's runtime state from a concrete configMap. Returns a
* record containing:
*
* - `registry`: the read-only `ProviderInstanceRegistry["Service"]` to expose
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
* under `ProviderInstanceRegistry`.
* - `mutator`: the `ProviderInstanceRegistryMutator["Service"]` to expose
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
* under `ProviderInstanceRegistryMutator`.
* - `reconcile`: the raw reconcile function, provided for convenience so
* boot-time layers can hydrate an initial map before publishing the
@@ -398,13 +327,13 @@ const makeReconcile = <R>(input: {
* created during `reconcile`. Closing that scope closes every live
* instance.
*/
export const make = <R>(input: {
export const makeProviderInstanceRegistry = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Effect.Effect<
{
readonly registry: ProviderInstanceRegistry["Service"];
readonly mutator: ProviderInstanceRegistryMutator["Service"];
readonly registry: ProviderInstanceRegistryShape;
readonly mutator: ProviderInstanceRegistryMutatorShape;
},
never,
R | Scope.Scope
@@ -433,14 +362,14 @@ export const make = <R>(input: {
const state: RegistryState = { entries, unavailable, changes };
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
const reconcile: ProviderInstanceRegistryMutator["Service"]["reconcile"] = (configMap) =>
const reconcile: ProviderInstanceRegistryMutatorShape["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 = ProviderInstanceRegistry.of({
const registry: ProviderInstanceRegistryShape = {
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
listInstances: Ref.get(entries).pipe(
Effect.map(
@@ -466,9 +395,9 @@ export const make = <R>(input: {
get subscribeChanges() {
return PubSub.subscribe(changes);
},
});
};
const mutator = ProviderInstanceRegistryMutator.of({ reconcile });
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
return { registry, mutator };
});
@@ -480,15 +409,15 @@ export const make = <R>(input: {
* wiring up the settings watcher.
*
* Only exposes the public registry tag — hot-reload consumers should use
* `mutableLayer` (below) or the hydration layer.
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
*/
export const layer = <R>(input: {
export const ProviderInstanceRegistryLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
Layer.effect(
ProviderInstanceRegistry,
make(input).pipe(Effect.map((built) => built.registry)),
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
/**
@@ -497,12 +426,12 @@ export const layer = <R>(input: {
* changes. Tests that exercise the mutator directly can pair this Layer
* with a test-local `ServerSettingsService`.
*/
export const mutableLayer = <R>(input: {
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
Layer.effectContext(
make(input).pipe(
makeProviderInstanceRegistry(input).pipe(
Effect.map(({ registry, mutator }) =>
Context.make(ProviderInstanceRegistry, registry).pipe(
Context.add(ProviderInstanceRegistryMutator, mutator),
@@ -2,7 +2,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
@@ -25,32 +24,31 @@ import {
type ServerSettings as ContractServerSettings,
} from "@t3tools/contracts";
import * as PlatformError from "effect/PlatformError";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import { createModelCapabilities } from "@t3tools/shared/model";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import {
checkCodexProviderStatus,
type CodexAppServerProviderSnapshot,
} from "./Layers/CodexProvider.ts";
import { checkClaudeProviderStatus } from "./Layers/ClaudeProvider.ts";
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
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 "./Layers/ProviderInstanceRegistryHydration.ts";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import * as ServerConfig from "../config.ts";
import * as ServerSettingsModule from "../serverSettings.ts";
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
import {
readProviderStatusCache,
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "./providerStatusCache.ts";
import type { ProviderInstance } from "./ProviderDriver.ts";
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
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";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
@@ -473,7 +471,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
});
describe("ProviderRegistry", () => {
describe("ProviderRegistryLive", () => {
it("treats equal provider snapshots as unchanged", () => {
const providers = [
{
@@ -504,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
},
] as const satisfies ReadonlyArray<ServerProvider>;
assert.strictEqual(ProviderRegistry.haveProvidersChanged(providers, [...providers]), false);
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
});
it("preserves previously discovered provider models when a refresh returns none", () => {
@@ -542,10 +540,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
models: [],
} satisfies ServerProvider;
assert.deepStrictEqual(
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
[...previousProvider.models],
);
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
});
it("fills missing capabilities from the previous provider snapshot", () => {
@@ -592,10 +589,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
],
} satisfies ServerProvider;
assert.deepStrictEqual(
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
[...previousProvider.models],
);
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
});
it.effect("does not run provider probes during layer construction", () =>
@@ -654,10 +650,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(
ProviderRegistry.layer.pipe(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
@@ -722,10 +718,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
models: [],
} satisfies ServerProvider;
const mergedProviders = ProviderRegistry.mergeProviderSnapshots(previousProviders, [
refreshedCursor,
]);
const persistedProviders = ProviderRegistry.selectProvidersByKind(
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
const persistedProviders = selectProvidersByKind(
mergedProviders,
new Set([ProviderDriverKind.make("cursor")]),
);
@@ -811,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(
ProviderRegistry.layer.pipe(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-merged-persist-",
}),
),
@@ -854,105 +848,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
it.effect("only keeps hydrated cache state while the boot snapshot is still initial", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const fallbackProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-04-29T10:01:00.000Z",
version: null,
models: [],
slashCommands: [],
skills: [],
message: "Codex provider status has not been checked in this session yet.",
} as const satisfies ServerProvider;
const cachedProvider = {
...fallbackProvider,
status: "ready",
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-29T10:00:00.000Z",
version: "1.0.0",
message: "Loaded from the provider status cache.",
} as const satisfies ServerProvider;
const loadProviders = (snapshotState: "initial" | "live") =>
Effect.gen(function* () {
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(fallbackProvider),
isInitialSnapshot: () => snapshotState === "initial",
refresh: Effect.succeed(fallbackProvider),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(
ProviderInstanceRegistry.ProviderInstanceRegistry,
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
},
);
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: `t3-provider-registry-cache-${snapshotState}-`,
});
const configLayer = ServerConfig.layerTest(process.cwd(), baseDir);
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(configLayer));
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: codexInstanceId,
});
yield* writeProviderStatusCache({ filePath, provider: cachedProvider });
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
Layer.fresh(
ProviderRegistry.layer.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(configLayer),
Layer.provideMerge(NodeServices.layer),
),
),
).pipe(Scope.provide(scope));
return yield* ProviderRegistry.ProviderRegistry.pipe(
Effect.flatMap((registry) => registry.getProviders),
Effect.provide(runtimeServices),
);
});
assert.deepStrictEqual(yield* loadProviders("initial"), [cachedProvider]);
assert.deepStrictEqual(yield* loadProviders("live"), [fallbackProvider]);
}),
);
it.effect("returns the cached provider list when a manual refresh fails", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
@@ -1007,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(
ProviderRegistry.layer.pipe(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-refresh-failure-",
}),
),
@@ -1114,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(
ProviderRegistry.layer.pipe(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-sync-failure-",
}),
),
@@ -1207,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 = ProviderRegistry.layer.pipe(
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1224,7 +1119,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
// 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
@@ -1299,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 = ProviderRegistry.layer.pipe(
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1316,7 +1211,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
ChildProcessSpawner.make((command) => {
spawnedCommands.push((command as { readonly command: string }).command);
@@ -1420,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 = ProviderRegistry.layer.pipe(
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1437,7 +1332,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
@@ -1481,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 = ProviderRegistry.layer.pipe(
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
),
Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
@@ -1498,7 +1393,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(OpenCodeRuntime.layer),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
@@ -0,0 +1,698 @@
/**
* 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;
}),
);
@@ -30,7 +30,6 @@ import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -42,27 +41,23 @@ import {
ProviderUnsupportedError,
ProviderValidationError,
type ProviderAdapterError,
} 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";
} 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";
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";
// Several tests build two ProviderService instances in one scope to simulate a
// process restart. Construct a fresh Layer for each build so Layer memoization
// cannot reuse the first service instance.
const makeFreshProviderServiceLayer = (options?: ProviderService.ProviderServiceOptions) =>
Layer.effect(ProviderService.ProviderService, ProviderService.make(options));
} from "../../persistence/Layers/Sqlite.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
@@ -289,11 +284,11 @@ function makeProviderServiceLayer() {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer));
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const layer = it.layer(
Layer.mergeAll(
makeFreshProviderServiceLayer().pipe(
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
@@ -342,11 +337,9 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const providerLayer = Layer.mergeAll(
makeFreshProviderServiceLayer().pipe(
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
@@ -404,10 +397,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeFreshProviderServiceLayer().pipe(
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
@@ -488,10 +479,10 @@ it.effect(
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeFreshProviderServiceLayer().pipe(
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(serverSettingsLayer),
@@ -560,10 +551,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeFreshProviderServiceLayer().pipe(
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
@@ -607,10 +596,8 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const providerLayer = makeFreshProviderServiceLayer({
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const providerLayer = makeProviderServiceLive({
canonicalEventLogger: {
filePath: "memory://provider-canonical-events",
write: (event, threadId) => {
@@ -669,9 +656,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(persistenceLayer),
);
const directoryLayer = ProviderSessionDirectory.layer.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
@@ -682,7 +667,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
});
}).pipe(Effect.provide(directoryLayer));
const providerLayer = makeFreshProviderServiceLayer().pipe(
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
@@ -743,10 +728,10 @@ it.effect(
[ProviderDriverKind.make("codex")]: firstCodex.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
),
@@ -802,10 +787,10 @@ it.effect(
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: secondCodex.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
),
@@ -1086,18 +1071,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
const exit = yield* Effect.exit(provider.listSessions());
assert.equal(Exit.hasDies(exit), true);
const defect = Exit.findDefect(exit);
assert.equal(Result.isSuccess(defect), true);
if (Result.isSuccess(defect)) {
assert.instanceOf(defect.success, ProviderService.ProviderSessionBindingCorrelationError);
assert.deepInclude(defect.success, {
threadId,
sessionProvider: ProviderDriverKind.make("codex"),
bindingProvider: ProviderDriverKind.make("claudeAgent"),
sessionInstanceId: codexInstanceId,
bindingInstanceId: claudeAgentInstanceId,
});
}
yield* directory.upsert({
threadId,
provider: ProviderDriverKind.make("codex"),
@@ -1325,10 +1298,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
const firstRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
),
@@ -1363,10 +1336,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
),
@@ -1431,10 +1404,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
const firstRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
});
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
),
@@ -1464,10 +1437,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
const secondRegistry = makeAdapterRegistryMock({
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
});
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
),
@@ -1810,25 +1783,6 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
const validation = makeProviderServiceLayer();
validation.layer("ProviderServiceLive validation", (it) => {
it.effect("rejects whitespace-only turns without attachments", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
validation.codex.sendTurn.mockClear();
const failure = yield* provider
.sendTurn({
threadId: asThreadId("thread-whitespace-only"),
input: " \n\t ",
attachments: [],
})
.pipe(Effect.flip);
assert.instanceOf(failure, ProviderValidationError);
assert.equal(failure.operation, "ProviderService.sendTurn");
assert.equal(validation.codex.sendTurn.mock.calls.length, 0);
}),
);
it.effect("rejects session starts without an explicit provider instance id", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
@@ -1,15 +1,13 @@
/**
* ProviderService - Cross-provider session and turn service.
* ProviderServiceLive - Cross-provider orchestration layer.
*
* Routes validated transport/API calls to provider adapters through
* `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
* unified provider event stream for subscribers.
*
* It does not implement provider protocol details (adapter concern).
* Uses Effect `Context.Service` for dependency injection and returns typed
* domain errors for validation, session, codex, and checkpoint workflows.
*
* @module ProviderService
* @module ProviderServiceLive
*/
import {
ModelSelection,
@@ -21,13 +19,12 @@ import {
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
ProviderDriverKind,
ProviderInstanceId,
type ProviderInstanceId,
type ProviderDriverKind,
type ProviderRuntimeEvent,
type ProviderSession,
type ProviderTurnStartResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -47,141 +44,17 @@ import {
providerTurnsTotal,
providerTurnMetricAttributes,
withMetrics,
} from "../observability/Metrics.ts";
import {
type ProviderAdapterError,
type ProviderServiceError,
ProviderValidationError,
} from "./Errors.ts";
import type {
ProviderAdapterCapabilities,
ProviderAdapterShape,
} from "./Services/ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
import { type EventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
} from "../../observability/Metrics.ts";
import { type ProviderAdapterError, ProviderValidationError } 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 { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
import {
clearAllMcpProviderSessions,
clearMcpProviderSession,
setMcpProviderSession,
} from "../mcp/McpProviderSession.ts";
import {
issueActiveMcpCredential,
revokeActiveMcpThread,
revokeAllActiveMcpCredentials,
} from "../mcp/McpSessionRegistry.ts";
export class ProviderBindingInstanceIdMissingError extends Schema.TaggedErrorClass<ProviderBindingInstanceIdMissingError>()(
"ProviderBindingInstanceIdMissingError",
{
operation: Schema.String,
provider: Schema.optional(ProviderDriverKind),
},
) {
override get message(): string {
const provider = this.provider === undefined ? "" : ` for provider '${this.provider}'`;
return `Provider binding is missing an instance id${provider} in ${this.operation}.`;
}
}
export class ProviderRuntimeEventCorrelationError extends Schema.TaggedErrorClass<ProviderRuntimeEventCorrelationError>()(
"ProviderRuntimeEventCorrelationError",
{
sourceInstanceId: ProviderInstanceId,
sourceProvider: ProviderDriverKind,
eventInstanceId: Schema.optional(ProviderInstanceId),
eventProvider: ProviderDriverKind,
},
) {
override get message(): string {
const eventInstanceId = this.eventInstanceId ?? "unattributed";
return `Provider runtime event correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceProvider}) and emitted instance '${eventInstanceId}' (${this.eventProvider}).`;
}
}
export class ProviderSessionBindingCorrelationError extends Schema.TaggedErrorClass<ProviderSessionBindingCorrelationError>()(
"ProviderSessionBindingCorrelationError",
{
threadId: ThreadId,
sessionProvider: ProviderDriverKind,
bindingProvider: ProviderDriverKind,
sessionInstanceId: ProviderInstanceId,
bindingInstanceId: ProviderInstanceId,
},
) {
override get message(): string {
return `Active provider session and persisted binding disagree for thread '${this.threadId}'.`;
}
}
export class ProviderService extends Context.Service<
ProviderService,
{
/** Start a provider session. */
readonly startSession: (
threadId: ThreadId,
input: ProviderSessionStartInput,
) => Effect.Effect<ProviderSession, ProviderServiceError>;
/** Send a turn through the adapter bound to the session. */
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 structured provider 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>;
/** Read routing metadata for a configured provider instance. */
readonly getInstanceInfo: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderAdapterRegistry.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>;
}
>()("t3/provider/ProviderService") {}
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
const isModelSelection = Schema.is(ModelSelection);
/**
@@ -189,15 +62,30 @@ const isModelSelection = Schema.is(ModelSelection);
* from `ProviderEventLoggers`. Production wiring leaves this undefined and
* reads the logger off the tag.
*/
export interface ProviderServiceOptions {
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogger?: EventNdjsonLogger;
}
type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
ProviderService.ProviderService["Service"][Name];
const ProviderRollbackConversationInput = Schema.Struct({
threadId: ThreadId,
numTurns: NonNegativeInt,
});
function toValidationError(
operation: string,
issue: string,
cause?: unknown,
): ProviderValidationError {
return new ProviderValidationError({
operation,
issue,
...(cause !== undefined ? { cause } : {}),
});
}
const decodeInputOrValidationError = <S extends Schema.Top>(input: {
readonly operation: string;
readonly schema: S;
@@ -284,10 +172,11 @@ const dieOnMissingBindingInstanceId = (
if (payload.providerInstanceId !== undefined) {
return payload.providerInstanceId;
}
throw new ProviderBindingInstanceIdMissingError({
operation,
...(payload.provider === undefined ? {} : { provider: payload.provider }),
});
throw new Error(
payload.provider
? `${operation}: provider instance id is required for provider '${payload.provider}'.`
: `${operation}: provider instance id is required.`,
);
};
const correlateRuntimeEventWithInstance = (
@@ -297,23 +186,22 @@ const correlateRuntimeEventWithInstance = (
},
event: ProviderRuntimeEvent,
): ProviderRuntimeEvent => {
if (
event.provider !== source.provider ||
(event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId)
) {
throw new ProviderRuntimeEventCorrelationError({
sourceInstanceId: source.instanceId,
sourceProvider: source.provider,
...(event.providerInstanceId === undefined
? {}
: { eventInstanceId: event.providerInstanceId }),
eventProvider: event.provider,
});
if (event.provider !== source.provider) {
throw new Error(
`ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
);
}
if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
throw new Error(
`ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
);
}
return { ...event, providerInstanceId: source.instanceId };
};
export const make = Effect.fn("ProviderService.make")(function* (options?: ProviderServiceOptions) {
const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
// Options-provided logger wins (test overrides); otherwise we take whatever
@@ -327,14 +215,16 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
Effect.tap((credential) =>
credential ? Effect.sync(() => setMcpProviderSession(credential.config)) : Effect.void,
credential
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
: Effect.void,
),
);
const clearMcpSession = (threadId: ThreadId) =>
revokeActiveMcpThread(threadId).pipe(
Effect.tap(() => Effect.sync(() => clearMcpProviderSession(threadId))),
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
);
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
@@ -358,12 +248,12 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
payload.providerInstanceId !== undefined
? Effect.succeed(payload.providerInstanceId)
: Effect.fail(
new ProviderValidationError({
toValidationError(
operation,
issue: payload.provider
payload.provider
? `Provider instance id is required for provider '${payload.provider}'.`
: "Provider instance id is required.",
}),
),
);
const upsertSessionBinding = (
@@ -498,10 +388,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
}
if (!hasResumeCursor) {
return yield* new ProviderValidationError({
operation: input.operation,
issue: `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
});
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
@@ -521,10 +411,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
.pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
if (resumed.provider !== adapter.provider) {
yield* clearMcpSession(input.binding.threadId);
return yield* new ProviderValidationError({
operation: input.operation,
issue: `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
});
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(
@@ -555,10 +445,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* new ProviderValidationError({
operation: input.operation,
issue: `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
});
return yield* toValidationError(
input.operation,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const instanceId = yield* requireBindingInstanceId(input.operation, binding);
const adapter = yield* registry.getByInstance(instanceId);
@@ -629,7 +519,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
);
});
const startSession: ProviderService["Service"]["startSession"] = Effect.fn("startSession")(
const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.startSession",
@@ -653,10 +543,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
const resolvedProvider = instanceInfo.driverKind;
metricProvider = resolvedProvider;
if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
return yield* new ProviderValidationError({
operation: "ProviderService.startSession",
issue: `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
});
return yield* toValidationError(
"ProviderService.startSession",
`Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
);
}
const input = {
...parsed,
@@ -664,10 +554,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
provider: resolvedProvider,
};
if (!instanceInfo.enabled) {
return yield* new ProviderValidationError({
operation: "ProviderService.startSession",
issue: `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
});
return yield* toValidationError(
"ProviderService.startSession",
`Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
@@ -712,10 +602,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
if (session.provider !== adapter.provider) {
yield* clearMcpSession(threadId);
return yield* new ProviderValidationError({
operation: "ProviderService.startSession",
issue: `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
});
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
const sessionWithInstance = {
...session,
@@ -752,84 +642,82 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
},
);
const sendTurn: ProviderService["Service"]["sendTurn"] = Effect.fn("sendTurn")(
function* (rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input?.trim() && input.attachments.length === 0) {
return yield* new ProviderValidationError({
operation: "ProviderService.sendTurn",
issue: "Either input text or at least one attachment is required",
});
}
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
"provider.interaction_mode": input.interactionMode,
"provider.attachment_count": input.attachments.length,
});
let metricProvider = "unknown";
let metricModel = input.modelSelection?.model;
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
metricModel = input.modelSelection?.model;
yield* Effect.annotateCurrentSpan({
"provider.kind": routed.adapter.provider,
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
providerInstanceId: routed.instanceId,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: yield* nowIso,
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
}).pipe(
withMetrics({
counter: providerTurnsTotal,
timer: providerTurnDuration,
attributes: () =>
providerTurnMetricAttributes({
provider: metricProvider,
model: metricModel,
extra: {
operation: "send",
},
}),
}),
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
},
);
}
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
"provider.interaction_mode": input.interactionMode,
"provider.attachment_count": input.attachments.length,
});
let metricProvider = "unknown";
let metricModel = input.modelSelection?.model;
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
metricModel = input.modelSelection?.model;
yield* Effect.annotateCurrentSpan({
"provider.kind": routed.adapter.provider,
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
providerInstanceId: routed.instanceId,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: yield* nowIso,
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
}).pipe(
withMetrics({
counter: providerTurnsTotal,
timer: providerTurnDuration,
attributes: () =>
providerTurnMetricAttributes({
provider: metricProvider,
model: metricModel,
extra: {
operation: "send",
},
}),
}),
);
});
const interruptTurn: ProviderService["Service"]["interruptTurn"] = Effect.fn("interruptTurn")(
const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.interruptTurn",
@@ -866,45 +754,45 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
},
);
const respondToRequest: ProviderService["Service"]["respondToRequest"] = Effect.fn(
"respondToRequest",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
allowRecovery: true,
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-request",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "approval-response",
}),
}),
);
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-request",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "approval-response",
}),
}),
);
},
);
const respondToUserInput: ProviderService["Service"]["respondToUserInput"] = Effect.fn(
const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
"respondToUserInput",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
@@ -938,7 +826,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
);
});
const stopSession: ProviderService["Service"]["stopSession"] = Effect.fn("stopSession")(
const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopSession",
@@ -986,7 +874,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
},
);
const listSessions: ProviderService["Service"]["listSessions"] = Effect.fn("listSessions")(
const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
function* () {
const currentAdapters = yield* getAdapterEntries;
const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
@@ -1047,18 +935,18 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
"ProviderService.listSessions",
binding,
);
if (
binding.provider !== session.provider ||
overrides.providerInstanceId !== session.providerInstanceId
) {
if (binding.provider !== session.provider) {
return yield* Effect.die(
new ProviderSessionBindingCorrelationError({
threadId: session.threadId,
sessionProvider: session.provider,
bindingProvider: binding.provider,
sessionInstanceId: session.providerInstanceId,
bindingInstanceId: overrides.providerInstanceId,
}),
new Error(
`ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
),
);
}
if (overrides.providerInstanceId !== session.providerInstanceId) {
return yield* Effect.die(
new Error(
`ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
),
);
}
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
@@ -1073,13 +961,13 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
},
);
const getCapabilities: ProviderService["Service"]["getCapabilities"] = (instanceId) =>
const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
const getInstanceInfo: ProviderService["Service"]["getInstanceInfo"] = (instanceId) =>
const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
registry.getInstanceInfo(instanceId);
const rollbackConversation: ProviderService["Service"]["rollbackConversation"] = Effect.fn(
const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
"rollbackConversation",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
@@ -1142,8 +1030,8 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
),
).pipe(Effect.asVoid);
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
yield* revokeAllActiveMcpCredentials();
clearAllMcpProviderSessions();
yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
McpProviderSession.clearAllMcpProviderSessions();
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
yield* Effect.forEach(bindings, (binding) =>
Effect.gen(function* () {
@@ -1172,11 +1060,15 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
yield* Effect.addFinalizer(() =>
runStopAll().pipe(
Effect.catchCause((cause) => Effect.logWarning("failed to stop provider service", { cause })),
Effect.catchCause((cause) =>
Effect.logWarning("failed to stop provider service", {
errorTag: causeErrorTag(cause),
}),
),
),
);
return ProviderService.of({
return {
startSession,
sendTurn,
interruptTurn,
@@ -1190,10 +1082,17 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderService["Service"]["streamEvents"] {
get streamEvents(): ProviderServiceMethod<"streamEvents"> {
return Stream.fromPubSub(runtimeEventPubSub);
},
});
} satisfies ProviderService.ProviderService["Service"];
});
export const layer = Layer.effect(ProviderService, make());
export const ProviderServiceLive = Layer.effect(
ProviderService.ProviderService,
makeProviderService(),
);
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
}
@@ -15,16 +15,16 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import { isProviderSessionNotFoundError } from "./Errors.ts";
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
} from "../../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
return Layer.mergeAll(
runtimeRepositoryLayer,
ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer)),
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
NodeServices.layer,
);
}
@@ -32,7 +32,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.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const initialThreadId = ThreadId.make("thread-1");
@@ -77,20 +77,9 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
assert.deepEqual(threadIds, [nextThreadId]);
}));
it("reports a missing provider binding as a domain not-found error", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const threadId = ThreadId.make("thread-missing");
const error = yield* directory.getProvider(threadId).pipe(Effect.flip);
assert(isProviderSessionNotFoundError(error));
assert.equal(error.threadId, threadId);
}));
it("persists runtime fields and merges payload updates", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const threadId = ThreadId.make("thread-runtime");
@@ -135,7 +124,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
it("lists persisted bindings with metadata in oldest-first order", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const olderThreadId = ThreadId.make("thread-runtime-older");
@@ -209,7 +198,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.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const threadId = ThreadId.make("thread-provider-change");
@@ -247,7 +236,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const threadId = ThreadId.make("thread-restart");
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
yield* directory.upsert({
provider: ProviderDriverKind.make("codex"),
threadId,
@@ -255,7 +244,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}).pipe(Effect.provide(directoryLayer));
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const directory = yield* ProviderSessionDirectory;
const sql = yield* SqlClient.SqlClient;
const provider = yield* directory.getProvider(threadId);
assert.equal(provider, "codex");
@@ -0,0 +1,201 @@
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";
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);
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);
}
@@ -17,13 +17,14 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
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";
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";
const defaultModelSelection = {
instanceId: ProviderInstanceId.make("codex"),
@@ -116,8 +117,7 @@ function makeReadModel(
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
| ProviderSessionReaper.ProviderSessionReaper
| ProviderSessionRuntime.ProviderSessionRuntimeRepository,
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<ProviderService.ProviderService["Service"]["stopSession"]>;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderService.ProviderService["Service"]["stopSession"]>(
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>,
})) as ReturnType<ProviderServiceShape["stopSession"]>,
);
const providerService: ProviderService.ProviderService["Service"] = {
const providerService: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
@@ -178,21 +178,18 @@ describe("ProviderSessionReaper", () => {
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = Layer.effect(
ProviderSessionReaper.ProviderSessionReaper,
ProviderSessionReaper.make({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}),
).pipe(
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, providerService)),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
@@ -260,9 +257,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -312,9 +307,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -363,9 +356,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -414,9 +405,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
await Effect.runPromise(drainFibers);
@@ -502,9 +491,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -587,9 +574,7 @@ describe("ProviderSessionReaper", () => {
}),
);
const reaper = await runtime!.runPromise(
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
);
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
@@ -1,37 +1,31 @@
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 * 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<
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
{
/** Start the background provider session reaper within the provided scope. */
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
>()("t3/provider/ProviderSessionReaper") {}
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperOptions {
export interface ProviderSessionReaperLiveOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
export const make = (options?: ProviderSessionReaperOptions) =>
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService.ProviderService;
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const inactivityThresholdMs = Math.max(
1,
@@ -109,15 +103,19 @@ export const make = (options?: ProviderSessionReaperOptions) =>
}
});
const start: ProviderSessionReaper["Service"]["start"] = () =>
const start: ProviderSessionReaperShape["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))),
),
@@ -129,7 +127,12 @@ export const make = (options?: ProviderSessionReaperOptions) =>
});
});
return ProviderSessionReaper.of({ start });
return {
start,
} satisfies ProviderSessionReaperShape;
});
export const layer = Layer.effect(ProviderSessionReaper, make());
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
@@ -1,167 +0,0 @@
/**
* 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.
* - `listProviders` — legacy kind-keyed routing for default instances
* (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D
* behaviour. New code should not grow additional callers of the kind-keyed
* methods; they exist so the settings UI, WS refresh RPC, and a handful
* of legacy persisted rows can still be routed during the rollout.
*
* Adapter lookups are resolved dynamically through `ProviderInstanceRegistry`.
* Settings-driven hot reload is therefore visible immediately without
* rebuilding this facade.
*
* @module ProviderAdapterRegistry
*/
import {
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 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>;
/** Resolve routing metadata for a specific live provider instance. */
readonly getInstanceInfo: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
/**
* List all live instance ids. Excludes unavailable/shadow instances because
* callers of this method want something they can pass to `getByInstance`.
*/
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
/**
* List provider kinds whose default instance is currently registered.
*
* @deprecated Prefer `listInstances`. Retained for migration-era call sites
* that iterate providers to build UI or metrics.
*/
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
/**
* Change notification stream mirroring
* `ProviderInstanceRegistry.streamChanges`. Emits one `void` tick whenever
* the set of live instances changes. Consumers that fan out
* `adapter.streamEvents` per instance re-pull `listInstances` on each tick
* and fork subscriptions for instances they have not seen yet.
*/
readonly streamChanges: Stream.Stream<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>;
}
>()("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)) {
// Only default instances appear through this legacy view; custom
// instances such as `codex_personal` have no driver-kind identity.
kinds.add(instance.driverKind);
}
}
return Array.from(kinds);
}),
);
return ProviderAdapterRegistry.of({
getByInstance,
getInstanceInfo,
listInstances,
listProviders,
// The facade owns no state; the instance registry already coalesces
// add, remove, and rebuild notifications into a single change channel.
streamChanges: registry.streamChanges,
subscribeChanges: registry.subscribeChanges,
});
});
export const layer = Layer.effect(ProviderAdapterRegistry, make);
@@ -1,769 +0,0 @@
/**
* 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,
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 Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
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 ProviderSnapshotCorrelationError extends Schema.TaggedErrorClass<ProviderSnapshotCorrelationError>()(
"ProviderSnapshotCorrelationError",
{
sourceInstanceId: ProviderInstanceId,
snapshotInstanceId: ProviderInstanceId,
sourceDriver: ProviderDriverKind,
snapshotDriver: ProviderDriverKind,
},
) {
override get message(): string {
return `Provider snapshot correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceDriver}) and emitted instance '${this.snapshotInstanceId}' (${this.snapshotDriver}).`;
}
}
export class ProviderRegistry extends Context.Service<
ProviderRegistry,
{
/**
* Read the latest provider snapshots for every configured instance.
* Multiple snapshots may share the same driver kind and disambiguate via
* `instanceId`.
*/
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh all providers, or the default instance of the specified kind
* when supplied.
*
* Retained for compatibility with legacy call sites such as the WS refresh
* RPC and orchestration metrics.
*
* @deprecated Prefer `refreshInstance` for new call sites.
*/
readonly refresh: (
provider?: ProviderDriverKind,
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh one configured instance. Unknown ids resolve to the current
* cached list, matching the legacy `refresh` behavior so transport layers
* do not have to special-case unknown ids.
*/
readonly refreshInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Resolve maintenance capabilities for one live provider instance,
* falling back to manual-only capabilities when it is unavailable.
*/
readonly getProviderMaintenanceCapabilitiesForInstance: (
instanceId: ProviderInstanceId,
provider: ProviderDriverKind,
) => Effect.Effect<ProviderMaintenanceCapabilities>;
/**
* Apply volatile maintenance-action state to one configured instance. This
* state is never persisted. Today only update actions are projected onto
* `ServerProvider.updateState`; install/auth actions can extend this map
* without adding driver-scoped APIs.
*/
readonly setProviderMaintenanceActionState: (input: {
readonly instanceId: ProviderInstanceId;
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>>;
}
>()("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 || snapshot.driver !== source.driverKind) {
return Effect.die(
new ProviderSnapshotCorrelationError({
sourceInstanceId: source.instanceId,
snapshotInstanceId: snapshot.instanceId,
sourceDriver: source.driverKind,
snapshotDriver: 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,
...(instance.snapshot.isInitialSnapshot === undefined
? {}
: { isInitialSnapshot: instance.snapshot.isInitialSnapshot }),
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 cachedInstanceIds = new Set(cachedProviders.map(snapshotInstanceKey));
const bootInstancesById = new Map(
bootInstances.map((instance) => [instance.instanceId, instance] as const),
);
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,
([instanceId, instance]) =>
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
// Keep hydrated cache state only while the original boot instance
// still exposes its explicitly-marked initial snapshot. Comparing
// snapshot values is insufficient: the first probe may have
// completed before registry construction, making the boot-time
// fallback a real live result that must replace stale disk state.
if (
cachedInstanceIds.has(instanceId) &&
bootInstancesById.get(instanceId) === instance &&
source.isInitialSnapshot?.(provider) === true
) {
return;
}
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,
});
}),
);
// Cached snapshots are already in `providersRef`; only seed instances
// without cache entries so pending fallbacks cannot overwrite hydrated
// status while the managed provider's first probe is still running.
yield* upsertProviders(
fallbackProviders.filter((provider) => !cachedInstanceIds.has(snapshotInstanceKey(provider))),
{ publish: false },
);
// 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,
});
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);
@@ -1,283 +0,0 @@
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,
ProviderSessionNotFoundError,
ProviderValidationError,
} from "./Errors.ts";
import * as ProviderSessionRuntime from "../persistence/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
| ProviderSessionNotFoundError;
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>,
ProviderSessionDirectoryPersistenceError
>;
readonly listThreadIds: () => Effect.Effect<
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
readonly listBindings: () => Effect.Effect<
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
ProviderSessionDirectoryPersistenceError
>;
}
>()("t3/provider/ProviderSessionDirectory") {}
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
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: rows written before provider instances had a
// nullable id. Promote them here so runtime routing never has to
// infer an instance from its driver kind.
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
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(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.getBinding:getByThreadId",
detail: "Failed to read the persisted provider session binding.",
cause,
}),
),
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(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.upsert:getByThreadId",
detail: "Failed to read the existing provider session binding before upsert.",
cause,
}),
),
);
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(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.upsert:upsert",
detail: "Failed to persist the provider session binding.",
cause,
}),
),
);
});
const getProvider: ProviderSessionDirectory["Service"]["getProvider"] = (threadId) =>
getBinding(threadId).pipe(
Effect.flatMap(
Option.match({
onSome: (value) => Effect.succeed(value.provider),
onNone: () =>
Effect.fail(
new ProviderSessionNotFoundError({
threadId,
}),
),
}),
),
);
const listThreadIds: ProviderSessionDirectory["Service"]["listThreadIds"] = () =>
repository.list().pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.listThreadIds:list",
detail: "Failed to list persisted provider session bindings.",
cause,
}),
),
Effect.map((rows) => rows.map((row) => row.threadId)),
);
const listBindings: ProviderSessionDirectory["Service"]["listBindings"] = () =>
repository.list().pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.listBindings:list",
detail: "Failed to list persisted provider session bindings.",
cause,
}),
),
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);
@@ -0,0 +1,100 @@
/**
* 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") {}
@@ -0,0 +1,87 @@
/**
* 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") {}
@@ -0,0 +1,52 @@
/**
* 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") {}
@@ -0,0 +1,81 @@
/**
* 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",
) {}
@@ -0,0 +1,121 @@
/**
* 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";
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",
) {}
@@ -0,0 +1,70 @@
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") {}
@@ -0,0 +1,15 @@
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") {}
@@ -6,15 +6,6 @@ import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts"
export interface ServerProviderShape {
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly getSnapshot: Effect.Effect<ServerProvider>;
/**
* Identifies the driver's unprobed startup snapshot. Registries use this to
* keep a hydrated disk snapshot only until the first live probe completes.
*
* Optional for compatibility with static/test snapshot sources. A source
* that does not expose lifecycle state is treated as live rather than
* allowing a stale cache entry to mask it.
*/
readonly isInitialSnapshot?: (snapshot: ServerProvider) => boolean;
readonly refresh: Effect.Effect<ServerProvider>;
readonly streamChanges: Stream.Stream<ServerProvider>;
}
@@ -12,22 +12,17 @@ describe("AcpAdapterSupport", () => {
});
it("maps ACP request errors to provider adapter request errors", () => {
const cause = new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: "Invalid params",
});
const error = mapAcpToAdapterError(
ProviderDriverKind.make("cursor"),
"thread-1" as never,
"session/prompt",
cause,
new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: "Invalid params",
}),
);
expect(error._tag).toBe("ProviderAdapterRequestError");
expect(error.message).toBe("Provider adapter request failed (cursor) for session/prompt.");
if (error._tag === "ProviderAdapterRequestError") {
expect(error.detail).toBe("ACP request failed.");
expect(error.cause).toBe(cause);
}
expect(error.message).toContain("Invalid params");
});
});
@@ -12,6 +12,7 @@ import {
type ProviderAdapterError,
} from "../Errors.ts";
const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
export function mapAcpToAdapterError(
provider: ProviderDriverKind,
@@ -26,10 +27,18 @@ export function mapAcpToAdapterError(
cause: error,
});
}
if (isAcpRequestError(error)) {
return new ProviderAdapterRequestError({
provider,
method,
detail: error.message,
cause: error,
});
}
return new ProviderAdapterRequestError({
provider,
method,
detail: "ACP request failed.",
detail: error.message,
cause: error,
});
}
@@ -12,7 +12,6 @@ export type ProviderSnapshotSource = {
/** Driver implementation kind. */
readonly driverKind: ProviderDriverKind;
readonly getSnapshot: ServerProviderShape["getSnapshot"];
readonly isInitialSnapshot?: (snapshot: ServerProvider) => boolean;
readonly refresh: ServerProviderShape["refresh"];
readonly streamChanges: Stream.Stream<ServerProvider>;
};
@@ -153,7 +153,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
isInitialSnapshot: (snapshot) => snapshot === initialSnapshot,
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
@@ -1,101 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
const encoder = new TextEncoder();
function exitedProcess(stdout: string, stderr: string, exitCode: number) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.make(encoder.encode(stdout)),
stderr: Stream.make(encoder.encode(stderr)),
all: Stream.empty,
exitCode: Effect.yieldNow.pipe(
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(exitCode))),
),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
}
const netService = {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(12_345),
findAvailablePort: () => Effect.succeed(12_345),
} satisfies NetService.NetServiceShape;
describe("OpenCodeRuntime", () => {
it.effect("retains SDK status and cause without copying arbitrary response bodies", () => {
const cause = {
response: { status: 401 },
body: { accessToken: "sdk-secret" },
};
return Effect.gen(function* () {
const result = yield* Effect.result(
OpenCodeRuntime.runOpenCodeSdk("session.get", () => Promise.reject(cause)),
);
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.instanceOf(result.failure, OpenCodeRuntime.OpenCodeRuntimeError);
assert.equal(result.failure.operation, "session.get");
assert.equal(result.failure.detail, "OpenCode SDK request failed.");
assert.equal(result.failure.responseStatus, 401);
assert.strictEqual(result.failure.cause, cause);
assert.notInclude(result.failure.detail, "sdk-secret");
assert.isFalse("body" in result.failure);
}
});
});
it.live("records startup output sizes without retaining process streams", () => {
const stdout = "startup output with a credential sdk-secret";
const stderr = "startup failed";
const layer = Layer.mergeAll(
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.succeed(exitedProcess(stdout, stderr, 17))),
),
Layer.succeed(NetService.NetService, netService),
Layer.succeed(HostProcessPlatform, "win32"),
);
return Effect.gen(function* () {
const runtime = yield* OpenCodeRuntime.make;
const result = yield* Effect.result(
Effect.scoped(
runtime.startOpenCodeServerProcess({
binaryPath: "opencode",
port: 12_345,
}),
),
);
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.instanceOf(result.failure, OpenCodeRuntime.OpenCodeRuntimeError);
assert.equal(result.failure.exitCode, 17);
assert.equal(result.failure.argumentCount, 3);
assert.equal(result.failure.stdoutBytes, encoder.encode(stdout).byteLength);
assert.equal(result.failure.stderrBytes, encoder.encode(stderr).byteLength);
assert.isFalse("stdout" in result.failure);
assert.isFalse("stderr" in result.failure);
assert.notInclude(result.failure.detail, "sdk-secret");
}
}).pipe(Effect.provide(layer));
});
});
+133 -159
View File
@@ -11,29 +11,29 @@ import {
type QuestionAnswer,
type QuestionRequest,
} from "@opencode-ai/sdk/v2";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
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";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { collectStreamAsString } from "./providerSnapshot.ts";
const encoder = new TextEncoder();
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
@@ -50,67 +50,35 @@ export interface OpenCodeServerConnection {
readonly external: boolean;
}
export class OpenCodeRuntimeError extends Schema.TaggedErrorClass<OpenCodeRuntimeError>()(
"OpenCodeRuntimeError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
exitCode: Schema.optionalKey(Schema.Number),
argumentCount: Schema.optionalKey(Schema.Number),
timeoutMs: Schema.optionalKey(Schema.Number),
responseStatus: Schema.optionalKey(Schema.Number),
stdoutBytes: Schema.optionalKey(Schema.Number),
stderrBytes: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
return `OpenCode runtime operation ${this.operation} failed.`;
}
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);
}
static fromCause(input: {
readonly operation: string;
readonly detail: string;
readonly cause: unknown;
readonly argumentCount?: number;
}): OpenCodeRuntimeError {
if (isOpenCodeRuntimeError(input.cause)) {
return input.cause;
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
if (cause && typeof cause === "object") {
// SDK v2 throws { response, request, error? } shapes — extract what's useful
const anyCause = cause as Record<string, unknown>;
const status = (anyCause.response as { status?: number } | undefined)?.status;
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
if (encodedBody) {
return `status=${status ?? "?"} body=${encodedBody}`;
}
const responseStatus = openCodeResponseStatus(input.cause);
return new OpenCodeRuntimeError({
operation: input.operation,
detail: input.detail,
cause: input.cause,
...(input.argumentCount === undefined ? {} : { argumentCount: input.argumentCount }),
...(responseStatus === undefined ? {} : { responseStatus }),
});
}
static detailFromCause(cause: unknown): string {
return isOpenCodeRuntimeError(cause) ? cause.detail : "OpenCode request failed.";
}
}
export const isOpenCodeRuntimeError = Schema.is(OpenCodeRuntimeError);
function openCodeResponseStatus(cause: unknown): number | undefined {
if (isOpenCodeRuntimeError(cause)) {
return cause.responseStatus;
}
if (typeof cause !== "object" || cause === null) {
return undefined;
}
const response = (cause as Readonly<Record<string, unknown>>).response;
if (typeof response !== "object" || response === null) {
return undefined;
}
const status = (response as Readonly<Record<string, unknown>>).status;
return typeof status === "number" && Number.isInteger(status) ? status : undefined;
}
function utf8ByteLength(value: string): number {
return encoder.encode(value).byteLength;
return String(cause);
}
export const runOpenCodeSdk = <A>(
@@ -120,11 +88,7 @@ export const runOpenCodeSdk = <A>(
Effect.tryPromise({
try: fn,
catch: (cause) =>
OpenCodeRuntimeError.fromCause({
operation,
detail: "OpenCode SDK request failed.",
cause,
}),
new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
}).pipe(Effect.withSpan(`opencode.${operation}`));
export interface OpenCodeCommandResult {
@@ -143,50 +107,47 @@ export interface ParsedOpenCodeModelSlug {
readonly modelID: string;
}
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") {}
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>;
}
function parseServerUrlFromOutput(output: string): string | null {
for (const line of output.split("\n")) {
@@ -304,14 +265,24 @@ export function toOpenCodeQuestionAnswers(
});
}
export const make = Effect.gen(function* () {
function ensureRuntimeError(
operation: OpenCodeRuntimeError["operation"],
detail: string,
cause: unknown,
): OpenCodeRuntimeError {
return OpenCodeRuntimeError.is(cause)
? cause
: new OpenCodeRuntimeError({ operation, detail, cause });
}
const makeOpenCodeRuntime = 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: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
Effect.gen(function* () {
const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
const child = yield* spawner.spawn(
@@ -328,8 +299,7 @@ export const make = Effect.gen(function* () {
if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
return yield* new OpenCodeRuntimeError({
operation: "runOpenCodeCommand",
detail: "OpenCode executable was not found.",
argumentCount: input.args.length,
detail: `spawn ${input.binaryPath} ENOENT`,
});
}
return {
@@ -340,18 +310,15 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.scoped,
Effect.mapError((cause) =>
OpenCodeRuntimeError.fromCause({
operation: "runOpenCodeCommand",
detail: "Failed to execute OpenCode command.",
ensureRuntimeError(
"runOpenCodeCommand",
`Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
cause,
argumentCount: input.args.length,
}),
),
),
);
const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (
input,
) =>
const startOpenCodeServerProcess: OpenCodeRuntimeShape["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
@@ -362,12 +329,13 @@ export const make = Effect.gen(function* () {
const port =
input.port ??
(yield* netService.findAvailablePort(0).pipe(
Effect.mapError((cause) =>
OpenCodeRuntimeError.fromCause({
operation: "startOpenCodeServerProcess",
detail: "Failed to find an available OpenCode server port.",
cause,
}),
Effect.mapError(
(cause) =>
new OpenCodeRuntimeError({
operation: "startOpenCodeServerProcess",
detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
cause,
}),
),
));
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
@@ -388,13 +356,13 @@ export const make = Effect.gen(function* () {
)
.pipe(
Effect.provideService(Scope.Scope, runtimeScope),
Effect.mapError((cause) =>
OpenCodeRuntimeError.fromCause({
operation: "startOpenCodeServerProcess",
detail: "Failed to spawn OpenCode server process.",
cause,
argumentCount: args.length,
}),
Effect.mapError(
(cause) =>
new OpenCodeRuntimeError({
operation: "startOpenCodeServerProcess",
detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
cause,
}),
),
);
@@ -454,11 +422,14 @@ export const make = Effect.gen(function* () {
readyDeferred,
new OpenCodeRuntimeError({
operation: "startOpenCodeServerProcess",
detail: "OpenCode server exited before startup completed.",
exitCode,
argumentCount: args.length,
stdoutBytes: utf8ByteLength(stdout),
stderrBytes: utf8ByteLength(stderr),
detail: [
`OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
]
.filter(Boolean)
.join("\n\n"),
cause: { exitCode, stdout, stderr },
}),
).pipe(Effect.ignore);
}),
@@ -480,11 +451,11 @@ export const make = Effect.gen(function* () {
if (Exit.isFailure(readyExit)) {
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
const squashed = Cause.squash(readyExit.cause);
return yield* OpenCodeRuntimeError.fromCause({
operation: "startOpenCodeServerProcess",
detail: "Failed while waiting for OpenCode server startup.",
cause: squashed,
});
return yield* ensureRuntimeError(
"startOpenCodeServerProcess",
`Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
squashed,
);
}
const readyOption = readyExit.value;
@@ -492,8 +463,7 @@ export const make = Effect.gen(function* () {
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
return yield* new OpenCodeRuntimeError({
operation: "startOpenCodeServerProcess",
detail: "Timed out waiting for OpenCode server startup.",
timeoutMs,
detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
});
}
@@ -506,9 +476,7 @@ export const make = Effect.gen(function* () {
} satisfies OpenCodeServerProcess;
});
const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
input,
) => {
const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
const serverUrl = input.serverUrl?.trim();
if (serverUrl) {
// We don't own externally-configured servers — no scope interaction.
@@ -534,7 +502,7 @@ export const make = Effect.gen(function* () {
);
};
const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>
const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
createOpencodeClient({
baseUrl: input.baseUrl,
directory: input.directory,
@@ -569,18 +537,24 @@ export const make = Effect.gen(function* () {
Effect.map((result) => result.data ?? []),
);
const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) =>
const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
Effect.map(([providerList, agents]) => ({ providerList, agents })),
);
return OpenCodeRuntime.of({
return {
startOpenCodeServerProcess,
connectToOpenCodeServer,
runOpenCodeCommand,
createOpenCodeSdkClient,
loadOpenCodeInventory,
});
} satisfies OpenCodeRuntimeShape;
});
export const layer = Layer.effect(OpenCodeRuntime, make).pipe(Layer.provide(NetService.layer));
export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
"t3/provider/opencodeRuntime",
) {}
export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
Layer.provide(NetService.layer),
);
@@ -357,9 +357,7 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
const env = options?.env ?? (yield* readCommandLookupEnv);
const resolvedCommandPath =
(yield* resolveCommandPath(binaryPath, { env }).pipe(
Effect.catchTags({
CommandResolutionError: () => Effect.succeed(null),
}),
Effect.catchTag("CommandResolutionError", () => Effect.succeed(null)),
)) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
if (!resolvedCommandPath) {
return resolver.resolve(options);
@@ -15,11 +15,10 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
import {
makeProviderMaintenanceCapabilities,
@@ -178,7 +177,7 @@ function makeRegistry(
);
});
const registry: ProviderRegistry.ProviderRegistry["Service"] = {
const registry: ProviderRegistryShape = {
getProviders: Ref.get(providersRef),
refresh: () => Ref.get(providersRef),
refreshInstance: () => Ref.get(providersRef),
@@ -195,13 +194,13 @@ function makeRegistry(
});
}
const makeTestRunner = (registry: ProviderRegistry.ProviderRegistry["Service"]) =>
const makeTestRunner = (registry: ProviderRegistryShape) =>
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
Effect.provide(
ProviderMaintenanceRunner.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(ProviderRegistry.ProviderRegistry, registry),
Layer.succeed(ProviderRegistry, registry),
Layer.succeed(ProviderVersionCache, new Map()),
),
),
@@ -461,10 +460,6 @@ describe("providerMaintenanceRunner", () => {
assert.strictEqual(isServerProviderUpdateError(error), true);
if (isServerProviderUpdateError(error)) {
assert.include(error.reason, "already running");
assert.strictEqual(isServerProviderUpdateError(error.cause), true);
if (isServerProviderUpdateError(error.cause)) {
assert.strictEqual(error.cause.provider, "unknown");
}
}
}
@@ -9,19 +9,18 @@ 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";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ProviderRegistry from "./ProviderRegistry.ts";
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
@@ -40,84 +39,26 @@ 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,
{
readonly updateProvider: (
target:
| ProviderDriverKind
| {
readonly provider: ProviderDriverKind;
readonly instanceId?: ProviderInstanceId | undefined;
},
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
}
ProviderMaintenanceRunnerShape
>()("t3/provider/providerMaintenanceRunner") {}
const platformFailureFields = {
failureTag: Schema.NullOr(Schema.String),
failureModule: Schema.String,
failureMethod: Schema.String,
failureDescription: Schema.NullOr(Schema.String),
failurePathOrDescriptor: Schema.NullOr(Schema.Union([Schema.String, Schema.Number])),
} as const;
interface PlatformFailureAttributes {
readonly failureTag: string | null;
readonly failureModule: string;
readonly failureMethod: string;
readonly failureDescription: string | null;
readonly failurePathOrDescriptor: string | number | null;
}
function platformFailureAttributes(cause: PlatformError.PlatformError): PlatformFailureAttributes {
const { reason } = cause;
return {
failureTag: reason._tag === "BadArgument" ? null : reason._tag,
failureModule: reason.module,
failureMethod: reason.method,
failureDescription: reason.description || null,
failurePathOrDescriptor:
"pathOrDescriptor" in reason ? (reason.pathOrDescriptor ?? null) : null,
};
}
function formatPlatformFailure(attributes: PlatformFailureAttributes): string {
const tag = attributes.failureTag === null ? "" : `${attributes.failureTag}: `;
const path =
attributes.failurePathOrDescriptor === null
? ""
: ` (${String(attributes.failurePathOrDescriptor)})`;
const description =
attributes.failureDescription === null ? "" : `: ${attributes.failureDescription}`;
return `${tag}${attributes.failureModule}.${attributes.failureMethod}${path}${description}`;
}
class ProviderMaintenanceCommandSpawnError extends Schema.TaggedErrorClass<ProviderMaintenanceCommandSpawnError>()(
"ProviderMaintenanceCommandSpawnError",
{
command: Schema.String,
...platformFailureFields,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to run update command ${this.command}: ${formatPlatformFailure(this)}`;
}
}
class ProviderMaintenanceCommandCollectError extends Schema.TaggedErrorClass<ProviderMaintenanceCommandCollectError>()(
"ProviderMaintenanceCommandCollectError",
{
command: Schema.String,
...platformFailureFields,
cause: Schema.Defect(),
},
) {
override get message(): string {
return formatPlatformFailure(this);
}
}
class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
interface VerifiedProviderRefresh {
readonly providers: ReadonlyArray<ServerProvider>;
@@ -139,9 +80,8 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
.pipe(
Effect.mapError(
(cause) =>
new ProviderMaintenanceCommandSpawnError({
command: input.command,
...platformFailureAttributes(cause),
new ProviderMaintenanceCommandError({
message: `Failed to run update command ${input.command}: ${cause.message}`,
cause,
}),
),
@@ -164,9 +104,8 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
).pipe(
Effect.mapError(
(cause) =>
new ProviderMaintenanceCommandCollectError({
command: input.command,
...platformFailureAttributes(cause),
new ProviderMaintenanceCommandError({
message: cause instanceof Error ? cause.message : "Update command failed to run.",
cause,
}),
),
@@ -252,7 +191,7 @@ function makeUpdateState(input: {
}
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerRegistry = yield* ProviderRegistry;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
@@ -326,7 +265,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
Effect.catchCause((cause) =>
Effect.logWarning("Provider post-update version verification failed", {
provider,
cause,
cause: Cause.pretty(cause),
}).pipe(
Effect.as<VerifiedProviderRefresh>({
providers,
@@ -338,7 +277,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
}),
);
const updateProvider: ProviderMaintenanceRunner["Service"]["updateProvider"] = Effect.fn(
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
"ProviderMaintenanceRunner.updateProvider",
)(function* (target) {
const provider = typeof target === "string" ? target : target.provider;
@@ -465,7 +404,6 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
? new ServerProviderUpdateError({
provider,
reason: error.reason,
cause: error,
})
: error,
),
@@ -1,5 +1,5 @@
/**
* Test helpers for constructing a `ProviderAdapterRegistry["Service"]` mock from a
* Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a
* kind-keyed adapter map.
*
* Tests historically assembled a `registry` object with only `getByProvider`
@@ -26,21 +26,19 @@ import * as Stream from "effect/Stream";
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts";
export type KindAdapterMap = Partial<
Record<ProviderDriverKind, ProviderAdapterShape<ProviderAdapterError>>
>;
/**
* Build a `ProviderAdapterRegistry["Service"]` from a kind-keyed adapter map.
* Build a `ProviderAdapterRegistryShape` 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,
): ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] => {
export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => {
const byInstanceId = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
for (const [kind, adapter] of Object.entries(adapters)) {
if (!adapter) continue;
@@ -48,17 +46,16 @@ export const makeAdapterRegistryMock = (
byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter);
}
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),
}),
);
};
const getByInstance: ProviderAdapterRegistryShape["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 * as ProviderRegistry from "../ProviderRegistry.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/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> = [],
): ProviderRegistry.ProviderRegistry["Service"] => ({
): ProviderRegistryShape => ({
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.ProviderRegistry, makeProviderRegistryMock(providers));
Layer.succeed(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/ProviderRegistry.ts";
import * as ProviderRegistry from "./provider/Services/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 * as ProviderSessionDirectory from "./provider/ProviderSessionDirectory.ts";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.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 { 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 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 * as ProviderRegistry from "./provider/ProviderRegistry.ts";
import { ProviderRegistryLive } from "./provider/Layers/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 = ProviderSessionDirectory.layer.pipe(
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
// `ProviderAdapterRegistry.layer` is a facade that resolves kind → adapter
// `ProviderAdapterRegistryLive` is now 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()`; `ProviderEventLoggers.layer` owns the shared native/canonical
// `create()`; `ProviderEventLoggersLive` 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 = ProviderService.layer.pipe(
Layer.provide(ProviderAdapterRegistry.layer),
const ProviderLayerLive = ProviderServiceLive.pipe(
Layer.provide(ProviderAdapterRegistryLive),
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
);
@@ -278,7 +278,7 @@ const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
),
);
const ProviderRuntimeLayerLive = ProviderSessionReaper.layer.pipe(
const ProviderRuntimeLayerLive = ProviderSessionReaperLive.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(ProviderRegistry.layer),
Layer.provideMerge(ProviderRegistryLive),
// 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.layer),
Layer.provideMerge(ProviderEventLoggers.ProviderEventLoggersLive),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// The old provider registry Layer pulled `OpenCodeRuntime.layer` in for itself, but
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` 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.layer),
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
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/ProviderSessionReaper.ts";
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
import {
formatHeadlessServeOutput,
formatHostForUrl,
@@ -4,9 +4,8 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -346,63 +345,11 @@ describe("AzureDevOpsCli.layer", () => {
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.operation, "execute");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.argumentCount, 2);
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
}).pipe(Effect.provide(layer)),
);
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
Effect.gen(function* () {
const cwd = "/missing/repo";
const platformCause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
syscall: "chdir",
pathOrDescriptor: cwd,
});
const cause = new VcsProcessSpawnError({
operation: "AzureDevOpsCli.execute",
command: "az",
cwd,
argumentCount: 2,
cause: platformCause,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.cwd, cwd);
assert.strictEqual(error.cause, cause);
}).pipe(Effect.provide(layer)),
);
it.effect("keeps invalid pull request output diagnostics structured", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.outputLength, 8);
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
assert.exists(error.cause);
assert.strictEqual(
error.message,
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
});
+83 -166
View File
@@ -1,11 +1,9 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
@@ -21,61 +19,16 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const azureDevOpsCommandErrorFields = {
operation: Schema.Literal("execute"),
command: Schema.Literal("az"),
cwd: Schema.String,
argumentCount: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
"AzureDevOpsCliUnavailableError",
azureDevOpsCommandErrorFields,
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
"AzureDevOpsCliError",
{
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
get detail(): string {
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
"AzureDevOpsCliAuthenticationError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
"AzureDevOpsPullRequestNotFoundError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
"AzureDevOpsCommandFailedError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI command failed.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -85,109 +38,53 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azure
readonly operation: "execute";
readonly command: "az";
readonly cwd: string;
readonly argumentCount: number;
},
cause: VcsError,
error: VcsError | unknown,
): AzureDevOpsCliError {
const fields = { ...context, cause };
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: az") || lower.includes("enoent")) {
return new AzureDevOpsCliError({
...context,
detail:
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
cause: error,
});
}
if (
cause._tag === "VcsProcessSpawnError" &&
cause.cause instanceof PlatformError.PlatformError &&
cause.cause.reason._tag === "NotFound" &&
cause.cause.reason.pathOrDescriptor !== context.cwd &&
cause.cause.reason.syscall !== "chdir"
lower.includes("az devops login") ||
lower.includes("please run az login") ||
lower.includes("not logged in") ||
lower.includes("authentication failed") ||
lower.includes("unauthorized")
) {
return new AzureDevOpsCliUnavailableError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
cause: error,
});
}
if (cause._tag === "VcsProcessExitError") {
if (cause.failureKind === "authentication") {
return new AzureDevOpsCliAuthenticationError(fields);
}
if (cause.failureKind === "not-found") {
return new AzureDevOpsPullRequestNotFoundError(fields);
}
if (
lower.includes("pull request") &&
(lower.includes("not found") || lower.includes("does not exist"))
) {
return new AzureDevOpsCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new AzureDevOpsCommandFailedError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI command failed.",
cause: error,
});
}
}
const azureDevOpsDecodeErrorFields = {
command: Schema.Literal("az"),
cwd: Schema.String,
outputLength: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
"AzureDevOpsPullRequestListDecodeError",
{
operation: Schema.Literal("listPullRequests"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid PR list JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
"AzureDevOpsPullRequestDecodeError",
{
operation: Schema.Literal("getPullRequest"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid pull request JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
"getRepositoryCloneUrls",
"getDefaultBranch",
"createRepository",
]);
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
"AzureDevOpsRepositoryDecodeError",
{
operation: AzureDevOpsRepositoryDecodeOperation,
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid repository JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const AzureDevOpsCliError = Schema.Union([
AzureDevOpsCliUnavailableError,
AzureDevOpsCliAuthenticationError,
AzureDevOpsPullRequestNotFoundError,
AzureDevOpsCommandFailedError,
AzureDevOpsPullRequestListDecodeError,
AzureDevOpsPullRequestDecodeError,
AzureDevOpsRepositoryDecodeError,
]);
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
export interface AzureDevOpsRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
@@ -249,6 +146,17 @@ export class AzureDevOpsCli extends Context.Service<
}
>()("t3/sourceControl/AzureDevOpsCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
@@ -317,18 +225,19 @@ function parseRepositorySpecifier(repository: string): {
function decodeAzureDevOpsJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(cause) =>
new AzureDevOpsRepositoryDecodeError({
(error) =>
new AzureDevOpsCliError({
operation,
command: "az",
cwd,
outputLength: raw.length,
cause,
detail: invalidDetail,
cause: error,
}),
),
);
@@ -348,13 +257,8 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError((error) =>
AzureDevOpsCommandFailedError.fromVcsError(
{
operation: "execute",
command: "az",
cwd: input.cwd,
argumentCount: input.args.length,
},
AzureDevOpsCliError.fromVcsError(
{ operation: "execute", command: "az", cwd: input.cwd },
error,
),
),
@@ -393,11 +297,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestListDecodeError({
new AzureDevOpsCliError({
operation: "listPullRequests",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -427,11 +331,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestDecodeError({
new AzureDevOpsCliError({
operation: "getPullRequest",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -453,6 +357,7 @@ export const make = Effect.gen(function* () {
raw,
RawAzureDevOpsRepositorySchema,
"getRepositoryCloneUrls",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
@@ -478,7 +383,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"createRepository",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
@@ -510,7 +421,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getDefaultBranch",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
),
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
it.effect("adds change-request context while retaining Azure CLI causes", () =>
Effect.gen(function* () {
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
operation: "execute",
command: "az",
cwd: "/repo",
argumentCount: 2,
detail: "Azure DevOps CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
@@ -544,61 +544,6 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}).pipe(Effect.provide(layer));
});
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
const responseBody = '{"error":{"message":"credential=secret-value"}}';
const { layer } = makeLayer({
response: () => new Response(responseBody, { status: 403 }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 403);
assert.strictEqual(error.responseBodyLength, responseBody.length);
assert.notProperty(error, "responseBody");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
);
assert.notInclude(error.message, "secret-value");
}).pipe(Effect.provide(layer));
});
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
const cause = new Error("response stream failed");
const { layer } = makeLayer({
response: () =>
new Response(
new ReadableStream<Uint8Array>({
start: (controller) => controller.error(cause),
}),
{ status: 502 },
),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.getPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 502);
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
assert.strictEqual(error.cause.cause, cause);
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
);
}).pipe(Effect.provide(layer));
});
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
const { git, layer } = makeLayer({
response: () =>
@@ -685,9 +630,8 @@ it.effect("preserves Git checkout failures without deriving the domain message f
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.reference, "42");
assert.strictEqual(error.operation, "checkoutPullRequest");
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
+41 -176
View File
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
@@ -37,156 +36,20 @@ const BitbucketApiEnvConfig = Config.all({
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});
const BitbucketApiOperation = Schema.Literals([
"resolveRepository",
"getRepository",
"getBranchingModel",
"getPullRequest",
"listPullRequests",
"createRepository",
"createPullRequest",
"probeAuth",
"checkoutPullRequest",
]);
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
"BitbucketRepositoryLocatorError",
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
"BitbucketApiError",
{
repository: Schema.String,
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
}
}
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
"BitbucketRequestError",
{
operation: BitbucketApiOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
}
}
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
"BitbucketResponseError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
responseBodyLength: NonNegativeInt,
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
"BitbucketResponseBodyReadError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
"BitbucketResponseDecodeError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
}
}
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
"BitbucketRepositoryVcsResolveError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
"BitbucketRepositoryRemotesListError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
"BitbucketRepositoryRemoteNotFoundError",
{
cwd: Schema.String,
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
}
}
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
"BitbucketPullRequestBodyReadError",
{
cwd: Schema.String,
bodyFile: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
}
}
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
"BitbucketCheckoutError",
{
cwd: Schema.String,
reference: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
}
}
export const BitbucketApiError = Schema.Union([
BitbucketRepositoryLocatorError,
BitbucketRequestError,
BitbucketResponseError,
BitbucketResponseBodyReadError,
BitbucketResponseDecodeError,
BitbucketRepositoryVcsResolveError,
BitbucketRepositoryRemotesListError,
BitbucketRepositoryRemoteNotFoundError,
BitbucketPullRequestBodyReadError,
BitbucketCheckoutError,
]);
export type BitbucketApiError = typeof BitbucketApiError.Type;
export const isBitbucketApiError = Schema.is(BitbucketApiError);
const isBitbucketApiError = Schema.is(BitbucketApiError);
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
@@ -346,14 +209,16 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
}
function requireRepositoryLocator(
operation: string,
repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
const locator = parseBitbucketRepositorySlug(repository);
return locator
? Effect.succeed(locator)
: Effect.fail(
new BitbucketRepositoryLocatorError({
repository,
new BitbucketApiError({
operation,
detail: "Bitbucket repositories must be specified as workspace/repository.",
}),
);
}
@@ -474,24 +339,20 @@ function authFromConfig(
}
function responseError(
operation: BitbucketApiOperation,
operation: string,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseBodyReadError({
operation,
status: response.status,
cause,
}),
),
Effect.orElseSucceed(() => ""),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketResponseError({
new BitbucketApiError({
operation,
status: response.status,
responseBodyLength: body.length,
detail:
body.trim().length > 0
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
: `Bitbucket returned HTTP ${response.status}.`,
}),
),
),
@@ -518,7 +379,7 @@ export const make = Effect.gen(function* () {
};
const decodeResponse = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
schema: S,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
@@ -527,9 +388,9 @@ export const make = Effect.gen(function* () {
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseDecodeError({
new BitbucketApiError({
operation,
status: success.status,
detail: "Bitbucket returned invalid JSON for the requested resource.",
cause,
}),
),
@@ -538,15 +399,16 @@ export const make = Effect.gen(function* () {
})(response);
const executeJson = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
Effect.mapError(
(cause) =>
new BitbucketRequestError({
new BitbucketApiError({
operation,
detail: "Failed to send the Bitbucket request.",
cause,
}),
),
@@ -571,8 +433,9 @@ export const make = Effect.gen(function* () {
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryVcsResolveError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
cause,
}),
),
@@ -580,8 +443,9 @@ export const make = Effect.gen(function* () {
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryRemotesListError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to list remotes for ${input.cwd}.`,
cause,
}),
),
@@ -593,8 +457,9 @@ export const make = Effect.gen(function* () {
if (parsed) return parsed;
}
return yield* new BitbucketRepositoryRemoteNotFoundError({
cwd: input.cwd,
return yield* new BitbucketApiError({
operation: "resolveRepository",
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
});
});
@@ -735,7 +600,7 @@ export const make = Effect.gen(function* () {
getRepositoryCloneUrls: (input) =>
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
createRepository: (input) =>
requireRepositoryLocator(input.repository).pipe(
requireRepositoryLocator("createRepository", input.repository).pipe(
Effect.flatMap((repository) =>
executeJson(
"createRepository",
@@ -760,9 +625,9 @@ export const make = Effect.gen(function* () {
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
Effect.mapError(
(cause) =>
new BitbucketPullRequestBodyReadError({
cwd: input.cwd,
bodyFile: input.bodyFile,
new BitbucketApiError({
operation: "createPullRequest",
detail: `Failed to read pull request body file ${input.bodyFile}.`,
cause,
}),
),
@@ -878,9 +743,9 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) =>
isBitbucketApiError(cause)
? cause
: new BitbucketCheckoutError({
cwd: input.cwd,
reference: input.reference,
: new BitbucketApiError({
operation: "checkoutPullRequest",
detail: "Failed to check out the Bitbucket pull request.",
cause,
}),
),
@@ -53,10 +53,11 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
it.effect("adds repository context while retaining Bitbucket API causes", () =>
Effect.gen(function* () {
const upstreamCause = new Error("raw upstream failure");
const cause = new BitbucketApi.BitbucketRequestError({
const cause = new BitbucketApi.BitbucketApiError({
operation: "getRepository",
cause: upstreamCause,
detail: "upstream detail that should remain in the cause",
status: 503,
cause: new Error("raw upstream failure"),
});
const provider = yield* makeProvider({
getRepositoryCloneUrls: () => Effect.fail(cause),
@@ -85,7 +86,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
},
);
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(upstreamCause.message), false);
assert.equal(error.message.includes(cause.detail), false);
}),
);
@@ -1,9 +1,8 @@
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
@@ -31,27 +30,6 @@ afterEach(() => {
});
describe("GitHubCli.layer", () => {
it("does not classify a missing cwd as an unavailable gh executable", () => {
const context = { command: "gh", cwd: "/repo" } as const;
const missingCwd = new VcsProcessSpawnError({
operation: "GitHubCli.execute",
command: "gh",
cwd: context.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "access",
pathOrDescriptor: context.cwd,
}),
});
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
assert.equal(commandFailure._tag, "GitHubCliCommandError");
assert.strictEqual(commandFailure.cause, missingCwd);
assert.notProperty(commandFailure, "operation");
});
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
@@ -296,7 +274,6 @@ describe("GitHubCli.layer", () => {
command: "gh pr view",
cwd: "/repo",
exitCode: 1,
failureKind: "not-found",
detail:
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
});
@@ -311,7 +288,6 @@ describe("GitHubCli.layer", () => {
.pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
+106 -166
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -19,163 +18,67 @@ import {
const DEFAULT_TIMEOUT_MS = 30_000;
const gitHubCliFailureFields = {
command: Schema.Literal("gh"),
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
"GitHubCliUnavailableError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI (`gh`) is required but not available on PATH.";
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
"GitHubCliAuthenticationError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "gh";
readonly cwd: string;
},
error: VcsError | unknown,
): GitHubCliError {
const lower = errorText(error).toLowerCase();
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
"GitHubCliCommandError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI command failed.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
const gitHubCliDecodeFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
"GitHubPullRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid PR list JSON.";
}
override get message(): string {
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
}
}
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
"GitHubChangeRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid change request JSON.";
}
override get message(): string {
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
}
}
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
"GitHubPullRequestDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid pull request JSON.";
}
override get message(): string {
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
}
}
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
"GitHubRepositoryDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
}
}
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
GitHubChangeRequestListDecodeError,
GitHubPullRequestDecodeError,
GitHubRepositoryDecodeError,
]);
export type GitHubCliError = typeof GitHubCliError.Type;
export const isGitHubCliError = Schema.is(GitHubCliError);
export function fromVcsError(
context: {
readonly command: "gh";
readonly cwd: string;
},
error: VcsError,
): GitHubCliError {
if (
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound" &&
error.cause.reason.module === "ChildProcess" &&
error.cause.reason.method === "spawn"
) {
return new GitHubCliUnavailableError({ ...context, cause: error });
}
if (error._tag === "VcsProcessExitError") {
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
return new GitHubCliError({
...context,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
}
return new GitHubCliCommandError({ ...context, cause: error });
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
...context,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
...context,
detail: "GitHub CLI command failed.",
cause: error,
});
}
}
export interface GitHubPullRequestSummary {
@@ -247,14 +150,22 @@ export class GitHubCli extends Context.Service<
}
>()("t3/sourceControl/GitHubCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
);
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
@@ -303,6 +214,27 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
command: "gh",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -315,7 +247,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
.pipe(
Effect.mapError((error) =>
GitHubCliError.fromVcsError(
{ operation: "execute", command: "gh", cwd: input.cwd },
error,
),
),
);
return GitHubCli.of({
execute,
@@ -343,9 +282,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestListDecodeError({
new GitHubCliError({
operation: "listOpenPullRequests",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -375,9 +316,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestDecodeError({
new GitHubCliError({
operation: "getPullRequest",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -397,15 +340,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitHubRepositoryDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -70,9 +70,11 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
const cause = new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: "/repo",
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -158,17 +158,23 @@ export const make = Effect.gen(function* () {
})),
)
: Effect.fail(
new GitHubCli.GitHubChangeRequestListDecodeError({
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
command: "gh",
cwd: input.cwd,
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError(
(error) =>
Effect.catchTags({
GitHubCliError: (error) =>
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
@@ -180,7 +186,7 @@ export const make = Effect.gen(function* () {
detail: error.detail,
cause: error,
}),
),
}),
);
};
@@ -315,11 +315,10 @@ layer("GitLabCli.layer", (it) => {
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
command: "glab mr view 4888",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 merge request not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
@@ -331,37 +330,11 @@ layer("GitLabCli.layer", (it) => {
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
assert.equal(error.message.includes("Merge request not found"), true);
assert.strictEqual(error.command, "glab");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(cause.detail), false);
}),
);
it.effect("keeps non-merge-request not-found failures generic", () =>
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 project not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
const error = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getRepositoryCloneUrls({
cwd: "/repo",
repository: "missing/project",
});
}).pipe(Effect.flip);
assert.strictEqual(error._tag, "GitLabCliCommandError");
assert.strictEqual(error.cause, cause);
}),
);
});
+122 -270
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Match from "effect/Match";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -22,56 +21,13 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const gitLabCliExecutionErrorContext = {
operation: Schema.Literal("execute"),
command: Schema.Literal("glab"),
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
};
const gitLabCliDecodeErrorContext = {
command: Schema.Literal("glab"),
cwd: Schema.String,
cause: Schema.Defect(),
};
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
"GitLabCliUnavailableError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI (`glab`) is required but not available on PATH.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
"GitLabCliAuthenticationError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
"GitLabMergeRequestNotFoundError",
{
...gitLabCliExecutionErrorContext,
reference: Schema.String,
},
) {
get detail(): string {
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -81,148 +37,52 @@ export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<Git
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
readonly reference: string;
},
error: VcsError,
error: VcsError | unknown,
): GitLabCliError {
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
return new GitLabCliError({
...context,
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
cause: error,
});
}
return GitLabCliCommandError.fromVcsError(
{
operation: context.operation,
command: context.command,
cwd: context.cwd,
},
error,
);
}
}
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("glab auth login") ||
lower.includes("token")
) {
return new GitLabCliError({
...context,
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
cause: error,
});
}
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
"GitLabCliCommandError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI command failed.";
}
if (
lower.includes("merge request not found") ||
lower.includes("not found") ||
lower.includes("404")
) {
return new GitLabCliError({
...context,
detail: "Merge request not found. Check the MR number or URL and try again.",
cause: error,
});
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
},
error: VcsError,
): GitLabCliError {
return Match.valueTags(error, {
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
VcsProcessExitError: (cause) => {
switch (cause.failureKind) {
case "authentication":
return new GitLabCliAuthenticationError({ ...context, cause });
case "not-found":
case "command-failed":
case undefined:
return new GitLabCliCommandError({ ...context, cause });
}
},
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
return new GitLabCliError({
...context,
detail: "GitLab CLI command failed.",
cause: error,
});
}
}
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
"GitLabMergeRequestListDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("listMergeRequests"),
},
) {
get detail(): string {
return "GitLab CLI returned invalid MR list JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
"GitLabMergeRequestDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("getMergeRequest"),
reference: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid merge request JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
"GitLabRepositoryDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
repository: Schema.optional(Schema.String),
},
) {
get detail(): string {
return "GitLab CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
"GitLabNamespaceDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("createRepository"),
namespacePath: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid namespace JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const GitLabCliError = Schema.Union([
GitLabCliUnavailableError,
GitLabCliAuthenticationError,
GitLabMergeRequestNotFoundError,
GitLabCliCommandError,
GitLabMergeRequestListDecodeError,
GitLabMergeRequestDecodeError,
GitLabRepositoryDecodeError,
GitLabNamespaceDecodeError,
]);
export type GitLabCliError = typeof GitLabCliError.Type;
export const isGitLabCliError = Schema.is(GitLabCliError);
export interface GitLabMergeRequestSummary {
readonly number: number;
readonly title: string;
@@ -242,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
readonly sshUrl: string;
}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
export class GitLabCli extends Context.Service<
GitLabCli,
{
@@ -297,6 +168,15 @@ export class GitLabCli extends Context.Service<
}
>()("t3/sourceControl/GitLabCli") {}
function isVcsProcessSpawnError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "VcsProcessSpawnError"
);
}
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
path_with_namespace: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
@@ -312,14 +192,6 @@ const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
);
const decodeGitLabDefaultBranch = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
);
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
@@ -330,6 +202,27 @@ function normalizeRepositoryCloneUrls(
};
}
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitLabCliError({
operation,
command: "glab",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
@@ -390,10 +283,7 @@ function parseRepositoryPath(repository: string): {
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const run = (
input: Parameters<GitLabCli["Service"]["execute"]>[0],
mapError: (error: VcsError) => GitLabCliError,
) =>
const execute: GitLabCli["Service"]["execute"] = (input) =>
process
.run({
operation: "GitLabCli.execute",
@@ -402,32 +292,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError(mapError));
const execute: GitLabCli["Service"]["execute"] = (input) =>
run(input, (error) =>
GitLabCliCommandError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
);
const executeMergeRequest = (input: {
readonly cwd: string;
readonly reference: string;
readonly args: ReadonlyArray<string>;
}) =>
run(input, (error) =>
GitLabMergeRequestNotFoundError.fromVcsError(
{
operation: "execute",
command: "glab",
cwd: input.cwd,
reference: input.reference,
},
error,
),
);
.pipe(
Effect.mapError((error) =>
GitLabCliError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
),
);
return GitLabCli.of({
execute,
@@ -454,10 +326,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestListDecodeError({
new GitLabCliError({
operation: "listMergeRequests",
command: "glab",
cwd: input.cwd,
detail: "GitLab CLI returned invalid MR list JSON.",
cause: decoded.failure,
}),
);
@@ -469,9 +342,8 @@ export const make = Effect.gen(function* () {
),
),
getMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "view", input.reference, "--output", "json"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
@@ -480,11 +352,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestDecodeError({
new GitLabCliError({
operation: "getMergeRequest",
command: "glab",
cwd: input.cwd,
reference: input.reference,
detail: "GitLab CLI returned invalid merge request JSON.",
cause: decoded.failure,
}),
);
@@ -502,17 +374,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getRepositoryCloneUrls",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -526,17 +393,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabNamespace(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabNamespaceDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
namespacePath,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabNamespaceSchema,
"createRepository",
"GitLab CLI returned invalid namespace JSON.",
input.cwd,
),
),
Effect.map((namespace) => namespace.id),
@@ -566,17 +428,12 @@ export const make = Effect.gen(function* () {
),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"createRepository",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -610,24 +467,19 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabDefaultBranch(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getDefaultBranch",
command: "glab",
cwd: input.cwd,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabDefaultBranchSchema,
"getDefaultBranch",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((value) => value.default_branch ?? null),
),
checkoutMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "checkout", input.reference],
}).pipe(Effect.asVoid),
});
@@ -54,10 +54,11 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
it.effect("adds repository context while retaining GitLab CLI causes", () =>
Effect.gen(function* () {
const cause = new GitLabCli.GitLabCliCommandError({
const cause = new GitLabCli.GitLabCliError({
operation: "execute",
command: "glab",
cwd: "/repo",
detail: "GitLab CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -1,4 +1,4 @@
import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Duration from "effect/Duration";
@@ -11,8 +11,8 @@ import { beforeEach, expect } from "vite-plus/test";
import * as ServerConfig from "../config.ts";
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
import * as TextGeneration from "./TextGeneration.ts";
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
@@ -20,11 +20,8 @@ const runtimeMock = {
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
sessionCreateError: undefined as unknown,
sessionResult: undefined as { data?: { id: string } } | undefined,
promptRequestError: undefined as unknown,
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
@@ -32,14 +29,11 @@ const runtimeMock = {
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.sessionCreateError = undefined;
this.state.sessionResult = undefined;
this.state.promptRequestError = undefined;
this.state.promptResult = undefined;
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
@@ -67,20 +61,12 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => {
if (runtimeMock.state.sessionCreateError !== undefined) {
throw runtimeMock.state.sessionCreateError;
}
return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
},
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
if (runtimeMock.state.promptRequestError !== undefined) {
throw runtimeMock.state.promptRequestError;
}
return (
runtimeMock.state.promptResult ?? {
data: {
@@ -98,9 +84,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
);
},
},
}) as unknown as ReturnType<
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
>,
}) as unknown as ReturnType<OpenCodeRuntime.OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
@@ -115,13 +99,6 @@ const DEFAULT_TEST_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
};
const DEFAULT_COMMIT_MESSAGE_INPUT = {
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
@@ -165,7 +142,7 @@ function withOpenCodeTextGeneration<A, E, R>(
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
const textGeneration = yield* makeOpenCodeTextGeneration(settings);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
@@ -244,99 +221,22 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
).pipe(Effect.provide(TestClock.layer())),
);
it.effect("preserves the SDK cause when session creation fails", () =>
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
const sdkCause = new Error("session endpoint unavailable");
runtimeMock.state.sessionCreateError = sdkCause;
runtimeMock.state.promptResult = { data: {} };
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.message).toContain("OpenCode session.create request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
it.effect("reports a missing session payload without manufacturing a cause", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.sessionResult = {};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode session.create returned no session payload.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionPayloadError",
operation: "generateCommitMessage",
cwd: process.cwd(),
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
it.effect("preserves the SDK cause and request context when prompting fails", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
const sdkCause = new Error("prompt endpoint unavailable");
runtimeMock.state.promptRequestError = sdkCause;
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode session.prompt request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [null, { type: "tool" }, { type: "text", text: " " }],
},
};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationEmptyOutputError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
responsePartCount: 3,
textPartCount: 1,
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -389,21 +289,16 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptResponseError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
providerErrorName: "StructuredOutputError",
providerMessage: "Model did not produce structured output",
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -6,7 +6,6 @@ import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import {
NonNegativeInt,
TextGenerationError,
type ChatAttachment,
type ModelSelection,
@@ -34,106 +33,11 @@ import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
const OpenCodeTextGenerationOperation = Schema.Literals([
"generateCommitMessage",
"generatePrContent",
"generateBranchName",
"generateThreadTitle",
]);
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
const openCodeTextGenerationErrorContext = {
operation: OpenCodeTextGenerationOperation,
cwd: Schema.String,
};
export class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(
"OpenCodeTextGenerationSessionRequestError",
{
...openCodeTextGenerationErrorContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;
}
}
export class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(
"OpenCodeTextGenerationSessionPayloadError",
openCodeTextGenerationErrorContext,
) {
override get message(): string {
return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;
}
}
const openCodePromptErrorContext = {
...openCodeTextGenerationErrorContext,
sessionId: Schema.String,
providerId: Schema.String,
modelId: Schema.String,
};
export class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(
"OpenCodeTextGenerationPromptRequestError",
{
...openCodePromptErrorContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;
}
}
export class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(
"OpenCodeTextGenerationPromptResponseError",
{
...openCodePromptErrorContext,
providerErrorName: Schema.optional(Schema.String),
providerMessage: Schema.String,
},
) {
override get message(): string {
const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : "";
return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;
}
}
export class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(
"OpenCodeTextGenerationEmptyOutputError",
{
...openCodePromptErrorContext,
responsePartCount: NonNegativeInt,
textPartCount: NonNegativeInt,
},
) {
override get message(): string {
return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;
}
}
interface OpenCodePromptFailure {
readonly name?: string;
readonly message: string;
}
interface OpenCodeTextPart {
readonly type: "text";
readonly text: string;
}
function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {
function getOpenCodePromptErrorMessage(error: unknown): string | null {
if (!error || typeof error !== "object") {
return null;
}
const name =
"name" in error && typeof error.name === "string" && error.name.trim().length > 0
? error.name.trim()
: undefined;
const message =
"data" in error &&
error.data &&
@@ -143,34 +47,31 @@ function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null
? error.data.message.trim()
: "";
if (message.length > 0) {
return {
...(name ? { name } : {}),
message,
};
return message;
}
if (name) {
return { name, message: name };
if ("name" in error && typeof error.name === "string") {
const name = error.name.trim();
return name.length > 0 ? name : null;
}
return null;
}
function isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {
return (
part !== null &&
typeof part === "object" &&
"type" in part &&
part.type === "text" &&
"text" in part &&
typeof part.text === "string"
);
}
function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
return (parts ?? [])
.filter(isOpenCodeTextPart)
.map((part) => part.text)
.flatMap((part) => {
if (!part || typeof part !== "object") {
return [];
}
if (!("type" in part) || part.type !== "text") {
return [];
}
if (!("text" in part) || typeof part.text !== "string") {
return [];
}
return [part.text];
})
.join("")
.trim();
}
@@ -309,7 +210,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
(cause) =>
new TextGenerationError({
operation: input.operation,
detail: OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(cause),
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
cause,
}),
),
@@ -359,7 +260,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
);
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
readonly operation: OpenCodeTextGenerationOperation;
readonly operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
readonly cwd: string;
readonly prompt: string;
readonly outputSchemaJson: S;
@@ -380,121 +285,54 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
});
const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
});
const session = yield* Effect.tryPromise({
try: () =>
client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
}),
catch: (cause) =>
new OpenCodeTextGenerationSessionRequestError({
operation: input.operation,
cwd: input.cwd,
cause,
}),
});
if (!session.data) {
return yield* new OpenCodeTextGenerationSessionPayloadError({
operation: input.operation,
cwd: input.cwd,
const runAgainstServer = (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) =>
Effect.tryPromise({
try: async () => {
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
});
}
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
const selectedVariant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
const promptContext = {
operation: input.operation,
cwd: input.cwd,
sessionId: session.data.id,
providerId: parsedModel.providerID,
modelId: parsedModel.modelID,
};
const session = await client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
});
if (!session.data) {
throw new Error("OpenCode session.create returned no session payload.");
}
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
const selectedVariant = getModelSelectionStringOptionValue(
input.modelSelection,
"variant",
);
const result = yield* Effect.tryPromise({
try: () =>
client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
}),
catch: (cause) =>
new OpenCodeTextGenerationPromptRequestError({
...promptContext,
cause,
}),
});
const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
if (promptFailure) {
return yield* new OpenCodeTextGenerationPromptResponseError({
...promptContext,
...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),
providerMessage: promptFailure.message,
const result = await client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
});
}
const responseParts = result.data?.parts ?? [];
const rawText = getOpenCodeTextResponse(responseParts);
if (rawText.length === 0) {
return yield* new OpenCodeTextGenerationEmptyOutputError({
...promptContext,
responsePartCount: responseParts.length,
textPartCount: responseParts.filter(isOpenCodeTextPart).length,
});
}
return rawText;
},
Effect.catchTags({
OpenCodeTextGenerationSessionRequestError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.create request failed.",
cause,
}),
),
OpenCodeTextGenerationSessionPayloadError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.create returned no session payload.",
cause,
}),
),
OpenCodeTextGenerationPromptRequestError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.prompt request failed.",
cause,
}),
),
OpenCodeTextGenerationPromptResponseError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: cause.providerMessage,
cause,
}),
),
OpenCodeTextGenerationEmptyOutputError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode returned empty output.",
cause,
}),
),
}),
);
const info = result.data?.info;
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
if (errorMessage) {
throw new Error(errorMessage);
}
const rawText = getOpenCodeTextResponse(result.data?.parts);
if (rawText.length === 0) {
throw new Error("OpenCode returned empty output.");
}
return rawText;
},
catch: (cause) =>
new TextGenerationError({
operation: input.operation,
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
cause,
}),
});
const rawOutput =
openCodeSettings.serverUrl.length > 0
@@ -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/ProviderInstanceRegistry.ts";
import * as ProviderInstanceRegistry from "../provider/Services/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/ProviderInstanceRegistry.ts";
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
-65
View File
@@ -11,7 +11,6 @@ import {
VcsProcessSpawnError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import * as ProcessRunner from "../processRunner.ts";
import * as VcsProcess from "./VcsProcess.ts";
const run = (input: VcsProcess.VcsProcessInput) =>
@@ -25,25 +24,6 @@ const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
effect.pipe(Effect.provide(liveLayer));
const baseInput = {
operation: "test.process-boundary",
command: "git",
args: ["status", "--short"],
cwd: "/workspace",
} satisfies VcsProcess.VcsProcessInput;
const captureProcessResult = (
result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
) =>
VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({ run: () => result }),
),
Effect.flatMap((service) => service.run(baseInput)),
Effect.flip,
);
describe("VcsProcess.run", () => {
it.effect("collects stdout", () =>
Effect.gen(function* () {
@@ -161,51 +141,6 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
it.effect("preserves real boundary causes without manufacturing structural ones", () =>
Effect.gen(function* () {
const cause = new Error("secret stdin failure");
const error = yield* captureProcessResult(
Effect.fail(
new ProcessRunner.ProcessStdinError({
command: baseInput.command,
argumentCount: baseInput.args.length,
cwd: baseInput.cwd,
stdinBytes: 47,
cause,
}),
),
);
expect(error).toMatchObject({
_tag: "VcsProcessStdinWriteError",
operation: baseInput.operation,
stdinBytes: 47,
cause,
});
expect(error.message).not.toContain(cause.message);
const missingExitCodeError = yield* captureProcessResult(
Effect.succeed({
stdout: "",
stderr: "",
code: null,
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
expect(missingExitCodeError).toMatchObject({
_tag: "VcsProcessMissingExitCodeError",
operation: baseInput.operation,
command: baseInput.command,
cwd: baseInput.cwd,
argumentCount: baseInput.args.length,
});
expect(missingExitCodeError).not.toHaveProperty("cause");
}),
);
it.effect("returns output when non-zero exits are allowed", () =>
Effect.gen(function* () {
const result = yield* run({
+5 -21
View File
@@ -5,14 +5,11 @@ import * as Match from "effect/Match";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
VcsOutputDecodeError,
type VcsError,
VcsProcessExitError,
type VcsProcessExitFailureKind,
VcsProcessMissingExitCodeError,
VcsProcessOutputLimitError,
VcsProcessOutputReadError,
VcsProcessSpawnError,
VcsProcessStdinWriteError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import * as ProcessRunner from "../processRunner.ts";
@@ -117,32 +114,19 @@ export const make = Effect.gen(function* () {
ProcessSpawnError: (error) =>
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
ProcessOutputLimitError: (error) =>
new VcsProcessOutputLimitError({
...baseError,
stream: error.stream,
maxBytes: error.maxBytes,
observedBytes: error.observedBytes,
}),
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
ProcessTimeoutError: (error) =>
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
ProcessStdinError: (error) =>
new VcsProcessStdinWriteError({
...baseError,
stdinBytes: error.stdinBytes,
cause: error.cause,
}),
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
ProcessReadError: (error) =>
new VcsProcessOutputReadError({
...baseError,
stream: error.stream,
cause: error.cause,
}),
VcsOutputDecodeError.fromProcessReadError(baseError, error),
}),
),
);
if (result.code === null) {
return yield* new VcsProcessMissingExitCodeError(baseError);
return yield* VcsOutputDecodeError.missingExitCode(baseError);
}
if (!input.allowNonZeroExit && result.code !== 0) {
+15 -20
View File
@@ -96,19 +96,16 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd });
assert.equal(kind, "jj");
const [message, context] = messages[0] as [string, Record<string, unknown>];
const failedCandidate = path.join(cwd, ".t3code", "vcs.json");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
assert.equal(
error.message,
"Failed to inspect VCS project config at " + failedCandidate + ".",
);
assert.deepInclude(error, {
assert.equal(message, "Failed to inspect VCS project config at " + failedCandidate + ".");
assert.deepInclude(context, {
operation: "inspect",
cwd,
configPath: failedCandidate,
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
@@ -149,19 +146,18 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
const [message, context] = messages[0] as [string, Record<string, unknown>];
assert.equal(
error.message,
message,
"Failed to decode VCS project config at " + path.join(configDir, "vcs.json") + ".",
);
assert.deepInclude(error.cause, { _tag: "SchemaError" });
assert.deepInclude(error, {
assert.deepInclude(context, {
operation: "decode",
cwd: root,
configPath: path.join(configDir, "vcs.json"),
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
@@ -186,16 +182,15 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
assert.equal(error.message, "Failed to read VCS project config at " + configPath + ".");
assert.deepInclude(error.cause, { _tag: "PlatformError" });
assert.deepInclude(error, {
const [message, context] = messages[0] as [string, Record<string, unknown>];
assert.equal(message, "Failed to read VCS project config at " + configPath + ".");
assert.deepInclude(context, {
operation: "read",
cwd: root,
configPath,
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
+7 -8
View File
@@ -55,14 +55,13 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
}
const logVcsProjectConfigError = (error: VcsProjectConfigError) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
operation: error.operation,
cwd: error.cwd,
configPath: error.configPath,
errorTag: error._tag,
}),
);
Effect.logWarning(error.message, {
operation: error.operation,
cwd: error.cwd,
configPath: error.configPath,
errorTag: error._tag,
stack: error.stack,
});
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+9 -18
View File
@@ -151,29 +151,20 @@ export const make = Effect.gen(function* () {
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
return;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
});
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
Effect.catch((cause) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
}),
),
);
},
);
@@ -1,8 +1,6 @@
import { FileFinder } from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { vi } from "vite-plus/test";
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
@@ -51,35 +49,6 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
}),
);
it.effect("preserves FileFinder destroy failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native destroy failed");
const finder = {
destroy: vi.fn(() => {
throw cause;
}),
isScanning: vi.fn(() => false),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
Effect.exit,
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasDies(exit.cause)).toBe(true);
const error = Cause.squash(exit.cause);
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
expect(error).toMatchObject({
_tag: "WorkspaceSearchIndexDestroyFailed",
cwd: "/workspace/project",
cause,
});
}
}),
);
it.effect("preserves search and refresh failures with operation context", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -71,18 +71,6 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
}
}
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
"WorkspaceSearchIndexDestroyFailed",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
}
}
export type WorkspaceSearchIndexError =
| WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndexScanTimedOut
@@ -213,10 +201,7 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
Effect.try({
try: () => finder.destroy(),
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
}).pipe(Effect.orDie),
Effect.sync(() => finder.destroy()),
);
yield* waitForScan(
cwd,
+1 -1
View File
@@ -73,7 +73,7 @@ import {
observeRpcStream as instrumentRpcStream,
observeRpcStreamEffect as instrumentRpcStreamEffect,
} from "./observability/RpcInstrumentation.ts";
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
+26 -76
View File
@@ -71,18 +71,6 @@ function installTestBrowser(url: string) {
return testWindow;
}
function installDesktopBootstrap() {
const testWindow = installTestBrowser("http://localhost/");
testWindow.desktopBridge = {
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
} as DesktopBridge;
}
function sequence<A>(...values: ReadonlyArray<A>) {
let index = 0;
return () => values[Math.min(index++, values.length - 1)]!;
@@ -143,7 +131,15 @@ describe("resolveInitialServerAuthGateState", () => {
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
installDesktopBootstrap();
const testWindow = installTestBrowser("http://localhost/");
testWindow.desktopBridge = {
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
} as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
@@ -293,23 +289,6 @@ describe("resolveInitialServerAuthGateState", () => {
expect(testApi.calls.session).toBe(2);
});
it("rejects a blank pairing token with a structured validation error", async () => {
const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
await import("./environments/primary/auth");
const error = await submitServerAuthCredential(" ").then(
() => null,
(failure: unknown) => failure,
);
expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
expect(error).toMatchObject({
_tag: "PrimaryEnvironmentPairingCredentialRequiredError",
providedLength: 3,
message: "Enter a pairing token to continue.",
});
});
it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
const cause = new EnvironmentAuthInvalidError({
code: "auth_invalid",
@@ -320,7 +299,7 @@ describe("resolveInitialServerAuthGateState", () => {
browserSession: () => Effect.fail(cause),
});
const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
const { isPrimaryEnvironmentRequestError, submitServerAuthCredential } =
await import("./environments/primary");
const error = await submitServerAuthCredential("bad-token").then(
@@ -328,13 +307,14 @@ describe("resolveInitialServerAuthGateState", () => {
(failure: unknown) => failure,
);
expect(error).toMatchObject({
_tag: "PrimaryEnvironmentPairingCredentialRejectedError",
providedLength: 9,
message: "Invalid pairing token. Check the token and try again.",
_tag: "PrimaryEnvironmentRequestError",
operation: "exchange-bootstrap-credential",
status: 401,
detail: "Invalid pairing token. Check the token and try again.",
});
expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
throw new Error("Expected a structured rejected pairing credential error.");
expect(isPrimaryEnvironmentRequestError(error)).toBe(true);
if (!isPrimaryEnvironmentRequestError(error)) {
throw new Error("Expected a structured primary environment request error.");
}
expect(error.cause).toMatchObject({
_tag: "EnvironmentAuthInvalidError",
@@ -345,22 +325,6 @@ describe("resolveInitialServerAuthGateState", () => {
expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
});
it("derives primary request messages from structural request context", async () => {
const cause = new Error("private transport detail");
const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
const error = PrimaryEnvironmentRequestError.fromCause({
operation: "list-pairing-links",
cause,
});
expect(error.status).toBe(500);
expect(error.cause).toBe(cause);
expect(error.message).toBe(
"Primary environment request failed during list-pairing-links (HTTP 500).",
);
expect(error.message).not.toContain(cause.message);
});
it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
vi.useFakeTimers();
const nextSession = sequence(
@@ -373,7 +337,15 @@ describe("resolveInitialServerAuthGateState", () => {
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
installDesktopBootstrap();
const testWindow = installTestBrowser("http://localhost/");
testWindow.desktopBridge = {
getLocalEnvironmentBootstrap: () => ({
label: "Local environment",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
} as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
@@ -384,28 +356,6 @@ describe("resolveInitialServerAuthGateState", () => {
expect(testApi.calls.session).toBe(3);
});
it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
vi.useFakeTimers();
const testApi = await installAuthApi({
session: () => unauthenticatedSession(DESKTOP_AUTH),
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
installDesktopBootstrap();
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
const gateStatePromise = resolveInitialServerAuthGateState();
await vi.advanceTimersByTimeAsync(2_000);
await expect(gateStatePromise).resolves.toEqual({
status: "requires-auth",
auth: DESKTOP_AUTH,
errorMessage: "Timed out waiting for authenticated session after bootstrap.",
});
expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
});
it("memoizes the authenticated gate state after the first successful read", async () => {
const testApi = await installAuthApi({
session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
+4 -1
View File
@@ -70,7 +70,10 @@ describe("makeCatalogBackend", () => {
const error = yield* backend.write("{}").pipe(Effect.flip);
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error.message).toContain("Desktop secure storage is unavailable");
expect(error.message).toBe("Could not save the local connection catalog.");
expect(error.cause).toEqual(
new Error("Desktop secure storage is unavailable in this system context."),
);
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
}),
);
+47 -34
View File
@@ -63,26 +63,8 @@ const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson)
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function persistenceError(
operation:
| "list-targets"
| "register-connection"
| "remove-connection"
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
@@ -233,7 +215,7 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
: Effect.fail(
catalogError(
"save",
"Desktop secure storage is unavailable in this system context.",
new Error("Desktop secure storage is unavailable in this system context."),
),
),
),
@@ -330,18 +312,29 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((cause) => persistenceError("list-targets", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -430,7 +423,9 @@ export const connectionStorageLayer = Layer.effectContext(
return Effect.succeed(Option.none());
}
return decodeStoredShellSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-shell", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
Effect.map((stored) =>
stored.environmentId === environmentId
? Option.some(stored.snapshot)
@@ -441,7 +436,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-shell", cause),
: new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
),
saveShell: (environmentId, snapshot) =>
@@ -450,13 +445,17 @@ export const connectionStorageLayer = Layer.effectContext(
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
}).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-shell", cause),
: new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
),
loadThread: (environmentId, threadId) =>
@@ -470,7 +469,9 @@ export const connectionStorageLayer = Layer.effectContext(
return Effect.succeed(Option.none());
}
return decodeStoredThreadSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-thread", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
Effect.map((stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
@@ -481,7 +482,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-thread", cause),
: new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
),
saveThread: (environmentId, thread) =>
@@ -491,7 +492,11 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
threadId: thread.id,
thread,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
}).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
yield* writeDatabaseValue(
database,
THREAD_STORE_NAME,
@@ -502,7 +507,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-thread", cause),
: new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
),
removeThread: (environmentId, threadId) =>
@@ -510,7 +515,11 @@ export const connectionStorageLayer = Layer.effectContext(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, threadId),
).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-thread", cause }),
),
),
clear: (environmentId) =>
Effect.all(
[
@@ -522,7 +531,11 @@ export const connectionStorageLayer = Layer.effectContext(
),
],
{ concurrency: "unbounded", discard: true },
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "clear-environment", cause }),
),
),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more