feat(ai): compat entrypoint, core-only root barrel (phase 5)

The root barrel is now core-only and side-effect free: types,
createModels/createProvider, auth substrate, lazyStream/lazyApi, faux,
utils. Generated catalogs, api-registry, env-api-keys, images, global
stream functions, and per-API lazy wrappers leave the root.

New @earendil-works/pi-ai/compat preserves the old surface verbatim as
a strict superset of the root: api-dispatch stream/complete with env
key injection, the builtin registration side effect (skip-if-present so
it cannot clobber earlier overrides), deprecated getModel/getModels/
getProviders aliases of the new getBuiltin* reads in providers/all,
lazy api wrappers + setBedrockProviderModule, and image generation.
Compat dies with the coding-agent ModelManager migration.

Packaging: exports map gains ./compat, ./providers/*, ./api/*;
sideEffects array lists only the effectful modules.

Old-global imports across agent/coding-agent/examples and pi-ai tests
switch to /compat (path-only; compat is a superset). The coding-agent
extension loader resolves the pi-ai ROOT specifier to compat, so
existing user extensions using the old global API keep working at
runtime until compat is removed. vitest configs alias /compat to src;
browser smoke imports old globals from /compat.
This commit is contained in:
Mario Zechner
2026-06-10 21:17:12 +02:00
parent 4d5c015820
commit 8a0903ebf2
116 changed files with 316 additions and 261 deletions
+17
View File
@@ -5,11 +5,28 @@
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"sideEffects": [
"./dist/compat.js",
"./dist/images.js",
"./dist/providers/images/register-builtins.js"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./compat": {
"types": "./dist/compat.d.ts",
"import": "./dist/compat.js"
},
"./providers/*": {
"types": "./dist/providers/*.d.ts",
"import": "./dist/providers/*.js"
},
"./api/*": {
"types": "./dist/api/*.d.ts",
"import": "./dist/api/*.js"
},
"./anthropic": {
"types": "./dist/api/anthropic-messages.d.ts",
"import": "./dist/api/anthropic-messages.js"
@@ -1,3 +1,32 @@
/**
* Temporary compatibility entrypoint preserving the old global pi-ai API
* surface: api-dispatch `stream()`/`complete()` with env API key injection,
* the api-registry, generated catalog reads (`getModel`/`getModels`/
* `getProviders`), per-API lazy stream wrappers, and image generation.
*
* Existing apps switch imports from "@earendil-works/pi-ai" to
* "@earendil-works/pi-ai/compat" unchanged; new code uses `createModels()`
* and the provider factories. This module is deleted with the coding-agent
* ModelManager migration.
*/
export * from "./api/anthropic-messages.lazy.ts";
export * from "./api/azure-openai-responses.lazy.ts";
export * from "./api/bedrock-converse-stream.lazy.ts";
export * from "./api/google-generative-ai.lazy.ts";
export * from "./api/google-vertex.lazy.ts";
export * from "./api/mistral-conversations.lazy.ts";
export * from "./api/openai-codex-responses.lazy.ts";
export * from "./api/openai-completions.lazy.ts";
export * from "./api/openai-responses.lazy.ts";
export * from "./api-registry.ts";
export * from "./env-api-keys.ts";
export * from "./image-models.ts";
export * from "./images.ts";
export * from "./images-api-registry.ts";
export * from "./index.ts";
export * from "./providers/images/register-builtins.ts";
import { anthropicMessagesApi } from "./api/anthropic-messages.lazy.ts";
import { azureOpenAIResponsesApi } from "./api/azure-openai-responses.lazy.ts";
import { bedrockConverseStreamApi } from "./api/bedrock-converse-stream.lazy.ts";
@@ -9,6 +38,7 @@ import { openAICompletionsApi } from "./api/openai-completions.lazy.ts";
import { openAIResponsesApi } from "./api/openai-responses.lazy.ts";
import { clearApiProviders, getApiProvider, registerApiProvider } from "./api-registry.ts";
import { getEnvApiKey } from "./env-api-keys.ts";
import { getBuiltinModel, getBuiltinModels, getBuiltinProviders } from "./providers/all.ts";
import type {
Api,
AssistantMessage,
@@ -21,7 +51,14 @@ import type {
StreamOptions,
} from "./types.ts";
export { getEnvApiKey } from "./env-api-keys.ts";
/** @deprecated Static catalog read. Use `getBuiltinModel` from "@earendil-works/pi-ai/providers/all" or `Models.getModel()`. */
export const getModel = getBuiltinModel;
/** @deprecated Static catalog read. Use `getBuiltinModels` from "@earendil-works/pi-ai/providers/all" or `Models.getModels()`. */
export const getModels = getBuiltinModels;
/** @deprecated Static catalog read. Use `getBuiltinProviders` from "@earendil-works/pi-ai/providers/all" or `Models.getProviders()`. */
export const getProviders = getBuiltinProviders;
const BUILTIN_APIS: [Api, ProviderStreams][] = [
["anthropic-messages", anthropicMessagesApi()],
@@ -35,8 +72,14 @@ const BUILTIN_APIS: [Api, ProviderStreams][] = [
["bedrock-converse-stream", bedrockConverseStreamApi()],
];
/**
* Registers the builtin API implementations into the api-registry without
* clobbering existing entries: compat may load after a test or extension has
* already registered an override for a builtin api id.
*/
export function registerBuiltInApiProviders(): void {
for (const [api, streams] of BUILTIN_APIS) {
if (getApiProvider(api)) continue;
registerApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });
}
}
+5 -16
View File
@@ -1,40 +1,29 @@
export type { Static, TSchema } from "typebox";
export { Type } from "typebox";
export * from "./api/anthropic-messages.lazy.ts";
// Core only, side-effect free: no generated catalogs, no provider factories,
// no api-registry, no OAuth implementations, no compat. Provider factories
// live under "@earendil-works/pi-ai/providers/*", API implementations under
// "@earendil-works/pi-ai/api/*", the old global API under
// "@earendil-works/pi-ai/compat".
export type { AnthropicEffort, AnthropicOptions, AnthropicThinkingDisplay } from "./api/anthropic-messages.ts";
export * from "./api/azure-openai-responses.lazy.ts";
export type { AzureOpenAIResponsesOptions } from "./api/azure-openai-responses.ts";
export * from "./api/bedrock-converse-stream.lazy.ts";
export type { BedrockOptions, BedrockThinkingDisplay } from "./api/bedrock-converse-stream.ts";
export * from "./api/google-generative-ai.lazy.ts";
export type { GoogleOptions } from "./api/google-generative-ai.ts";
export type { GoogleThinkingLevel } from "./api/google-shared.ts";
export * from "./api/google-vertex.lazy.ts";
export type { GoogleVertexOptions } from "./api/google-vertex.ts";
export * from "./api/lazy.ts";
export * from "./api/mistral-conversations.lazy.ts";
export type { MistralOptions } from "./api/mistral-conversations.ts";
export * from "./api/openai-codex-responses.lazy.ts";
export type { OpenAICodexResponsesOptions, OpenAICodexWebSocketDebugStats } from "./api/openai-codex-responses.ts";
export * from "./api/openai-completions.lazy.ts";
export type { OpenAICompletionsOptions } from "./api/openai-completions.ts";
export * from "./api/openai-responses.lazy.ts";
export type { OpenAIResponsesOptions } from "./api/openai-responses.ts";
export * from "./api-registry.ts";
export * from "./auth/context.ts";
export * from "./auth/credential-store.ts";
export * from "./auth/helpers.ts";
export * from "./auth/types.ts";
export * from "./env-api-keys.ts";
export * from "./image-models.ts";
export * from "./images.ts";
export * from "./images-api-registry.ts";
export * from "./models.ts";
export * from "./providers/faux.ts";
export * from "./providers/images/register-builtins.ts";
export * from "./session-resources.ts";
export * from "./stream.ts";
export * from "./types.ts";
export * from "./utils/diagnostics.ts";
export * from "./utils/event-stream.ts";
-37
View File
@@ -12,14 +12,12 @@ import type {
OAuthCredential,
ProviderAuth,
} from "./auth/types.ts";
import { MODELS } from "./models.generated.ts";
import type {
Api,
ApiStreamOptions,
AssistantMessage,
AssistantMessageEventStream,
Context,
KnownProvider,
Model,
ModelThinkingLevel,
ProviderStreams,
@@ -421,41 +419,6 @@ export function hasApi<TApi extends Api>(model: Model<Api>, api: TApi): model is
return model.api === api;
}
const modelRegistry: Map<string, Map<string, Model<Api>>> = new Map();
// Initialize registry from MODELS on module load
for (const [provider, models] of Object.entries(MODELS)) {
const providerModels = new Map<string, Model<Api>>();
for (const [id, model] of Object.entries(models)) {
providerModels.set(id, model as Model<Api>);
}
modelRegistry.set(provider, providerModels);
}
type ModelApi<
TProvider extends KnownProvider,
TModelId extends keyof (typeof MODELS)[TProvider],
> = (typeof MODELS)[TProvider][TModelId] extends { api: infer TApi } ? (TApi extends Api ? TApi : never) : never;
export function getModel<TProvider extends KnownProvider, TModelId extends keyof (typeof MODELS)[TProvider]>(
provider: TProvider,
modelId: TModelId,
): Model<ModelApi<TProvider, TModelId>> {
const providerModels = modelRegistry.get(provider);
return providerModels?.get(modelId as string) as Model<ModelApi<TProvider, TModelId>>;
}
export function getProviders(): KnownProvider[] {
return Array.from(modelRegistry.keys()) as KnownProvider[];
}
export function getModels<TProvider extends KnownProvider>(
provider: TProvider,
): Model<ModelApi<TProvider, keyof (typeof MODELS)[TProvider]>>[] {
const models = modelRegistry.get(provider);
return models ? (Array.from(models.values()) as Model<ModelApi<TProvider, keyof (typeof MODELS)[TProvider]>>[]) : [];
}
export function calculateCost<TApi extends Api>(model: Model<TApi>, usage: Usage): Usage["cost"] {
usage.cost.input = (model.cost.input / 1000000) * usage.input;
usage.cost.output = (model.cost.output / 1000000) * usage.output;
+28 -5
View File
@@ -1,4 +1,6 @@
import { MODELS } from "../models.generated.ts";
import { type CreateModelsOptions, createModels, type MutableModels, type Provider } from "../models.ts";
import type { Api, KnownProvider, Model } from "../types.ts";
import { amazonBedrockProvider } from "./amazon-bedrock.ts";
import { antLingProvider } from "./ant-ling.ts";
import { anthropicProvider } from "./anthropic.ts";
@@ -35,11 +37,32 @@ import { xiaomiTokenPlanSgpProvider } from "./xiaomi-token-plan-sgp.ts";
import { zaiProvider } from "./zai.ts";
import { zaiCodingCnProvider } from "./zai-coding-cn.ts";
export {
getModel as getBuiltinModel,
getModels as getBuiltinModels,
getProviders as getBuiltinProviders,
} from "../models.ts";
type BuiltinModelApi<
TProvider extends KnownProvider,
TModelId extends keyof (typeof MODELS)[TProvider],
> = (typeof MODELS)[TProvider][TModelId] extends { api: infer TApi } ? (TApi extends Api ? TApi : never) : never;
/** Typed read of the generated built-in catalog. */
export function getBuiltinModel<TProvider extends KnownProvider, TModelId extends keyof (typeof MODELS)[TProvider]>(
provider: TProvider,
modelId: TModelId,
): Model<BuiltinModelApi<TProvider, TModelId>> {
const models = MODELS[provider] as Record<string, Model<Api>> | undefined;
return models?.[modelId as string] as Model<BuiltinModelApi<TProvider, TModelId>>;
}
export function getBuiltinProviders(): KnownProvider[] {
return Object.keys(MODELS) as KnownProvider[];
}
export function getBuiltinModels<TProvider extends KnownProvider>(
provider: TProvider,
): Model<BuiltinModelApi<TProvider, keyof (typeof MODELS)[TProvider]>>[] {
const models = MODELS[provider] as Record<string, Model<Api>> | undefined;
return models
? (Object.values(models) as Model<BuiltinModelApi<TProvider, keyof (typeof MODELS)[TProvider]>>[])
: [];
}
/** All built-in providers, freshly constructed. */
export function builtinProviders(): Provider[] {
@@ -3,7 +3,7 @@
*/
import type { OAuthAuth, OAuthCredential } from "../../auth/types.ts";
import { getModels } from "../../models.ts";
import { GITHUB_COPILOT_MODELS } from "../../providers/github-copilot.models.ts";
import type { Api, Model } from "../../types.ts";
import { pollOAuthDeviceCodeFlow } from "./device-code.ts";
import type { OAuthCredentials, OAuthDeviceCodeInfo, OAuthLoginCallbacks, OAuthProviderInterface } from "./types.ts";
@@ -274,7 +274,7 @@ async function enableAllGitHubCopilotModels(
enterpriseDomain?: string,
onProgress?: (model: string, success: boolean) => void,
): Promise<void> {
const models = getModels("github-copilot");
const models = Object.values(GITHUB_COPILOT_MODELS);
await Promise.all(
models.map(async (model) => {
const success = await enableGitHubCopilotModel(token, model.id, enterpriseDomain);
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete, stream } from "../src/stream.ts";
import { complete, getModel, stream } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModels, getProviders } from "../src/models.ts";
import { getModels, getProviders } from "../src/compat.ts";
import type { Api, Model } from "../src/types.ts";
const EXPECTED_CURRENT_ADAPTIVE_THINKING_MODELS = [
@@ -1,8 +1,7 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { complete, getModels, getProviders } from "../src/compat.ts";
import { getEnvApiKey } from "../src/env-api-keys.ts";
import { getModels, getProviders } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import type { Api, KnownProvider, Model, ProviderStreamOptions, Tool } from "../src/types.ts";
import { resolveApiKey } from "./oauth.ts";
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { streamSimple } from "../src/stream.ts";
import { streamSimple } from "../src/compat.ts";
import type { AssistantMessage, Context, Model } from "../src/types.ts";
interface AnthropicPayload {
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Context, Model, SimpleStreamOptions } from "../src/types.ts";
interface AnthropicThinkingPayload {
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import { complete, getModels, getProviders } from "../src/compat.ts";
import { getEnvApiKey } from "../src/env-api-keys.ts";
import { getModels, getProviders } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import type { Api, KnownProvider, Model, ProviderStreamOptions } from "../src/types.ts";
import { resolveApiKey } from "./oauth.ts";
+36 -1
View File
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { loginAnthropic, refreshAnthropicToken } from "../src/utils/oauth/anthropic.ts";
import type { AuthEvent, AuthPrompt } from "../src/auth/types.ts";
import { anthropicOAuth, loginAnthropic, refreshAnthropicToken } from "../src/utils/oauth/anthropic.ts";
function jsonResponse(body: unknown, status: number = 200): Response {
return new Response(JSON.stringify(body), {
@@ -96,4 +97,38 @@ describe.sequential("Anthropic OAuth", () => {
expect(credentials.refresh).toBe("new-refresh-token");
expect(fetchMock).toHaveBeenCalledOnce();
});
it("anthropicOAuth.login resolves through the manual_code prompt and aborts it after settling", async () => {
const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
const url = typeof input === "string" ? input : String(input);
if (url.includes("/oauth/token")) {
return jsonResponse({ access_token: "access", refresh_token: "refresh", expires_in: 3600 });
}
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const events: AuthEvent[] = [];
const prompts: AuthPrompt[] = [];
let manualSignal: AbortSignal | undefined;
const credential = await anthropicOAuth.login({
notify: (event) => events.push(event),
prompt: async (prompt) => {
prompts.push(prompt);
if (prompt.type === "manual_code") {
manualSignal = prompt.signal;
return "the-code";
}
throw new Error(`Unexpected prompt: ${prompt.type}`);
},
});
expect(credential.type).toBe("oauth");
expect(credential.access).toBe("access");
expect(events.some((e) => e.type === "auth_url")).toBe(true);
expect(prompts.some((p) => p.type === "manual_code")).toBe(true);
// the prompt's signal is aborted once login settles, so UIs can dismiss it
expect(manualSignal?.aborted).toBe(true);
});
});
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
interface AnthropicThinkingPayload {
@@ -2,7 +2,7 @@ import type Anthropic from "@anthropic-ai/sdk";
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { stream as streamAnthropic } from "../src/api/anthropic-messages.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, ToolCall } from "../src/types.ts";
function createSseResponse(events: Array<{ event: string; data: string }>): Response {
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Context, Model, SimpleStreamOptions } from "../src/types.ts";
interface AnthropicTemperaturePayload {
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Context, Model, SimpleStreamOptions } from "../src/types.ts";
interface AnthropicThinkingPayload {
@@ -1,7 +1,6 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { stream } from "../src/stream.ts";
import { getModel, stream } from "../src/compat.ts";
import type { Context, Tool } from "../src/types.ts";
import { resolveApiKey } from "./oauth.ts";
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { stream as streamAzureOpenAIResponses } from "../src/api/azure-openai-responses.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
interface CapturedAzureClientOptions {
@@ -45,7 +45,7 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => {
});
import { stream as streamBedrock } from "../src/api/bedrock-converse-stream.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, Message } from "../src/types.ts";
const baseModel = getModel("amazon-bedrock", "us.anthropic.claude-sonnet-4-5-20250929-v1:0");
@@ -53,7 +53,7 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => {
import type { BedrockOptions } from "../src/api/bedrock-converse-stream.ts";
import { stream as streamBedrock, streamSimple as streamSimpleBedrock } from "../src/api/bedrock-converse-stream.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
const context: Context = {
@@ -45,7 +45,7 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => {
});
import { stream as streamBedrock } from "../src/api/bedrock-converse-stream.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
const context: Context = {
+1 -2
View File
@@ -17,8 +17,7 @@
*/
import { describe, expect, it } from "vitest";
import { getModels } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModels } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
import { hasBedrockCredentials } from "./bedrock-utils.ts";
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { type BedrockOptions, stream as streamBedrock } from "../src/api/bedrock-converse-stream.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
import { hasBedrockCredentials } from "./bedrock-utils.ts";
+1 -2
View File
@@ -2,8 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { stream as streamAnthropic } from "../src/api/anthropic-messages.ts";
import { stream as streamOpenAICompletions } from "../src/api/openai-completions.ts";
import { stream as streamOpenAIResponses } from "../src/api/openai-responses.ts";
import { getModel } from "../src/models.ts";
import { stream } from "../src/stream.ts";
import { getModel, stream } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
class PayloadCaptured extends Error {
@@ -16,7 +16,7 @@ import {
resetOpenAICodexWebSocketDebugStats,
stream as streamOpenAICodexResponses,
} from "../src/api/openai-codex-responses.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { AssistantMessage, Context, Message, Model, Tool, ToolResultMessage, Transport } from "../src/types.ts";
type ThinkingLevel = "minimal" | "low" | "medium" | "high" | "xhigh";
+1 -2
View File
@@ -14,8 +14,7 @@
import type { ChildProcess } from "child_process";
import { execSync, spawn } from "child_process";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getModel, getModels } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel, getModels } from "../src/compat.ts";
import type { AssistantMessage, Context, Model, Usage } from "../src/types.ts";
import { isContextOverflow } from "../src/utils/overflow.ts";
import { hasAzureOpenAICredentials } from "./azure-utils.ts";
@@ -25,8 +25,7 @@
import { writeFileSync } from "fs";
import { Type } from "typebox";
import { beforeAll, describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { completeSimple, getEnvApiKey } from "../src/stream.ts";
import { completeSimple, getEnvApiKey, getModel } from "../src/compat.ts";
import type { Api, AssistantMessage, Message, Model, Tool, ToolResultMessage } from "../src/types.ts";
import { hasAzureOpenAICredentials } from "./azure-utils.ts";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.ts";
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Api, AssistantMessage, Context, Model, StreamOptions, UserMessage } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
+1 -1
View File
@@ -8,7 +8,7 @@ import {
registerFauxProvider,
stream,
Type,
} from "../src/index.ts";
} from "../src/compat.ts";
import type { AssistantMessageEvent, Context } from "../src/types.ts";
async function collectEvents(streamResult: ReturnType<typeof stream>): Promise<AssistantMessageEvent[]> {
+1 -1
View File
@@ -3,8 +3,8 @@ import type { AddressInfo } from "node:net";
import { Type } from "typebox";
import { afterEach, describe, expect, it } from "vitest";
import { stream as streamAnthropic } from "../src/api/anthropic-messages.ts";
import { getModel, getModels } from "../src/compat.ts";
import { findEnvKeys, getEnvApiKey } from "../src/env-api-keys.ts";
import { getModel, getModels } from "../src/models.ts";
import type { Context, Model, Tool } from "../src/types.ts";
const originalFireworksApiKey = process.env.FIREWORKS_API_KEY;
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { stream as streamAnthropic } from "../src/api/anthropic-messages.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
const mockState = vi.hoisted(() => ({
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Api, Context, Model, SimpleStreamOptions } from "../src/types.ts";
type SimpleOptionsWithExtras = SimpleStreamOptions & Record<string, unknown>;
@@ -46,7 +46,7 @@ vi.mock("@google/genai", () => {
});
import { stream as streamGoogleVertex } from "../src/api/google-vertex.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
const model = getModel("google-vertex", "gemini-3-flash-preview");
+2 -2
View File
@@ -2,8 +2,8 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import type { Api, Context, Model, Tool, ToolResultMessage } from "../src/index.ts";
import { complete, getModel } from "../src/index.ts";
import type { Api, Context, Model, Tool, ToolResultMessage } from "../src/compat.ts";
import { complete, getModel } from "../src/compat.ts";
import type { StreamOptions } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
@@ -1,8 +1,7 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { completeSimple, getModel } from "../src/compat.ts";
import { getEnvApiKey } from "../src/env-api-keys.ts";
import { getModel } from "../src/models.ts";
import { completeSimple } from "../src/stream.ts";
import type { Api, Context, Model, StopReason, Tool, ToolCall, ToolResultMessage } from "../src/types.ts";
import { StringEnum } from "../src/utils/typebox-helpers.ts";
import { hasBedrockCredentials } from "./bedrock-utils.ts";
+13 -3
View File
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const aiEntryUrl = new URL("../src/index.ts", import.meta.url).href;
const compatEntryUrl = new URL("../src/compat.ts", import.meta.url).href;
const providersAllUrl = new URL("../src/providers/all.ts", import.meta.url).href;
const SDK_SPECIFIERS = [
@@ -76,8 +77,16 @@ describe("lazy provider module loading", () => {
expect(result.loadedSpecifiers).toEqual([]);
});
it("does not load provider SDKs when importing the compat entrypoint", () => {
const result = runProbe(`
await import(${JSON.stringify(compatEntryUrl)});
`);
expect(result.loadedSpecifiers).toEqual([]);
});
it("loads only the Anthropic SDK when streaming through the lazy API wrapper", () => {
const result = runProbe(`
const compat = await import(${JSON.stringify(compatEntryUrl)});
const model = {
id: "claude-sonnet-4-6",
name: "Claude Sonnet 4",
@@ -91,7 +100,7 @@ describe("lazy provider module loading", () => {
maxTokens: 8192,
};
const context = { messages: [{ role: "user", content: "hi" }] };
await mod.anthropicMessagesApi().streamSimple(model, context).result();
await compat.anthropicMessagesApi().streamSimple(model, context).result();
`);
expect(result.loadedSpecifiers).toEqual(["@anthropic-ai/sdk"]);
@@ -99,9 +108,10 @@ describe("lazy provider module loading", () => {
it("loads only the Anthropic SDK when dispatching through streamSimple", () => {
const result = runProbe(`
const model = mod.getModel("anthropic", "claude-sonnet-4-6");
const compat = await import(${JSON.stringify(compatEntryUrl)});
const model = compat.getModel("anthropic", "claude-sonnet-4-6");
const context = { messages: [{ role: "user", content: "hi" }] };
await mod.streamSimple(model, context).result();
await compat.streamSimple(model, context).result();
`);
expect(result.loadedSpecifiers).toEqual(["@anthropic-ai/sdk"]);
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
import type { Context, Model, SimpleStreamOptions } from "../src/types.ts";
interface MistralPayload {
+1 -2
View File
@@ -1,7 +1,6 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
interface MistralToolPayload {
-35
View File
@@ -1,6 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { InMemoryCredentialStore } from "../src/auth/credential-store.ts";
import type { AuthEvent, AuthPrompt } from "../src/auth/types.ts";
import { createModels } from "../src/models.ts";
import { anthropicProvider } from "../src/providers/anthropic.ts";
import { githubCopilotProvider } from "../src/providers/github-copilot.ts";
@@ -86,40 +85,6 @@ describe.sequential("OAuthAuth adapters", () => {
expect(refreshed.enterpriseUrl).toBe("company.ghe.com");
expect(fetchedUrls[0]).toContain("api.company.ghe.com");
});
it("anthropic login resolves through the manual_code prompt and aborts it after settling", async () => {
const fetchMock = vi.fn(async (input: unknown) => {
const url = typeof input === "string" ? input : String(input);
if (url.includes("/oauth/token")) {
return jsonResponse({ access_token: "access", refresh_token: "refresh", expires_in: 3600 });
}
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const events: AuthEvent[] = [];
const prompts: AuthPrompt[] = [];
let manualSignal: AbortSignal | undefined;
const credential = await anthropicOAuth.login({
notify: (event) => events.push(event),
prompt: async (prompt) => {
prompts.push(prompt);
if (prompt.type === "manual_code") {
manualSignal = prompt.signal;
return "the-code";
}
throw new Error(`Unexpected prompt: ${prompt.type}`);
},
});
expect(credential.type).toBe("oauth");
expect(credential.access).toBe("access");
expect(events.some((e) => e.type === "auth_url")).toBe(true);
expect(prompts.some((p) => p.type === "manual_code")).toBe(true);
// the prompt's signal is aborted once login settles, so UIs can dismiss it
expect(manualSignal?.aborted).toBe(true);
});
});
describe("OAuth through Models.getAuth (lazy load chain)", () => {
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
import { resolveApiKey } from "./oauth.ts";
@@ -1,7 +1,7 @@
import { Type } from "typebox";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { stream as streamOpenAICompletions } from "../src/api/openai-completions.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Model } from "../src/types.ts";
interface CacheControl {
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getModel } from "../src/models.ts";
import { streamSimple } from "../src/stream.ts";
import { getModel, streamSimple } from "../src/compat.ts";
// Empty tools arrays must NOT be serialized as `tools: []` — some OpenAI-compatible
// backends (e.g. DashScope / Aliyun Qwen via compatible-mode) reject the request with
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { stream as streamOpenAICompletions } from "../src/api/openai-completions.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Model } from "../src/types.ts";
interface FakeOpenAIClientOptions {
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { complete } from "../src/stream.ts";
import { complete } from "../src/compat.ts";
import type { Model } from "../src/types.ts";
// Router/virtual ids (e.g. OpenRouter `auto`) keep `model` pinned to the
@@ -1,8 +1,7 @@
import { Type } from "typebox";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { convertMessages } from "../src/api/openai-completions.ts";
import { getModel } from "../src/models.ts";
import { stream, streamSimple } from "../src/stream.ts";
import { getModel, stream, streamSimple } from "../src/compat.ts";
import type { AssistantMessage, Model, Tool, ToolResultMessage } from "../src/types.ts";
const mockState = vi.hoisted(() => ({
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { convertMessages } from "../src/api/openai-completions.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type {
AssistantMessage,
Context,
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Context } from "../src/types.ts";
describe.skipIf(!process.env.OPENAI_API_KEY)("openai responses cache affinity e2e", () => {
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { stream as streamOpenAIResponses } from "../src/api/openai-responses.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { Model } from "../src/types.ts";
type CapturedHeaders = Headers | string[][] | Record<string, string | readonly string[]> | undefined;
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { convertResponsesMessages } from "../src/api/openai-responses-shared.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { AssistantMessage, Context, ToolResultMessage, Usage } from "../src/types.ts";
import { shortHash } from "../src/utils/hash.ts";
@@ -1,7 +1,7 @@
import type { ResponseOutputMessage } from "openai/resources/responses/responses.js";
import { describe, expect, it } from "vitest";
import { convertResponsesMessages } from "../src/api/openai-responses-shared.ts";
import { getModel } from "../src/models.ts";
import { getModel } from "../src/compat.ts";
import type { AssistantMessage, Context, Usage } from "../src/types.ts";
const usage: Usage = {
@@ -1,7 +1,6 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete, getEnvApiKey } from "../src/stream.ts";
import { complete, getEnvApiKey, getModel } from "../src/compat.ts";
import type { AssistantMessage, Context, Message, Tool, ToolCall } from "../src/types.ts";
const testToolSchema = Type.Object({
@@ -4,8 +4,8 @@ import { fileURLToPath } from "node:url";
import type { ResponseFunctionCallOutputItemList } from "openai/resources/responses/responses.js";
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import type { Api, Context, Model, StreamOptions, Tool, ToolResultMessage } from "../src/index.ts";
import { complete, getModel } from "../src/index.ts";
import type { Api, Context, Model, StreamOptions, Tool, ToolResultMessage } from "../src/compat.ts";
import { complete, getModel } from "../src/compat.ts";
import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
import { resolveApiKey } from "./oauth.ts";
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { completeSimple } from "../src/stream.ts";
import { completeSimple, getModel } from "../src/compat.ts";
function createLongSystemPrompt(): string {
const nonce = `${Date.now()}-${Math.random()}`;
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions } from "../src/types.ts";
import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
import { resolveApiKey } from "./oauth.ts";
+1 -2
View File
@@ -4,8 +4,7 @@ import { dirname, join } from "path";
import { Type } from "typebox";
import { fileURLToPath } from "url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete, stream } from "../src/stream.ts";
import { complete, getModel, stream } from "../src/compat.ts";
import type { Api, Context, ImageContent, Model, StreamOptions, Tool, ToolResultMessage } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel, getSupportedThinkingLevels } from "../src/models.ts";
import { getModel, getSupportedThinkingLevels } from "../src/compat.ts";
describe("getSupportedThinkingLevels", () => {
it("includes xhigh for Anthropic Opus 4.6 on anthropic-messages API", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { getModel } from "../src/compat.ts";
import { findEnvKeys, getEnvApiKey } from "../src/env-api-keys.ts";
import { getModel } from "../src/models.ts";
const originalTogetherApiKey = process.env.TOGETHER_API_KEY;
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel, getModels } from "../src/models.ts";
import { stream } from "../src/stream.ts";
import { getModel, getModels, stream } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
@@ -12,8 +12,7 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { completeSimple, getEnvApiKey } from "../src/stream.ts";
import { completeSimple, getEnvApiKey, getModel } from "../src/compat.ts";
import type { AssistantMessage, Message, Tool, ToolResultMessage } from "../src/types.ts";
import { resolveApiKey } from "./oauth.ts";
@@ -1,7 +1,6 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions, Tool } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
+1 -2
View File
@@ -13,8 +13,7 @@
*/
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions, Usage } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
+1 -2
View File
@@ -1,7 +1,6 @@
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { complete } from "../src/stream.ts";
import { complete, getModel } from "../src/compat.ts";
import type { Api, Context, Model, StreamOptions, ToolResultMessage } from "../src/types.ts";
type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
+1 -2
View File
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.ts";
import { stream } from "../src/stream.ts";
import { getModel, stream } from "../src/compat.ts";
import type { Context, Model } from "../src/types.ts";
function makeContext(): Context {
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getModel, getModels } from "../src/models.ts";
import { getModel, getModels } from "../src/compat.ts";
describe("Xiaomi MiMo models", () => {
it("keeps mimo-v2-flash on the API billing provider", () => {
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { completeSimple, getEnvApiKey, streamSimple } from "../src/stream.ts";
import { completeSimple, getEnvApiKey, streamSimple } from "../src/compat.ts";
import type { AssistantMessage, Context, Model } from "../src/types.ts";
const provider = "xiaomi-token-plan-ams";
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { complete } from "../src/compat.ts";
import { MODELS } from "../src/models.generated.ts";
import { complete } from "../src/stream.ts";
import type { Model } from "../src/types.ts";
describe.skipIf(!process.env.OPENCODE_API_KEY)("OpenCode Models Smoke Test", () => {