refactor!: enforce canonical evidence and provider boundaries

Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership.

Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers.

BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
morluto
2026-10-09 20:18:52 +08:00
parent 2a7746998d
commit 63bf91405c
514 changed files with 9296 additions and 5825 deletions
@@ -1,10 +1,14 @@
import { expect, it } from "vitest";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err } from "../../domain/result.js";
import type { AnalysisClient } from "../AnalysisProvider.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
import {
analysisErrorWithCleanupFailure,
closeAnalysisClient,
} from "./AnalysisClientCleanup.js";
const clientClosingWith = (cause: unknown): AnalysisClient => ({
execute: () => Promise.resolve(err(new ProviderCleanupError("x", [], {}))),
@@ -43,3 +47,31 @@ it("still reports an untyped close rejection as the provider client", async () =
details: { resources: ["provider-client"] },
});
});
it("preserves the original explanation and collected output alongside cleanup uncertainty", () => {
const primary = new ProviderAdapterError("fixture", "capture", {
userMessage: "Select the running target process and retry the capture.",
capturedOutput: {
stdout: "partial observation",
stderr: "native reason",
truncated: false,
},
});
const cleanup = new ProviderCleanupError("fixture", ["owned-process"], {
reason: "Process termination was not confirmed",
});
const combined = analysisErrorWithCleanupFailure(primary, cleanup);
expect(projectAnalysisError(combined)).toMatchObject({
code: "cleanup_incomplete",
message: primary.userMessage,
details: {
resources: ["owned-process"],
captured_output: primary.capturedOutput,
diagnostics: {
primary_error: projectAnalysisError(primary),
cleanup_error: projectAnalysisError(cleanup),
},
},
});
expect(combined.cause).toBe(primary);
});
@@ -1,7 +1,7 @@
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { err, type Result } from "../../domain/result.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisClient, ExecutionOptions } from "../AnalysisProvider.js";
@@ -14,10 +14,7 @@ export const closeAnalysisClient = async (
} = {},
): Promise<Result<null, AnalysisError>> => {
try {
if (client.closeWithOutcome !== undefined)
return await client.closeWithOutcome(options);
await client.close();
return ok(null);
return await client.close(options);
} catch (cause: unknown) {
// A typed cleanup failure already names its leftover resources.
if (cause instanceof AnalysisError && cause.cleanupIncomplete)
@@ -45,6 +42,13 @@ export const analysisErrorWithCleanupFailure = (
operation,
{
cause: primary,
userMessage: projectAnalysisError(primary).message,
...(primary.capturedOutput === undefined
? {}
: { capturedOutput: primary.capturedOutput }),
...(primary.partialObservation === undefined
? {}
: { partialObservation: primary.partialObservation }),
cleanup: {
reason: projected.message,
resources: cleanup.cleanupResources,
@@ -19,7 +19,6 @@ export interface AnalysisProviderCandidateEvaluation {
readonly candidate: AnalysisProviderCandidate;
readonly status: AnalysisProviderCandidateStatus;
readonly profile?: AnalysisProfileCommitment;
readonly compatibility?: Readonly<Record<string, JsonValue>>;
readonly profileError?: AnalysisError;
}
@@ -87,7 +86,6 @@ export const evaluateAnalysisProviderCandidate = async (
),
);
const profile = analysisProfileSchema.parse(resolved.value.profile);
const compatibility = jsonObjectSchema.parse(resolved.value.compatibility);
const identity = candidate.identity();
if (
profile.provider.id !== identity.id ||
@@ -102,7 +100,7 @@ export const evaluateAnalysisProviderCandidate = async (
"Resolved analysis profile has mismatched provider identity",
),
);
return ok({ candidate, status, profile, compatibility });
return ok({ candidate, status, profile });
} catch (cause: unknown) {
void cause;
return ok(
@@ -308,7 +308,6 @@ const candidate = (
{ id, name: identity.name, version: "1" },
{ fixture: id },
),
compatibility: {},
}),
);
},
@@ -325,7 +324,7 @@ const candidate = (
),
),
),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
};
},
};
@@ -49,7 +49,6 @@ export interface AnalysisProviderBinding {
readonly identity: ProviderIdentity & { readonly version: string };
readonly selectionSource: "request" | "environment" | "auto-single-candidate";
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
}
/** Complete result used for both a bound and intentionally unbound target. */
@@ -247,10 +246,7 @@ export class AnalysisProviderRegistry {
if (evaluated.profileError !== undefined)
return err(evaluated.profileError);
const statuses = replaceCandidate(baseline, evaluated.status);
if (
evaluated.profile === undefined ||
evaluated.compatibility === undefined
)
if (evaluated.profile === undefined)
return err(selectionError("provider_unavailable", providerId, statuses));
return ok(
selectedResult(
@@ -259,7 +255,6 @@ export class AnalysisProviderRegistry {
{
...evaluated,
profile: evaluated.profile,
compatibility: evaluated.compatibility,
},
statuses,
),
@@ -312,10 +307,7 @@ export class AnalysisProviderRegistry {
evaluation,
): evaluation is AnalysisProviderCandidateEvaluation & {
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
} =>
evaluation.profile !== undefined &&
evaluation.compatibility !== undefined,
} => evaluation.profile !== undefined,
);
if (usable.length === 0)
return ok({
@@ -363,7 +355,6 @@ const selectedResult = (
source: AnalysisProviderBinding["selectionSource"],
evaluated: AnalysisProviderCandidateEvaluation & {
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
},
statuses: readonly AnalysisProviderCandidateStatus[],
): AnalysisProviderSelection => {
@@ -379,7 +370,6 @@ const selectedResult = (
identity: structuredClone(evaluated.profile.provider),
selectionSource: source,
profile: structuredClone(evaluated.profile),
compatibility: structuredClone(evaluated.compatibility),
},
candidates: replaceCandidate(statuses, selectedStatus),
};
@@ -72,6 +72,7 @@ it("exports independent nested query, workflow and Evidence payloads", () => {
}),
createEvidence(target, REA_WORKFLOW_PROVIDER, {
operation: "analyze_function",
confidence: "derived",
parameters,
result,
rawResult: result,
@@ -91,7 +92,7 @@ it("exports independent nested query, workflow and Evidence payloads", () => {
execution.result,
execution.raw_result,
]),
...(exported.value.workflow_entries ?? []).flatMap(({ execution }) => [
...exported.value.workflow_entries.flatMap(({ execution }) => [
execution.result,
execution.raw_result,
]),
@@ -186,6 +187,7 @@ describe("analysis snapshot cache capacity", () => {
});
const evidence = createEvidence(target, REA_WORKFLOW_PROVIDER, {
operation: workflowInput.operation,
confidence: "derived",
parameters: workflowInput.parameters,
result: execution.result,
rawResult: execution.rawResult,
@@ -124,7 +124,7 @@ export class AnalysisSnapshotCache {
if (!this.#entries.has(entry.query_id)) imported += 1;
this.#entries.set(entry.query_id, structuredClone(entry));
}
for (const entry of snapshot.workflow_entries ?? []) {
for (const entry of snapshot.workflow_entries) {
if (!this.#workflowEntries.has(entry.query_id) && !this.#hasCapacity())
continue;
this.#workflowEntries.set(entry.query_id, structuredClone(entry));
@@ -156,7 +156,7 @@ export class AnalysisSnapshotCache {
target: snapshotTargetIdentity,
binding,
entries,
...(workflows.length === 0 ? {} : { workflow_entries: workflows }),
workflow_entries: workflows,
evidence_bundle: evidenceBundle,
}),
);
+6 -15
View File
@@ -60,7 +60,6 @@ interface SessionBinding {
readonly target: BinaryTarget;
readonly client: AnalysisClient;
readonly profile: AnalysisProfileCommitment | null;
readonly compatibility: Readonly<Record<string, JsonValue>>;
readonly route: SessionProviderRoute;
readonly runId: string;
}
@@ -105,13 +104,13 @@ export class BinarySession
/** Identify the provider producing evidence for this session. */
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
const route = this.#currentRoute();
let selected = route.identity;
let selected = route.binding?.identity ?? route.identity;
if (operation !== undefined) {
const exact = route.capabilities?.get(operation)?.provider;
const exact = route.capabilities.get(operation)?.provider;
if (exact !== undefined) selected = exact;
else if (ENHANCED_OPERATIONS.has(operation)) {
const providers = new Map<string, ProviderIdentity>();
for (const descriptor of route.capabilities?.values() ?? [])
for (const descriptor of route.capabilities.values())
if (
descriptor.available &&
OFFICIAL_OPERATIONS.has(descriptor.operation)
@@ -157,11 +156,6 @@ export class BinarySession
return structuredClone(profile);
}
/** Return opaque adapter metadata retained for legacy open_binary output. */
openCompatibility(): Readonly<Record<string, JsonValue>> {
return structuredClone(this.#active?.compatibility ?? {});
}
/** Observe runtime provider-health changes that affect discovery metadata. */
onAvailabilityChanged(listener: () => void | Promise<void>): () => void {
this.#availabilityListeners.add(listener);
@@ -241,7 +235,7 @@ export class BinarySession
const resolved = await resolve();
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile, compatibility } = route;
const { profile } = route;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
@@ -310,7 +304,6 @@ export class BinarySession
target,
client,
profile,
compatibility: structuredClone(compatibility),
route,
runId,
};
@@ -370,9 +363,8 @@ export class BinarySession
return closed.ok
? ok({
...written.value,
entries: snapshot.value.entries.length,
primitive_entries: snapshot.value.entries.length,
workflow_entries: snapshot.value.workflow_entries?.length ?? 0,
workflow_entries: snapshot.value.workflow_entries.length,
evidence_records: snapshot.value.evidence_bundle.records.length,
})
: closed;
@@ -584,7 +576,7 @@ export class BinarySession
parameters: arguments_,
execution: profiled.value,
});
} else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
} else if (profiled.ok && capability.effects.mutatesArtifact) {
this.invalidateSnapshot();
}
return profiled;
@@ -699,7 +691,6 @@ export class BinarySession
target: previous.target,
client,
profile: previous.profile,
compatibility: previous.compatibility,
route: previous.route,
runId,
};
@@ -9,12 +9,10 @@ import { SessionProviderRouter } from "./SessionProviderRouter.js";
* disjoint auxiliary operation families.
*/
export const composeBinarySession = (
registry: AnalysisProviderRegistry | SessionProviderRouter,
registry: AnalysisProviderRegistry,
auxiliaryProviders: readonly AnalysisProvider[] = [],
): BinarySession =>
new BinarySession(
registry instanceof SessionProviderRouter
? registry
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
SessionProviderRouter.selectable(registry, auxiliaryProviders),
new InvestigationRecords(),
);
@@ -25,7 +25,7 @@ interface ActiveExecutionBinding {
export interface PreparedSessionExecution {
readonly active: ActiveExecutionBinding;
readonly capability: CapabilityDescriptor | undefined;
readonly capability: CapabilityDescriptor;
readonly profile: AnalysisProfileCommitment | undefined;
readonly cacheable: boolean;
readonly cached: AnalysisExecution | undefined;
@@ -59,11 +59,8 @@ export const prepareSessionExecution = (
lookupSnapshot,
} = input;
if (active === undefined) return err(new NoBinaryOpenError());
const capability = active.route.capabilities?.get(operation);
if (
active.route.capabilities !== undefined &&
capability?.available !== true
) {
const capability = active.route.capabilities.get(operation);
if (capability?.available !== true) {
const selectionError = unboundOperationError(operation, active.route);
if (selectionError !== undefined) return err(selectionError);
return err(
@@ -76,8 +73,7 @@ export const prepareSessionExecution = (
}
const profile =
active.profile !== null &&
(capability === undefined ||
capability.provider.id === active.profile.provider.id)
capability.provider.id === active.profile.provider.id
? active.profile
: undefined;
const cacheable =
+1 -3
View File
@@ -21,8 +21,7 @@ import type {
export interface SavedAnalysisSnapshot {
readonly path: string;
readonly bytes: number;
readonly entries: number;
/** Eligible primitive query bindings; also reported by the legacy entries field. */
/** Eligible primitive query bindings. */
readonly primitive_entries: number;
/** Eligible composed workflow bindings, separate from primitive queries. */
readonly workflow_entries: number;
@@ -68,7 +67,6 @@ export interface BinarySessionPort
recordWorkflowSnapshot(
input: WorkflowSnapshotRecordInput,
): Result<null, EvidenceIntegrityError>;
openCompatibility(): Readonly<Record<string, JsonValue>>;
onAvailabilityChanged?(listener: () => void | Promise<void>): () => void;
onAnalysisSnapshotChanged?(listener: () => void | Promise<void>): () => void;
}
@@ -42,7 +42,7 @@ export interface WorkflowSnapshotRecordInput {
>[0]["execution"];
}
/** Binary snapshot owner and compatibility facade for composed investigation records. */
/** Own binary snapshots and coordinate the composed investigation records. */
export abstract class BinarySessionRecords {
readonly #records: InvestigationRecords;
readonly #snapshot = new AnalysisSnapshotCache();
@@ -36,10 +36,7 @@ export const binarySessionStatus = ({
requestActivitySnapshots,
providerOperationHealth,
}: BinarySessionStatusInput): JsonValue => {
const configuredProvider = router.configuredIdentity();
const provider = providerSummary(configuredProvider);
const providers = router.providerIdentities(route).map(providerSummary);
const capabilities = [...(route.capabilities?.values() ?? [])]
const capabilities = [...route.capabilities.values()]
.filter(({ operation }) => operation !== "inventory_artifact")
.sort((left, right) => left.operation.localeCompare(right.operation))
.map((descriptor) => {
@@ -75,8 +72,6 @@ export const binarySessionStatus = ({
.map(capabilityStatus),
}));
const common = {
provider,
providers,
capabilities,
analysis_provider_binding: analysisProviderBinding,
analysis_provider_candidates: analysisProviderCandidates,
+4 -29
View File
@@ -5,15 +5,14 @@ import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js"
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisProfileResolutionOptions,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "../AnalysisProvider.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
/** Synthetic compatibility identity for a deterministic provider set. */
export const compositeProviderIdentity = (
/** Synthetic identity for a deterministic provider set. */
const compositeProviderIdentity = (
identities: readonly ProviderIdentity[],
): ProviderIdentity => ({
id: `composite:${identities
@@ -29,19 +28,10 @@ export class CompositeProvider implements AnalysisProvider {
readonly #identity: ProviderIdentity;
readonly #capabilities: readonly CapabilityDescriptor[];
readonly #providerByOperation: ReadonlyMap<string, AnalysisProvider>;
readonly #profileProvider: AnalysisProvider | undefined;
constructor(readonly providers: readonly AnalysisProvider[]) {
if (providers.length === 0)
throw new RangeError("CompositeProvider requires at least one provider");
const profileProviders = providers.filter(
({ resolveAnalysisProfile }) => resolveAnalysisProfile !== undefined,
);
if (profileProviders.length > 1)
throw new TypeError(
"CompositeProvider supports at most one target-bound analysis profile",
);
this.#profileProvider = profileProviders[0];
this.#identity = Object.freeze(
compositeProviderIdentity(
providers.map((provider) => provider.identity()),
@@ -77,16 +67,6 @@ export class CompositeProvider implements AnalysisProvider {
return this.#capabilities;
}
resolveAnalysisProfile(
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) {
const resolve = this.#profileProvider?.resolveAnalysisProfile;
return resolve === undefined
? Promise.resolve(ok({ profile: null, compatibility: {} }))
: resolve.call(this.#profileProvider, target, options);
}
createClient(
target: BinaryTarget,
profile?: AnalysisProfileCommitment,
@@ -104,9 +84,7 @@ export class CompositeProvider implements AnalysisProvider {
clients.set(provider, created);
return created;
};
const closeWithOutcome: NonNullable<
AnalysisClient["closeWithOutcome"]
> = async (options) => {
const close: AnalysisClient["close"] = async (options) => {
const outcomes = await Promise.all(
[...clients.entries()].map(([provider, client]) =>
closeAnalysisClient(client, provider.identity().id, options),
@@ -164,10 +142,7 @@ export class CompositeProvider implements AnalysisProvider {
}
return undefined;
},
closeWithOutcome,
close: async () => {
await closeWithOutcome();
},
close,
};
}
}
@@ -7,7 +7,7 @@ import type {
} from "../AnalysisProvider.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { err } from "../../domain/result.js";
import { err, ok as resultOk } from "../../domain/result.js";
const identity: ProviderIdentity = {
id: "test-provider",
@@ -24,7 +24,7 @@ const providerWithClient = (
onCreate();
return {
execute: async (operation) => err(new AnalysisCancelledError(operation)),
close: async () => undefined,
close: async () => resultOk(null),
};
},
});
@@ -4,7 +4,7 @@ import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
import { err } from "../../domain/result.js";
import { err, ok } from "../../domain/result.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import type {
AnalysisClient,
@@ -120,12 +120,12 @@ class LazyAnalysisClient implements AnalysisClient {
return this.#client?.operationHealthSnapshot?.();
}
async close(): Promise<void> {
close: AnalysisClient["close"] = async (options) => {
this.#closed = true;
if (this.#loading === undefined) return;
if (this.#loading === undefined) return ok(null);
const client = await this.#loading;
await client.close();
}
return client.close(options);
};
async #load(operation: string): Promise<AnalysisClient> {
if (this.#closed)
+29 -221
View File
@@ -1,24 +1,13 @@
import type { AnalysisProviderSelector } from "../../contracts/providerSelection.js";
import {
analysisProfileSchema,
type AnalysisProfileCommitment,
} from "../../domain/analysisProfile.js";
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { ProviderSelectionError } from "../../domain/providerSelectionError.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisClientFactory,
AnalysisProfileResolution,
AnalysisProfileResolutionOptions,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
@@ -29,18 +18,13 @@ import {
type AnalysisProviderCandidateStatus,
type AnalysisProviderSelection,
} from "./AnalysisProviderRegistry.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import {
CompositeProvider,
compositeProviderIdentity,
} from "./CompositeProvider.js";
import { CompositeProvider } from "./CompositeProvider.js";
/** Immutable operation routes and binding metadata for one target transition. */
export interface SessionProviderRoute {
readonly identity: ProviderIdentity;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor>;
readonly profile: AnalysisProfileCommitment | null;
readonly compatibility: Readonly<Record<string, JsonValue>>;
readonly binding: AnalysisProviderBinding | null;
readonly selection: AnalysisProviderSelection | undefined;
createClient(
@@ -49,69 +33,14 @@ export interface SessionProviderRoute {
): AnalysisClient;
}
interface SingleProviderRuntime {
readonly kind: "single";
readonly provider: AnalysisProvider | AnalysisClientFactory;
readonly identity: ProviderIdentity;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
readonly resolveProfile: (
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
}
interface SelectableProviderRuntime {
readonly kind: "selectable";
readonly registry: AnalysisProviderRegistry;
readonly auxiliaryProviders: readonly AnalysisProvider[];
readonly identity: ProviderIdentity;
readonly initialRoute: SessionProviderRoute;
}
/** Resolve either the compatibility single-provider seam or a selectable set. */
/** Resolve one registry-selected deep provider and disjoint auxiliary families. */
export class SessionProviderRouter {
private constructor(
private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime,
private readonly registry: AnalysisProviderRegistry,
private readonly auxiliaryProviders: readonly AnalysisProvider[],
private readonly route: SessionProviderRoute,
) {}
/** Create routing for an embedding backed by one fixed provider or factory. */
static single(
provider: AnalysisProvider | AnalysisClientFactory,
options: {
readonly resolveAnalysisProfile?: (
target: BinaryTarget,
resolutionOptions?: AnalysisProfileResolutionOptions,
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
} = {},
): SessionProviderRouter {
const identity =
typeof provider === "function"
? { id: "unidentified", name: "Unidentified provider", version: null }
: provider.identity();
const capabilities =
typeof provider === "function"
? undefined
: capabilityMap(provider.capabilities());
const resolveProfile =
options.resolveAnalysisProfile ??
(typeof provider === "function" ||
provider.resolveAnalysisProfile === undefined
? () => Promise.resolve(ok({ profile: null, compatibility: {} }))
: (
target: BinaryTarget,
resolutionOptions?: AnalysisProfileResolutionOptions,
) =>
provider.resolveAnalysisProfile?.(target, resolutionOptions) ??
Promise.resolve(ok({ profile: null, compatibility: {} })));
return new SessionProviderRouter({
kind: "single",
provider,
identity,
capabilities,
resolveProfile,
});
}
/** Create selection-aware routing while keeping auxiliary families disjoint. */
static selectable(
registry: AnalysisProviderRegistry,
@@ -129,56 +58,16 @@ export class SessionProviderRouter {
`Deep and auxiliary providers both declare operation ${operation}`,
);
const initialRoute = selectableRoute(auxiliaryProviders, undefined);
return new SessionProviderRouter({
kind: "selectable",
return new SessionProviderRouter(
registry,
auxiliaryProviders: [...auxiliaryProviders],
identity:
identities.length === 0
? emptyProviderIdentity()
: compositeProviderIdentity(identities),
[...auxiliaryProviders],
initialRoute,
});
}
/** Compatibility identity covering every configured provider. */
configuredIdentity(): ProviderIdentity {
return structuredClone(this.runtime.identity);
}
/** Provider identities exposed through the flat 1.x compatibility field. */
providerIdentities(route: SessionProviderRoute): readonly ProviderIdentity[] {
if (this.runtime.kind === "single") {
if (route.capabilities === undefined) return [route.identity];
return uniqueProviderIdentities(
[...route.capabilities.values()].map(({ provider }) => provider),
);
}
const selected = route.binding?.identity;
return uniqueProviderIdentities([
...this.runtime.auxiliaryProviders.map((provider) => provider.identity()),
...this.runtime.registry
.identities()
.map((identity) =>
identity.id === selected?.id ? selected : identity,
),
]);
);
}
/** Target-free routes and discovery metadata. */
initialRoute(): SessionProviderRoute {
if (this.runtime.kind === "selectable") return this.runtime.initialRoute;
const runtime = this.runtime;
return {
identity: structuredClone(runtime.identity),
capabilities: runtime.capabilities,
profile: null,
compatibility: {},
binding: null,
selection: undefined,
createClient: (target, context) =>
createSingleProviderClient(runtime, target, undefined, context),
};
return this.route;
}
/** Resolve target routes before any provider client is created. */
@@ -188,64 +77,21 @@ export class SessionProviderRouter {
signal?: AbortSignal,
): Promise<Result<SessionProviderRoute, AnalysisError>> {
const resolutionOptions = signal === undefined ? undefined : { signal };
if (this.runtime.kind === "selectable") {
const selected = await this.runtime.registry.select(
target,
providerId,
resolutionOptions,
);
return selected.ok
? ok(selectableRoute(this.runtime.auxiliaryProviders, selected.value))
: selected;
}
const runtime = this.runtime;
if (
providerId !== undefined &&
providerId !== "auto" &&
providerId !== runtime.identity.id
)
return err(
new ProviderSelectionError({
reason: "unknown_provider",
requestedProviderId: providerId,
candidateIds: [runtime.identity.id],
}),
);
const resolved = await waitForAbortable(
runtime.resolveProfile(target, resolutionOptions),
signal,
const selected = await this.registry.select(
target,
providerId,
resolutionOptions,
);
if (resolved === ABORTED)
return err(new AnalysisCancelledError("open_binary"));
if (!resolved.ok) return resolved;
const normalized = normalizeProfileResolution(
resolved.value,
runtime.identity.id,
);
if (!normalized.ok) return normalized;
return ok({
identity: structuredClone(runtime.identity),
capabilities: runtime.capabilities,
profile: normalized.value.profile,
compatibility: normalized.value.compatibility,
binding: null,
selection: undefined,
createClient: (openedTarget, context) =>
createSingleProviderClient(
runtime,
openedTarget,
normalized.value.profile ?? undefined,
context,
),
});
return selected.ok
? ok(selectableRoute(this.auxiliaryProviders, selected.value))
: selected;
}
/** Candidate status authoritative for the active or target-free route. */
candidateStatuses(
route: SessionProviderRoute,
): readonly AnalysisProviderCandidateStatus[] {
if (this.runtime.kind === "single") return [];
return route.selection?.candidates ?? this.runtime.registry.candidates();
return route.selection?.candidates ?? this.registry.candidates();
}
/** Produce exact candidate rejections for an intentionally unbound route. */
@@ -254,15 +100,12 @@ export class SessionProviderRouter {
route: SessionProviderRoute,
): ProviderSelectionError | undefined {
if (
this.runtime.kind !== "selectable" ||
route.binding !== null ||
route.selection === undefined
route.selection === undefined ||
!this.registry.declaredOperations().includes(operation)
)
return undefined;
return this.runtime.registry.unboundOperationError(
operation,
route.selection,
);
return this.registry.unboundOperationError(operation, route.selection);
}
}
@@ -276,14 +119,17 @@ const selectableRoute = (
...(binding === null ? [] : [binding.provider]),
];
const provider =
providers.length === 0 ? undefined : new CompositeProvider(providers);
binding === null && providers.length === 1
? providers[0]
: providers.length === 0
? undefined
: new CompositeProvider(providers);
const identity = provider?.identity() ?? emptyProviderIdentity();
const capabilities = capabilityMap(provider?.capabilities() ?? []);
return {
identity,
capabilities,
profile: binding?.profile ?? null,
compatibility: structuredClone(binding?.compatibility ?? {}),
binding,
selection,
createClient: (target, context) =>
@@ -292,16 +138,6 @@ const selectableRoute = (
};
};
const createSingleProviderClient = (
runtime: SingleProviderRuntime,
target: BinaryTarget,
profile: AnalysisProfileCommitment | undefined,
context: AnalysisClientContext,
): AnalysisClient =>
typeof runtime.provider === "function"
? runtime.provider(target, profile, context)
: runtime.provider.createClient(target, profile, context);
const emptyClient = (identity: ProviderIdentity): AnalysisClient => ({
execute: (operation) =>
operation === "health"
@@ -324,7 +160,7 @@ const emptyClient = (identity: ProviderIdentity): AnalysisClient => ({
),
),
),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
});
const emptyProviderIdentity = (): ProviderIdentity => ({
@@ -338,13 +174,6 @@ const capabilityMap = (
): ReadonlyMap<string, CapabilityDescriptor> =>
new Map(capabilities.map((descriptor) => [descriptor.operation, descriptor]));
const uniqueProviderIdentities = (
identities: readonly ProviderIdentity[],
): readonly ProviderIdentity[] =>
[...new Map(identities.map((identity) => [identity.id, identity])).values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map((identity) => structuredClone(identity));
const assertDisjoint = (
providers: readonly AnalysisProvider[],
): ReadonlySet<string> => {
@@ -370,24 +199,3 @@ const assertUniqueProviderIds = (
ids.add(identity.id);
}
};
const normalizeProfileResolution = (
resolution: AnalysisProfileResolution,
providerId: string,
): Result<AnalysisProfileResolution, ProviderAdapterError> => {
try {
return ok({
profile:
resolution.profile === null
? null
: analysisProfileSchema.parse(resolution.profile),
compatibility: jsonObjectSchema.parse(resolution.compatibility),
});
} catch (cause: unknown) {
return err(
new ProviderAdapterError(providerId, "resolve_analysis_profile", {
cause,
}),
);
}
};