Files
openclaw/src/llm/env-api-keys.test.ts
Peter Steinberger 062f88e3e3 refactor: extract reusable AI runtime package (#99059)
* refactor: extract reusable AI runtime package

* refactor: complete AI provider relocation

* refactor: keep llm core internal

* refactor(ai): make @openclaw/ai self-contained with host policy ports

Move pure transport helpers (tool projections, strict-schema normalization,
prompt-cache boundary, stream guards, anthropic/openai compat, request
activity) from src into packages/ai; move utf16-slice into
normalization-core. Inject host policy (guarded fetch, redaction,
strict-tool defaults, diagnostics logging) through AiTransportHost with
inert library defaults installed by src/llm/stream.ts. Narrow the public
barrel to instance-scoped createApiRegistry/createLlmRuntime; the
process-default runtime moves behind internal/ and
registerBuiltInApiProviders takes an explicit registry. Delete the
src/llm/api-registry re-export facade.

* fix(ai): teach node, jiti, and vite resolvers the @openclaw/ai and utf16-slice subpaths

The workspace alias tables in root-alias.cjs, plugin-sdk-native-resolver,
sdk-alias, the shared vitest config, and the Control UI vite config only
knew @openclaw/llm-core; Node-side plugin loading resolved @openclaw/ai
through the pnpm symlink to the unbuilt dist (checks-node-compact CI
failures), and the Control UI build broke on the new
normalization-core/utf16-slice subpath.

* chore(ui): drop leftover service-worker debug logging

* build(release): ship @openclaw/ai with its own shrinkwrap and honest dependency set

packages/ai declares only its six real runtime deps (kysely, chalk, json5,
tslog, zod, fs-safe, and proxyline were never imported); orphaned root deps
removed. generate-npm-shrinkwrap now treats publishable packages/* like
publishable plugins so the AI tarball pins its transitive tree even though
workspace deps are omitted from the root shrinkwrap. knip learns the
package entry points; the tsdown dts neverBundle option moves to its
documented deps.dts home; the README documents the no-semver internal/*
contract and host ports.

* docs(ai): add minimal external-consumer example app

examples/ai-chat consumes only the public @openclaw/ai surface (built dist
via the workspace link): isolated runtime, built-in provider registration,
one streamed completion. Supports Anthropic/OpenAI via env keys and a
keyless local Ollama target; live-verified against Ollama.

* docs(ai): document the @openclaw/ai package and workspace shrinkwrap boundary

* chore(check): include examples/ in duplicate-scan targets

* fix: emit normalization package subpaths

* fix: complete AI package boundary artifacts

* fix: align AI package boundary contracts

* fix(ci): stabilize package release contracts

* test: align documentation contract checks

* test: keep cron docs guard aligned

* test: align restored docs contract guards

* test: follow upstream docs contracts

* docs: drop superseded talk wording
2026-07-05 01:56:40 -04:00

111 lines
3.9 KiB
TypeScript

// Covers API-key discovery from environment and key files.
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { captureEnv, withEnvAsync } from "../test-utils/env.js";
const envKeys = [
"GOOGLE_APPLICATION_CREDENTIALS",
"GOOGLE_CLOUD_LOCATION",
"GOOGLE_CLOUD_PROJECT",
"KIMI_API_KEY",
"KIMICODE_API_KEY",
"MOONSHOT_API_KEY",
] as const;
const originalEnv = captureEnv([...envKeys]);
const tempDirs: string[] = [];
afterEach(async () => {
vi.unstubAllGlobals();
originalEnv.restore();
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
vi.resetModules();
});
describe("getEnvApiKey", () => {
it("returns no env auth in browser contexts without process", async () => {
vi.resetModules();
const { findEnvKeys, getEnvApiKey } = await import("@openclaw/ai/internal/runtime");
vi.stubGlobal("process", undefined);
expect(findEnvKeys("openai")).toBeUndefined();
expect(getEnvApiKey("openai")).toBeUndefined();
expect(getEnvApiKey("google-vertex")).toBeUndefined();
expect(getEnvApiKey("amazon-bedrock")).toBeUndefined();
});
it("detects Google Vertex ADC credentials on the first synchronous lookup", async () => {
const dir = await mkdtemp(join(tmpdir(), "openclaw-vertex-adc-"));
tempDirs.push(dir);
const credentialsPath = join(dir, "application_default_credentials.json");
await writeFile(credentialsPath, "{}", "utf-8");
await withEnvAsync(
{
GOOGLE_APPLICATION_CREDENTIALS: credentialsPath,
GOOGLE_CLOUD_LOCATION: "us-central1",
GOOGLE_CLOUD_PROJECT: "vertex-project",
},
async () => {
vi.resetModules();
const { getEnvApiKey } = await import("@openclaw/ai/internal/runtime");
expect(getEnvApiKey("google-vertex")).toBe("<authenticated>");
},
);
});
it("detects canonical Moonshot and Kimi provider credentials", async () => {
await withEnvAsync(
{
MOONSHOT_API_KEY: "moonshot-key",
KIMI_API_KEY: "kimi-key",
KIMICODE_API_KEY: "kimicode-key",
},
async () => {
vi.resetModules();
const { findEnvKeys, getEnvApiKey } = await import("@openclaw/ai/internal/runtime");
expect(findEnvKeys("moonshot")).toEqual(["MOONSHOT_API_KEY", "KIMI_API_KEY"]);
expect(getEnvApiKey("moonshot")).toBe("moonshot-key");
expect(findEnvKeys("kimi")).toEqual(["KIMI_API_KEY", "KIMICODE_API_KEY"]);
expect(getEnvApiKey("kimi")).toBe("kimi-key");
expect(findEnvKeys("kimi-coding")).toEqual(["KIMI_API_KEY", "KIMICODE_API_KEY"]);
expect(getEnvApiKey("kimi-coding")).toBe("kimi-key");
},
);
});
it("falls back to alternate canonical Kimi env vars", async () => {
await withEnvAsync({ KIMICODE_API_KEY: "kimicode-key" }, async () => {
vi.resetModules();
const { findEnvKeys, getEnvApiKey } = await import("@openclaw/ai/internal/runtime");
expect(findEnvKeys("kimi")).toEqual(["KIMICODE_API_KEY"]);
expect(getEnvApiKey("kimi")).toBe("kimicode-key");
});
});
it("does not cache missing Google Vertex ADC credentials", async () => {
const dir = await mkdtemp(join(tmpdir(), "openclaw-vertex-adc-"));
tempDirs.push(dir);
const credentialsPath = join(dir, "application_default_credentials.json");
await withEnvAsync(
{
GOOGLE_APPLICATION_CREDENTIALS: credentialsPath,
GOOGLE_CLOUD_LOCATION: "us-central1",
GOOGLE_CLOUD_PROJECT: "vertex-project",
},
async () => {
vi.resetModules();
const { getEnvApiKey } = await import("@openclaw/ai/internal/runtime");
expect(getEnvApiKey("google-vertex")).toBeUndefined();
await writeFile(credentialsPath, "{}", "utf-8");
expect(getEnvApiKey("google-vertex")).toBe("<authenticated>");
},
);
});
});