fix: preserve provider failure structure
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
f8eb67ddd7
commit
7f05bcdbc0
15 files changed
+258
-131
No files matched your search
@@ -193,7 +193,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
|
||||
detail: "Failed to build the Claude provider snapshot.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -134,7 +134,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: cause.message,
|
||||
detail: "Failed to materialize the Codex shadow home.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -193,7 +193,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
|
||||
detail: "Failed to build the Codex provider snapshot.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -165,7 +165,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
|
||||
detail: "Failed to build the Cursor provider snapshot.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -141,7 +141,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
|
||||
detail: "Failed to build the Grok provider snapshot.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -177,7 +177,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
|
||||
detail: "Failed to build the OpenCode provider snapshot.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -564,7 +564,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
detail: "Failed to start the Cursor ACP session process.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -979,7 +979,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -408,7 +408,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
detail: "Failed to start the Grok ACP session process.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -736,7 +736,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -307,13 +307,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
const customModels = openCodeSettings.customModels;
|
||||
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
const buildFailureSnapshot = (
|
||||
failure: { readonly installed: boolean; readonly message: string },
|
||||
version: string | null,
|
||||
) =>
|
||||
buildServerProvider({
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: openCodeSettings.enabled,
|
||||
checkedAt,
|
||||
@@ -331,7 +329,16 @@ 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({
|
||||
@@ -381,10 +388,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
|
||||
if (!version) {
|
||||
return fallback(
|
||||
new Error(
|
||||
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
),
|
||||
return buildFailureSnapshot(
|
||||
{
|
||||
installed: true,
|
||||
message: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
},
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ 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";
|
||||
|
||||
@@ -159,6 +160,8 @@ 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;
|
||||
@@ -203,12 +206,13 @@ 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 issue = decodeResult.failure;
|
||||
const detail = issue.message ?? String(issue);
|
||||
const cause = decodeResult.failure;
|
||||
const detail = formatSchemaIssue(cause.issue);
|
||||
yield* Effect.logError("Failed to decode provider instance config", {
|
||||
instanceId: rawInstanceId,
|
||||
driver: entry.driver,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
return {
|
||||
kind: "unavailable" as const,
|
||||
@@ -246,6 +250,7 @@ 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 {
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,8 +38,9 @@ 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 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";
|
||||
@@ -60,6 +61,20 @@ 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,
|
||||
{
|
||||
@@ -211,18 +226,14 @@ const correlateSnapshotWithSource = (
|
||||
source: ProviderSnapshotSource,
|
||||
snapshot: ServerProvider,
|
||||
): Effect.Effect<ServerProvider> => {
|
||||
if (snapshot.instanceId !== source.instanceId) {
|
||||
if (snapshot.instanceId !== source.instanceId || snapshot.driver !== source.driverKind) {
|
||||
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}'.`,
|
||||
),
|
||||
new ProviderSnapshotCorrelationError({
|
||||
sourceInstanceId: source.instanceId,
|
||||
snapshotInstanceId: snapshot.instanceId,
|
||||
sourceDriver: source.driverKind,
|
||||
snapshotDriver: snapshot.driver,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(snapshot);
|
||||
@@ -669,7 +680,7 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.logError("provider registry instance sync failed; keeping subscription alive", {
|
||||
cause: Cause.pretty(cause),
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -717,7 +728,7 @@ export const make = Effect.gen(function* () {
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
|
||||
cause: Cause.pretty(cause),
|
||||
cause,
|
||||
});
|
||||
return yield* Ref.get(providersRef);
|
||||
});
|
||||
|
||||
@@ -30,6 +30,7 @@ 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";
|
||||
@@ -1085,6 +1086,18 @@ 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"),
|
||||
|
||||
@@ -21,13 +21,12 @@ import {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
type ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -73,7 +72,49 @@ import {
|
||||
revokeActiveMcpThread,
|
||||
revokeAllActiveMcpCredentials,
|
||||
} from "../mcp/McpSessionRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
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,
|
||||
@@ -141,6 +182,8 @@ export class ProviderService extends Context.Service<
|
||||
}
|
||||
>()("t3/provider/ProviderService") {}
|
||||
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
* Hook for tests that want to override the canonical event logger pulled
|
||||
* from `ProviderEventLoggers`. Production wiring leaves this undefined and
|
||||
@@ -155,18 +198,6 @@ const ProviderRollbackConversationInput = Schema.Struct({
|
||||
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;
|
||||
@@ -253,11 +284,10 @@ const dieOnMissingBindingInstanceId = (
|
||||
if (payload.providerInstanceId !== undefined) {
|
||||
return payload.providerInstanceId;
|
||||
}
|
||||
throw new Error(
|
||||
payload.provider
|
||||
? `${operation}: provider instance id is required for provider '${payload.provider}'.`
|
||||
: `${operation}: provider instance id is required.`,
|
||||
);
|
||||
throw new ProviderBindingInstanceIdMissingError({
|
||||
operation,
|
||||
...(payload.provider === undefined ? {} : { provider: payload.provider }),
|
||||
});
|
||||
};
|
||||
|
||||
const correlateRuntimeEventWithInstance = (
|
||||
@@ -267,15 +297,18 @@ const correlateRuntimeEventWithInstance = (
|
||||
},
|
||||
event: ProviderRuntimeEvent,
|
||||
): ProviderRuntimeEvent => {
|
||||
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}'.`,
|
||||
);
|
||||
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,
|
||||
});
|
||||
}
|
||||
return { ...event, providerInstanceId: source.instanceId };
|
||||
};
|
||||
@@ -325,12 +358,12 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
payload.providerInstanceId !== undefined
|
||||
? Effect.succeed(payload.providerInstanceId)
|
||||
: Effect.fail(
|
||||
toValidationError(
|
||||
new ProviderValidationError({
|
||||
operation,
|
||||
payload.provider
|
||||
issue: payload.provider
|
||||
? `Provider instance id is required for provider '${payload.provider}'.`
|
||||
: "Provider instance id is required.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const upsertSessionBinding = (
|
||||
@@ -465,10 +498,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
});
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
@@ -488,10 +521,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* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(
|
||||
@@ -522,10 +555,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* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
});
|
||||
}
|
||||
const instanceId = yield* requireBindingInstanceId(input.operation, binding);
|
||||
const adapter = yield* registry.getByInstance(instanceId);
|
||||
@@ -620,10 +653,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* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
});
|
||||
}
|
||||
const input = {
|
||||
...parsed,
|
||||
@@ -631,10 +664,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
provider: resolvedProvider,
|
||||
};
|
||||
if (!instanceInfo.enabled) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
});
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
@@ -679,10 +712,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(threadId);
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
});
|
||||
}
|
||||
const sessionWithInstance = {
|
||||
...session,
|
||||
@@ -732,10 +765,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
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",
|
||||
);
|
||||
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",
|
||||
@@ -1014,18 +1047,18 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
"ProviderService.listSessions",
|
||||
binding,
|
||||
);
|
||||
if (binding.provider !== session.provider) {
|
||||
if (
|
||||
binding.provider !== session.provider ||
|
||||
overrides.providerInstanceId !== session.providerInstanceId
|
||||
) {
|
||||
return yield* Effect.die(
|
||||
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}'.`,
|
||||
),
|
||||
new ProviderSessionBindingCorrelationError({
|
||||
threadId: session.threadId,
|
||||
sessionProvider: session.provider,
|
||||
bindingProvider: binding.provider,
|
||||
sessionInstanceId: session.providerInstanceId,
|
||||
bindingInstanceId: overrides.providerInstanceId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
@@ -1139,9 +1172,7 @@ 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: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.catchCause((cause) => Effect.logWarning("failed to stop provider service", { cause })),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../persistence/Layers/Sqlite.ts";
|
||||
import { PersistenceSqlError } from "../persistence/Errors.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
|
||||
@@ -28,6 +29,36 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("preserves provider session repository failure causes", () => {
|
||||
const rootCause = new Error("database unavailable");
|
||||
const repositoryCause = new PersistenceSqlError({
|
||||
operation: "ProviderSessionRuntimeRepository.getByThreadId",
|
||||
detail: "Failed to read provider session runtime.",
|
||||
cause: rootCause,
|
||||
});
|
||||
const repository = ProviderSessionRuntime.ProviderSessionRuntimeRepository.of({
|
||||
upsert: () => Effect.fail(repositoryCause),
|
||||
getByThreadId: () => Effect.fail(repositoryCause),
|
||||
list: () => Effect.fail(repositoryCause),
|
||||
deleteByThreadId: () => Effect.fail(repositoryCause),
|
||||
});
|
||||
const layer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderSessionRuntime.ProviderSessionRuntimeRepository, repository),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const error = yield* directory
|
||||
.getBinding(ThreadId.make("thread-read-failure"))
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.operation, "ProviderSessionDirectory.getBinding:getByThreadId");
|
||||
assert.equal(error.cause, repositoryCause);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -67,15 +67,6 @@ export class ProviderSessionDirectory extends Context.Service<
|
||||
|
||||
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,
|
||||
@@ -139,7 +130,14 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const getBinding: ProviderSessionDirectory["Service"]["getBinding"] = (threadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
|
||||
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>()),
|
||||
@@ -154,9 +152,16 @@ export const make = Effect.gen(function* () {
|
||||
const upsert: ProviderSessionDirectory["Service"]["upsert"] = Effect.fn(
|
||||
"ProviderSessionDirectory.upsert",
|
||||
)(function* (binding) {
|
||||
const existing = yield* repository
|
||||
.getByThreadId({ threadId: binding.threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
|
||||
const 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;
|
||||
@@ -198,7 +203,16 @@ export const make = Effect.gen(function* () {
|
||||
binding.runtimePayload,
|
||||
),
|
||||
})
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
|
||||
.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) =>
|
||||
@@ -219,13 +233,27 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const listThreadIds: ProviderSessionDirectory["Service"]["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
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(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.listBindings:list",
|
||||
detail: "Failed to list persisted provider session bindings.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
|
||||
@@ -326,7 +326,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Provider post-update version verification failed", {
|
||||
provider,
|
||||
cause: Cause.pretty(cause),
|
||||
cause,
|
||||
}).pipe(
|
||||
Effect.as<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
|
||||
Reference in new issue
Block a user