Vendor OpenClaw source as Adolf fork baseline
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
This commit is contained in:
12
extensions/cloudflare-ai-gateway/README.md
Normal file
12
extensions/cloudflare-ai-gateway/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# OpenClaw Cloudflare AI Gateway Provider
|
||||
|
||||
Official OpenClaw provider plugin for Cloudflare AI Gateway.
|
||||
|
||||
Install from OpenClaw:
|
||||
|
||||
```bash
|
||||
openclaw plugins install @openclaw/cloudflare-ai-gateway-provider
|
||||
openclaw gateway restart
|
||||
```
|
||||
|
||||
See <https://docs.openclaw.ai/providers/cloudflare-ai-gateway> for setup and configuration.
|
||||
18
extensions/cloudflare-ai-gateway/api.ts
Normal file
18
extensions/cloudflare-ai-gateway/api.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Public Cloudflare AI Gateway provider helpers shared by onboarding, catalog,
|
||||
* and tests.
|
||||
*/
|
||||
export {
|
||||
buildCloudflareAiGatewayModelDefinition,
|
||||
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_ID,
|
||||
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
|
||||
CLOUDFLARE_AI_GATEWAY_PROVIDER_ID,
|
||||
resolveCloudflareAiGatewayBaseUrl,
|
||||
} from "./models.js";
|
||||
export { buildCloudflareAiGatewayCatalogProvider } from "./catalog-provider.js";
|
||||
|
||||
export {
|
||||
applyCloudflareAiGatewayConfig,
|
||||
applyCloudflareAiGatewayProviderConfig,
|
||||
buildCloudflareAiGatewayConfigPatch,
|
||||
} from "./onboard.js";
|
||||
81
extensions/cloudflare-ai-gateway/catalog-provider.ts
Normal file
81
extensions/cloudflare-ai-gateway/catalog-provider.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Builds runtime model catalog entries from stored Cloudflare AI Gateway auth
|
||||
* profiles.
|
||||
*/
|
||||
import {
|
||||
coerceSecretRef,
|
||||
resolveNonEnvSecretRefApiKeyMarker,
|
||||
} from "openclaw/plugin-sdk/provider-auth";
|
||||
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
||||
import {
|
||||
buildCloudflareAiGatewayModelDefinition,
|
||||
resolveCloudflareAiGatewayBaseUrl,
|
||||
} from "./models.js";
|
||||
|
||||
type CloudflareAiGatewayCredential =
|
||||
| {
|
||||
type?: string;
|
||||
keyRef?: unknown;
|
||||
key?: unknown;
|
||||
metadata?: {
|
||||
accountId?: unknown;
|
||||
gatewayId?: unknown;
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
function resolveCloudflareAiGatewayApiKey(cred: CloudflareAiGatewayCredential): string | undefined {
|
||||
if (!cred || cred.type !== "api_key") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const keyRef = coerceSecretRef(cred.keyRef);
|
||||
const keyRefId = normalizeOptionalString(keyRef?.id);
|
||||
if (keyRef && keyRefId) {
|
||||
return keyRef.source === "env" ? keyRefId : resolveNonEnvSecretRefApiKeyMarker(keyRef.source);
|
||||
}
|
||||
return normalizeOptionalString(cred.key);
|
||||
}
|
||||
|
||||
function resolveCloudflareAiGatewayMetadata(cred: CloudflareAiGatewayCredential): {
|
||||
accountId?: string;
|
||||
gatewayId?: string;
|
||||
} {
|
||||
if (!cred || cred.type !== "api_key") {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
accountId: normalizeOptionalString(cred.metadata?.accountId),
|
||||
gatewayId: normalizeOptionalString(cred.metadata?.gatewayId),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a provider catalog entry when credentials and Gateway metadata are
|
||||
* complete enough to construct an Anthropic-compatible base URL.
|
||||
*/
|
||||
export function buildCloudflareAiGatewayCatalogProvider(params: {
|
||||
credential: CloudflareAiGatewayCredential;
|
||||
envApiKey?: string;
|
||||
}) {
|
||||
const apiKey =
|
||||
normalizeOptionalString(params.envApiKey) ??
|
||||
resolveCloudflareAiGatewayApiKey(params.credential);
|
||||
if (!apiKey) {
|
||||
return null;
|
||||
}
|
||||
const { accountId, gatewayId } = resolveCloudflareAiGatewayMetadata(params.credential);
|
||||
if (!accountId || !gatewayId) {
|
||||
return null;
|
||||
}
|
||||
const baseUrl = resolveCloudflareAiGatewayBaseUrl({ accountId, gatewayId });
|
||||
if (!baseUrl) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
baseUrl,
|
||||
api: "anthropic-messages" as const,
|
||||
apiKey,
|
||||
models: [buildCloudflareAiGatewayModelDefinition()],
|
||||
};
|
||||
}
|
||||
61
extensions/cloudflare-ai-gateway/index.test.ts
Normal file
61
extensions/cloudflare-ai-gateway/index.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Cloudflare Ai Gateway tests cover index plugin behavior.
|
||||
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
|
||||
import { capturePluginRegistration } from "openclaw/plugin-sdk/plugin-test-runtime";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import plugin from "./index.js";
|
||||
|
||||
function registerProvider() {
|
||||
const captured = capturePluginRegistration(plugin);
|
||||
const provider = captured.providers[0];
|
||||
if (!provider) {
|
||||
throw new Error("expected Cloudflare AI Gateway provider");
|
||||
}
|
||||
expect(provider.id).toBe("cloudflare-ai-gateway");
|
||||
return provider;
|
||||
}
|
||||
|
||||
describe("cloudflare-ai-gateway plugin", () => {
|
||||
it("registers a stream wrapper that strips Anthropic thinking assistant prefill", () => {
|
||||
const provider = registerProvider();
|
||||
expect(provider.wrapStreamFn).toBeTypeOf("function");
|
||||
if (!provider.wrapStreamFn) {
|
||||
throw new Error("expected Cloudflare AI Gateway stream wrapper");
|
||||
}
|
||||
|
||||
let capturedPayload: Record<string, unknown> | undefined;
|
||||
const baseStreamFn: StreamFn = (_model, _context, options) => {
|
||||
const payload: Record<string, unknown> = {
|
||||
thinking: { type: "enabled", budget_tokens: 1024 },
|
||||
messages: [
|
||||
{ role: "user", content: "Return JSON." },
|
||||
{ role: "assistant", content: "{" },
|
||||
],
|
||||
};
|
||||
options?.onPayload?.(payload as never, _model as never);
|
||||
capturedPayload = payload;
|
||||
return {} as ReturnType<StreamFn>;
|
||||
};
|
||||
|
||||
const wrapped = provider.wrapStreamFn({
|
||||
provider: "cloudflare-ai-gateway",
|
||||
modelId: "claude-sonnet-4-6",
|
||||
model: { api: "anthropic-messages" },
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
expect(wrapped).toBeTypeOf("function");
|
||||
if (!wrapped) {
|
||||
throw new Error("expected Cloudflare AI Gateway wrapped stream function");
|
||||
}
|
||||
|
||||
void wrapped(
|
||||
{ provider: "cloudflare-ai-gateway", api: "anthropic-messages" } as never,
|
||||
{} as never,
|
||||
{},
|
||||
);
|
||||
|
||||
if (!capturedPayload) {
|
||||
throw new Error("expected Cloudflare AI Gateway payload capture");
|
||||
}
|
||||
expect(capturedPayload.messages).toEqual([{ role: "user", content: "Return JSON." }]);
|
||||
});
|
||||
});
|
||||
241
extensions/cloudflare-ai-gateway/index.ts
Normal file
241
extensions/cloudflare-ai-gateway/index.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* Bundled provider plugin entry for Cloudflare AI Gateway setup, catalog
|
||||
* discovery, failover classification, and stream wrapping.
|
||||
*/
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import {
|
||||
applyAuthProfileConfig,
|
||||
buildApiKeyCredential,
|
||||
ensureApiKeyFromOptionEnvOrPrompt,
|
||||
ensureAuthProfileStore,
|
||||
listProfilesForProvider,
|
||||
normalizeApiKeyInput,
|
||||
normalizeOptionalSecretInput,
|
||||
upsertAuthProfileWithLock,
|
||||
validateApiKeyInput,
|
||||
} from "openclaw/plugin-sdk/provider-auth";
|
||||
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
||||
import { buildCloudflareAiGatewayCatalogProvider } from "./catalog-provider.js";
|
||||
import { CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF } from "./models.js";
|
||||
import { applyCloudflareAiGatewayConfig, buildCloudflareAiGatewayConfigPatch } from "./onboard.js";
|
||||
import { wrapCloudflareAiGatewayProviderStream } from "./stream-wrappers.js";
|
||||
|
||||
const PROVIDER_ID = "cloudflare-ai-gateway";
|
||||
const PROVIDER_ENV_VAR = "CLOUDFLARE_AI_GATEWAY_API_KEY";
|
||||
const PROFILE_ID = "cloudflare-ai-gateway:default";
|
||||
type UpsertAuthProfileParams = Parameters<typeof upsertAuthProfileWithLock>[0];
|
||||
|
||||
async function upsertAuthProfileWithLockOrThrow(params: UpsertAuthProfileParams): Promise<void> {
|
||||
const updated = await upsertAuthProfileWithLock(params);
|
||||
if (!updated) {
|
||||
throw new Error(
|
||||
"Failed to update auth profile store; the auth store lock may be busy. Wait a moment and retry.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function readRequiredTextInput(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
async function resolveCloudflareGatewayMetadataInteractive(ctx: {
|
||||
accountId?: string;
|
||||
gatewayId?: string;
|
||||
prompter: {
|
||||
text: (params: {
|
||||
message: string;
|
||||
validate?: (value: unknown) => string | undefined;
|
||||
}) => Promise<unknown>;
|
||||
};
|
||||
}) {
|
||||
let accountId = normalizeOptionalString(ctx.accountId) ?? "";
|
||||
let gatewayId = normalizeOptionalString(ctx.gatewayId) ?? "";
|
||||
if (!accountId) {
|
||||
const value = await ctx.prompter.text({
|
||||
message: "Enter Cloudflare Account ID",
|
||||
validate: (val) => (readRequiredTextInput(val) ? undefined : "Account ID is required"),
|
||||
});
|
||||
accountId = readRequiredTextInput(value);
|
||||
}
|
||||
if (!gatewayId) {
|
||||
const value = await ctx.prompter.text({
|
||||
message: "Enter Cloudflare AI Gateway ID",
|
||||
validate: (val) => (readRequiredTextInput(val) ? undefined : "Gateway ID is required"),
|
||||
});
|
||||
gatewayId = readRequiredTextInput(value);
|
||||
}
|
||||
return { accountId, gatewayId };
|
||||
}
|
||||
|
||||
export default definePluginEntry({
|
||||
id: PROVIDER_ID,
|
||||
name: "Cloudflare AI Gateway Provider",
|
||||
description: "Bundled Cloudflare AI Gateway provider plugin",
|
||||
register(api) {
|
||||
api.registerProvider({
|
||||
id: PROVIDER_ID,
|
||||
label: "Cloudflare AI Gateway",
|
||||
docsPath: "/providers/cloudflare-ai-gateway",
|
||||
envVars: ["CLOUDFLARE_AI_GATEWAY_API_KEY"],
|
||||
auth: [
|
||||
{
|
||||
id: "api-key",
|
||||
label: "Cloudflare AI Gateway",
|
||||
hint: "Account ID + Gateway ID + API key",
|
||||
kind: "api_key",
|
||||
wizard: {
|
||||
choiceId: "cloudflare-ai-gateway-api-key",
|
||||
choiceLabel: "Cloudflare AI Gateway",
|
||||
choiceHint: "Account ID + Gateway ID + API key",
|
||||
groupId: "cloudflare-ai-gateway",
|
||||
groupLabel: "Cloudflare AI Gateway",
|
||||
groupHint: "Account ID + Gateway ID + API key",
|
||||
},
|
||||
run: async (ctx) => {
|
||||
const metadata = await resolveCloudflareGatewayMetadataInteractive({
|
||||
accountId: normalizeOptionalSecretInput(ctx.opts?.cloudflareAiGatewayAccountId),
|
||||
gatewayId: normalizeOptionalSecretInput(ctx.opts?.cloudflareAiGatewayGatewayId),
|
||||
prompter: ctx.prompter,
|
||||
});
|
||||
let capturedSecretInput: Parameters<typeof buildApiKeyCredential>[1] = "";
|
||||
let capturedCredential = false;
|
||||
let capturedMode: "plaintext" | "ref" | undefined;
|
||||
// Capture through the shared provider auth helper so plaintext,
|
||||
// env refs, and secret refs keep the same validation path.
|
||||
await ensureApiKeyFromOptionEnvOrPrompt({
|
||||
token: normalizeOptionalSecretInput(ctx.opts?.cloudflareAiGatewayApiKey),
|
||||
tokenProvider: "cloudflare-ai-gateway",
|
||||
secretInputMode:
|
||||
ctx.allowSecretRefPrompt === false
|
||||
? (ctx.secretInputMode ?? "plaintext")
|
||||
: ctx.secretInputMode,
|
||||
config: ctx.config,
|
||||
expectedProviders: [PROVIDER_ID],
|
||||
provider: PROVIDER_ID,
|
||||
envLabel: PROVIDER_ENV_VAR,
|
||||
promptMessage: "Enter Cloudflare AI Gateway API key",
|
||||
normalize: normalizeApiKeyInput,
|
||||
validate: validateApiKeyInput,
|
||||
prompter: ctx.prompter,
|
||||
setCredential: async (apiKey, mode) => {
|
||||
capturedSecretInput = apiKey;
|
||||
capturedCredential = true;
|
||||
capturedMode = mode;
|
||||
},
|
||||
});
|
||||
if (!capturedCredential) {
|
||||
throw new Error("Missing Cloudflare AI Gateway API key.");
|
||||
}
|
||||
const credentialInput = capturedSecretInput ?? "";
|
||||
return {
|
||||
profiles: [
|
||||
{
|
||||
profileId: PROFILE_ID,
|
||||
credential: buildApiKeyCredential(
|
||||
PROVIDER_ID,
|
||||
credentialInput,
|
||||
{
|
||||
accountId: metadata.accountId,
|
||||
gatewayId: metadata.gatewayId,
|
||||
},
|
||||
capturedMode ? { secretInputMode: capturedMode } : undefined,
|
||||
),
|
||||
},
|
||||
],
|
||||
configPatch: buildCloudflareAiGatewayConfigPatch(metadata),
|
||||
defaultModel: CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
|
||||
};
|
||||
},
|
||||
runNonInteractive: async (ctx) => {
|
||||
const authStore = ensureAuthProfileStore(ctx.agentDir, {
|
||||
allowKeychainPrompt: false,
|
||||
});
|
||||
const storedMetadata =
|
||||
authStore.profiles[PROFILE_ID]?.type === "api_key"
|
||||
? {
|
||||
accountId: normalizeOptionalString(
|
||||
authStore.profiles[PROFILE_ID]?.metadata?.accountId,
|
||||
),
|
||||
gatewayId: normalizeOptionalString(
|
||||
authStore.profiles[PROFILE_ID]?.metadata?.gatewayId,
|
||||
),
|
||||
}
|
||||
: {};
|
||||
const accountId =
|
||||
normalizeOptionalSecretInput(ctx.opts.cloudflareAiGatewayAccountId) ??
|
||||
storedMetadata.accountId;
|
||||
const gatewayId =
|
||||
normalizeOptionalSecretInput(ctx.opts.cloudflareAiGatewayGatewayId) ??
|
||||
storedMetadata.gatewayId;
|
||||
if (!accountId || !gatewayId) {
|
||||
ctx.runtime.error(
|
||||
"Cloudflare AI Gateway setup requires --cloudflare-ai-gateway-account-id and --cloudflare-ai-gateway-gateway-id.",
|
||||
);
|
||||
ctx.runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
const resolved = await ctx.resolveApiKey({
|
||||
provider: PROVIDER_ID,
|
||||
flagValue: normalizeOptionalSecretInput(ctx.opts.cloudflareAiGatewayApiKey),
|
||||
flagName: "--cloudflare-ai-gateway-api-key",
|
||||
envVar: PROVIDER_ENV_VAR,
|
||||
});
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
if (resolved.source !== "profile") {
|
||||
// Persist newly supplied credentials with Gateway metadata; a
|
||||
// profile-sourced key already owns its existing auth-store record.
|
||||
const credential = ctx.toApiKeyCredential({
|
||||
provider: PROVIDER_ID,
|
||||
resolved,
|
||||
metadata: { accountId, gatewayId },
|
||||
});
|
||||
if (!credential) {
|
||||
return null;
|
||||
}
|
||||
await upsertAuthProfileWithLockOrThrow({
|
||||
profileId: PROFILE_ID,
|
||||
credential,
|
||||
agentDir: ctx.agentDir,
|
||||
});
|
||||
}
|
||||
const next = applyAuthProfileConfig(ctx.config, {
|
||||
profileId: PROFILE_ID,
|
||||
provider: PROVIDER_ID,
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyCloudflareAiGatewayConfig(next, { accountId, gatewayId });
|
||||
},
|
||||
},
|
||||
],
|
||||
catalog: {
|
||||
order: "late",
|
||||
run: async (ctx) => {
|
||||
const authStore = ensureAuthProfileStore(ctx.agentDir, {
|
||||
allowKeychainPrompt: false,
|
||||
});
|
||||
const envManagedApiKey = normalizeOptionalString(ctx.env[PROVIDER_ENV_VAR])
|
||||
? PROVIDER_ENV_VAR
|
||||
: undefined;
|
||||
for (const profileId of listProfilesForProvider(authStore, PROVIDER_ID)) {
|
||||
const provider = buildCloudflareAiGatewayCatalogProvider({
|
||||
credential: authStore.profiles[profileId],
|
||||
envApiKey: envManagedApiKey,
|
||||
});
|
||||
if (!provider) {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
provider,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
classifyFailoverReason: ({ errorMessage }) =>
|
||||
/\bworkers?_ai\b.*\b(?:rate|limit|quota)\b/i.test(errorMessage) ? "rate_limit" : undefined,
|
||||
wrapStreamFn: wrapCloudflareAiGatewayProviderStream,
|
||||
});
|
||||
},
|
||||
});
|
||||
59
extensions/cloudflare-ai-gateway/models.ts
Normal file
59
extensions/cloudflare-ai-gateway/models.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Model ids, default model metadata, and URL construction for the Cloudflare AI
|
||||
* Gateway provider.
|
||||
*/
|
||||
import type { ModelDefinitionConfig } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
|
||||
/** Provider id used in model refs and auth profiles. */
|
||||
export const CLOUDFLARE_AI_GATEWAY_PROVIDER_ID = "cloudflare-ai-gateway";
|
||||
/** Default Cloudflare AI Gateway model id exposed by the bundled provider. */
|
||||
export const CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_ID = "claude-sonnet-4-6";
|
||||
/** Fully-qualified default model ref used by onboarding. */
|
||||
export const CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF = `${CLOUDFLARE_AI_GATEWAY_PROVIDER_ID}/${CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_ID}`;
|
||||
|
||||
const CLOUDFLARE_AI_GATEWAY_DEFAULT_CONTEXT_WINDOW = 200_000;
|
||||
const CLOUDFLARE_AI_GATEWAY_DEFAULT_MAX_TOKENS = 64_000;
|
||||
const CLOUDFLARE_AI_GATEWAY_DEFAULT_COST = {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheRead: 0.3,
|
||||
cacheWrite: 3.75,
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a provider model definition, allowing tests/catalog code to override
|
||||
* the model id while preserving Cloudflare defaults.
|
||||
*/
|
||||
export function buildCloudflareAiGatewayModelDefinition(params?: {
|
||||
id?: string;
|
||||
name?: string;
|
||||
reasoning?: boolean;
|
||||
input?: Array<"text" | "image">;
|
||||
}): ModelDefinitionConfig {
|
||||
const id = params?.id?.trim() || CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_ID;
|
||||
return {
|
||||
id,
|
||||
name: params?.name ?? "Claude Sonnet 4.6",
|
||||
reasoning: params?.reasoning ?? true,
|
||||
input: params?.input ?? ["text", "image"],
|
||||
cost: CLOUDFLARE_AI_GATEWAY_DEFAULT_COST,
|
||||
contextWindow: CLOUDFLARE_AI_GATEWAY_DEFAULT_CONTEXT_WINDOW,
|
||||
maxTokens: CLOUDFLARE_AI_GATEWAY_DEFAULT_MAX_TOKENS,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the Anthropic Messages base URL for a Cloudflare account/gateway
|
||||
* pair, returning an empty string for incomplete metadata.
|
||||
*/
|
||||
export function resolveCloudflareAiGatewayBaseUrl(params: {
|
||||
accountId: string;
|
||||
gatewayId: string;
|
||||
}): string {
|
||||
const accountId = params.accountId.trim();
|
||||
const gatewayId = params.gatewayId.trim();
|
||||
if (!accountId || !gatewayId) {
|
||||
return "";
|
||||
}
|
||||
return `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/anthropic`;
|
||||
}
|
||||
12
extensions/cloudflare-ai-gateway/npm-shrinkwrap.json
generated
Normal file
12
extensions/cloudflare-ai-gateway/npm-shrinkwrap.json
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@openclaw/cloudflare-ai-gateway-provider",
|
||||
"version": "2026.6.11",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@openclaw/cloudflare-ai-gateway-provider",
|
||||
"version": "2026.6.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
104
extensions/cloudflare-ai-gateway/onboard.ts
Normal file
104
extensions/cloudflare-ai-gateway/onboard.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Config patch helpers used by Cloudflare AI Gateway interactive and
|
||||
* non-interactive onboarding flows.
|
||||
*/
|
||||
import {
|
||||
applyAgentDefaultModelPrimary,
|
||||
applyProviderConfigWithDefaultModel,
|
||||
type OpenClawConfig,
|
||||
} from "openclaw/plugin-sdk/provider-onboard";
|
||||
import {
|
||||
buildCloudflareAiGatewayModelDefinition,
|
||||
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
|
||||
resolveCloudflareAiGatewayBaseUrl,
|
||||
} from "./models.js";
|
||||
|
||||
/**
|
||||
* Builds the minimal config patch for provider setup and default model aliasing.
|
||||
*/
|
||||
export function buildCloudflareAiGatewayConfigPatch(params: {
|
||||
accountId: string;
|
||||
gatewayId: string;
|
||||
}) {
|
||||
const baseUrl = resolveCloudflareAiGatewayBaseUrl(params);
|
||||
return {
|
||||
models: {
|
||||
providers: {
|
||||
"cloudflare-ai-gateway": {
|
||||
baseUrl,
|
||||
api: "anthropic-messages" as const,
|
||||
models: [buildCloudflareAiGatewayModelDefinition()],
|
||||
},
|
||||
},
|
||||
},
|
||||
agents: {
|
||||
defaults: {
|
||||
models: {
|
||||
[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF]: {
|
||||
alias: "Cloudflare AI Gateway",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies provider model config while preserving existing agent model aliases.
|
||||
*/
|
||||
export function applyCloudflareAiGatewayProviderConfig(
|
||||
cfg: OpenClawConfig,
|
||||
params?: { accountId?: string; gatewayId?: string },
|
||||
): OpenClawConfig {
|
||||
const models = { ...cfg.agents?.defaults?.models };
|
||||
models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF] = {
|
||||
...models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF],
|
||||
alias: models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF]?.alias ?? "Cloudflare AI Gateway",
|
||||
};
|
||||
|
||||
const existingProvider = cfg.models?.providers?.["cloudflare-ai-gateway"] as
|
||||
| { baseUrl?: unknown }
|
||||
| undefined;
|
||||
const baseUrl =
|
||||
params?.accountId && params?.gatewayId
|
||||
? resolveCloudflareAiGatewayBaseUrl({
|
||||
accountId: params.accountId,
|
||||
gatewayId: params.gatewayId,
|
||||
})
|
||||
: typeof existingProvider?.baseUrl === "string"
|
||||
? existingProvider.baseUrl
|
||||
: undefined;
|
||||
if (!baseUrl) {
|
||||
return {
|
||||
...cfg,
|
||||
agents: {
|
||||
...cfg.agents,
|
||||
defaults: {
|
||||
...cfg.agents?.defaults,
|
||||
models,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return applyProviderConfigWithDefaultModel(cfg, {
|
||||
agentModels: models,
|
||||
providerId: "cloudflare-ai-gateway",
|
||||
api: "anthropic-messages",
|
||||
baseUrl,
|
||||
defaultModel: buildCloudflareAiGatewayModelDefinition(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies Cloudflare AI Gateway config and makes its default model primary.
|
||||
*/
|
||||
export function applyCloudflareAiGatewayConfig(
|
||||
cfg: OpenClawConfig,
|
||||
params?: { accountId?: string; gatewayId?: string },
|
||||
): OpenClawConfig {
|
||||
return applyAgentDefaultModelPrimary(
|
||||
applyCloudflareAiGatewayProviderConfig(cfg, params),
|
||||
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
|
||||
);
|
||||
}
|
||||
50
extensions/cloudflare-ai-gateway/openclaw.plugin.json
Normal file
50
extensions/cloudflare-ai-gateway/openclaw.plugin.json
Normal file
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"id": "cloudflare-ai-gateway",
|
||||
"icon": "https://cdn.simpleicons.org/cloudflare",
|
||||
"activation": {
|
||||
"onStartup": false
|
||||
},
|
||||
"enabledByDefault": true,
|
||||
"providers": ["cloudflare-ai-gateway"],
|
||||
"modelPricing": {
|
||||
"providers": {
|
||||
"cloudflare-ai-gateway": {
|
||||
"openRouter": {
|
||||
"passthroughProviderModel": true
|
||||
},
|
||||
"liteLLM": {
|
||||
"passthroughProviderModel": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"setup": {
|
||||
"providers": [
|
||||
{
|
||||
"id": "cloudflare-ai-gateway",
|
||||
"envVars": ["CLOUDFLARE_AI_GATEWAY_API_KEY"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "cloudflare-ai-gateway",
|
||||
"method": "api-key",
|
||||
"choiceId": "cloudflare-ai-gateway-api-key",
|
||||
"choiceLabel": "Cloudflare AI Gateway",
|
||||
"choiceHint": "Account ID + Gateway ID + API key",
|
||||
"groupId": "cloudflare-ai-gateway",
|
||||
"groupLabel": "Cloudflare AI Gateway",
|
||||
"groupHint": "Account ID + Gateway ID + API key",
|
||||
"optionKey": "cloudflareAiGatewayApiKey",
|
||||
"cliFlag": "--cloudflare-ai-gateway-api-key",
|
||||
"cliOption": "--cloudflare-ai-gateway-api-key <key>",
|
||||
"cliDescription": "Cloudflare AI Gateway API key"
|
||||
}
|
||||
],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
35
extensions/cloudflare-ai-gateway/package.json
Normal file
35
extensions/cloudflare-ai-gateway/package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@openclaw/cloudflare-ai-gateway-provider",
|
||||
"version": "2026.6.11",
|
||||
"description": "OpenClaw Cloudflare AI Gateway provider plugin.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/openclaw/openclaw"
|
||||
},
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@openclaw/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
"./index.ts"
|
||||
],
|
||||
"install": {
|
||||
"clawhubSpec": "clawhub:@openclaw/cloudflare-ai-gateway-provider",
|
||||
"npmSpec": "@openclaw/cloudflare-ai-gateway-provider",
|
||||
"defaultChoice": "npm",
|
||||
"minHostVersion": ">=2026.6.8"
|
||||
},
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.6.11"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.6.11",
|
||||
"bundledDist": false
|
||||
},
|
||||
"release": {
|
||||
"publishToClawHub": true,
|
||||
"publishToNpm": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Cloudflare Ai Gateway tests cover provider discovery.contract plugin behavior.
|
||||
import { describeCloudflareAiGatewayProviderDiscoveryContract } from "openclaw/plugin-sdk/provider-test-contracts";
|
||||
|
||||
describeCloudflareAiGatewayProviderDiscoveryContract(() => import("./index.js"));
|
||||
161
extensions/cloudflare-ai-gateway/stream-wrappers.test.ts
Normal file
161
extensions/cloudflare-ai-gateway/stream-wrappers.test.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
// Cloudflare Ai Gateway tests cover stream wrappers plugin behavior.
|
||||
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
|
||||
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
testing,
|
||||
createCloudflareAiGatewayAnthropicThinkingPrefillWrapper,
|
||||
wrapCloudflareAiGatewayProviderStream,
|
||||
} from "./stream-wrappers.js";
|
||||
|
||||
const { warnMock } = vi.hoisted(() => ({
|
||||
warnMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/runtime-env", () => ({
|
||||
createSubsystemLogger: () => ({
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: warnMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
afterAll(() => {
|
||||
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
function createPayloadBaseStream(payload: Record<string, unknown>): StreamFn {
|
||||
return ((model, _context, options) => {
|
||||
options?.onPayload?.(payload as never, model as never);
|
||||
return {} as ReturnType<StreamFn>;
|
||||
}) as StreamFn;
|
||||
}
|
||||
|
||||
function runWrapper(payload: Record<string, unknown>): Record<string, unknown> {
|
||||
const wrapper = createCloudflareAiGatewayAnthropicThinkingPrefillWrapper(
|
||||
createPayloadBaseStream(payload),
|
||||
);
|
||||
void wrapper(
|
||||
{ provider: "cloudflare-ai-gateway", api: "anthropic-messages" } as never,
|
||||
{} as never,
|
||||
{},
|
||||
);
|
||||
return payload;
|
||||
}
|
||||
|
||||
describe("createCloudflareAiGatewayAnthropicThinkingPrefillWrapper", () => {
|
||||
beforeEach(() => {
|
||||
warnMock.mockClear();
|
||||
});
|
||||
|
||||
it("removes trailing assistant prefill when thinking is enabled", () => {
|
||||
const payload = runWrapper({
|
||||
thinking: { type: "enabled", budget_tokens: 1024 },
|
||||
messages: [
|
||||
{ role: "user", content: "Return JSON." },
|
||||
{ role: "assistant", content: "{" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.messages).toEqual([{ role: "user", content: "Return JSON." }]);
|
||||
expect(warnMock).toHaveBeenCalledWith(
|
||||
"removed 1 trailing assistant prefill message because Anthropic extended thinking requires conversations to end with a user turn",
|
||||
);
|
||||
});
|
||||
|
||||
it("removes multiple trailing assistant prefill messages until the conversation ends with user", () => {
|
||||
const payload = runWrapper({
|
||||
thinking: { type: "adaptive" },
|
||||
messages: [
|
||||
{ role: "user", content: "Return JSON." },
|
||||
{ role: "assistant", content: "{" },
|
||||
{ role: "assistant", content: '"status"' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.messages).toEqual([{ role: "user", content: "Return JSON." }]);
|
||||
expect(warnMock).toHaveBeenCalledWith(
|
||||
"removed 2 trailing assistant prefill messages because Anthropic extended thinking requires conversations to end with a user turn",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps assistant prefill when thinking is disabled", () => {
|
||||
const payload = runWrapper({
|
||||
thinking: { type: "disabled" },
|
||||
messages: [
|
||||
{ role: "user", content: "Return JSON." },
|
||||
{ role: "assistant", content: "{" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.messages).toHaveLength(2);
|
||||
expect(warnMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps trailing assistant tool use turns when thinking is enabled", () => {
|
||||
const payload = runWrapper({
|
||||
thinking: { type: "enabled", budget_tokens: 1024 },
|
||||
messages: [
|
||||
{ role: "user", content: "Read a file." },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "tool_use", id: "toolu_1", name: "Read" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(payload.messages).toHaveLength(2);
|
||||
expect(warnMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("wrapCloudflareAiGatewayProviderStream", () => {
|
||||
beforeEach(() => {
|
||||
warnMock.mockClear();
|
||||
});
|
||||
|
||||
it("patches Anthropic Messages models", () => {
|
||||
const payload = {
|
||||
thinking: { type: "enabled" },
|
||||
messages: [
|
||||
{ role: "user", content: "Return JSON." },
|
||||
{ role: "assistant", content: "{" },
|
||||
],
|
||||
};
|
||||
const wrapped = wrapCloudflareAiGatewayProviderStream({
|
||||
model: { api: "anthropic-messages" },
|
||||
streamFn: createPayloadBaseStream(payload),
|
||||
} as never);
|
||||
|
||||
void wrapped?.(
|
||||
{ provider: "cloudflare-ai-gateway", api: "anthropic-messages" } as never,
|
||||
{} as never,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(payload.messages).toEqual([{ role: "user", content: "Return JSON." }]);
|
||||
});
|
||||
|
||||
it("leaves non-Anthropic model APIs on the original stream path", () => {
|
||||
let onPayloadWasInstalled = false;
|
||||
const baseStreamFn: StreamFn = (_model, _context, options) => {
|
||||
onPayloadWasInstalled = typeof options?.onPayload === "function";
|
||||
return {} as ReturnType<StreamFn>;
|
||||
};
|
||||
|
||||
const wrapped = wrapCloudflareAiGatewayProviderStream({
|
||||
model: { api: "openai-completions" },
|
||||
streamFn: baseStreamFn,
|
||||
} as never);
|
||||
void wrapped?.({ api: "openai-completions" } as never, {} as never, {});
|
||||
|
||||
expect(wrapped).toBe(baseStreamFn);
|
||||
expect(onPayloadWasInstalled).toBe(false);
|
||||
expect(warnMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats missing model API as the plugin's default Anthropic Messages route", () => {
|
||||
expect(testing.shouldPatchAnthropicMessagesPayload({} as never)).toBe(true);
|
||||
});
|
||||
});
|
||||
44
extensions/cloudflare-ai-gateway/stream-wrappers.ts
Normal file
44
extensions/cloudflare-ai-gateway/stream-wrappers.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Stream wrapper for Cloudflare AI Gateway's Anthropic Messages compatibility
|
||||
* quirks.
|
||||
*/
|
||||
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
|
||||
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { createAnthropicThinkingPrefillPayloadWrapper } from "openclaw/plugin-sdk/provider-stream-shared";
|
||||
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
|
||||
|
||||
const log = createSubsystemLogger("cloudflare-ai-gateway-stream");
|
||||
|
||||
function shouldPatchAnthropicMessagesPayload(model: ProviderWrapStreamFnContext["model"]): boolean {
|
||||
return model?.api === undefined || model.api === "anthropic-messages";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wrapper that removes trailing assistant prefill messages before
|
||||
* extended-thinking Anthropic requests are sent through Cloudflare.
|
||||
*/
|
||||
export function createCloudflareAiGatewayAnthropicThinkingPrefillWrapper(
|
||||
baseStreamFn: StreamFn | undefined,
|
||||
): StreamFn {
|
||||
return createAnthropicThinkingPrefillPayloadWrapper(baseStreamFn, (stripped) => {
|
||||
log.warn(
|
||||
`removed ${stripped} trailing assistant prefill message${stripped === 1 ? "" : "s"} because Anthropic extended thinking requires conversations to end with a user turn`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the Anthropic payload wrapper only for Anthropic-compatible models.
|
||||
*/
|
||||
export function wrapCloudflareAiGatewayProviderStream(
|
||||
ctx: ProviderWrapStreamFnContext,
|
||||
): StreamFn | undefined {
|
||||
if (!shouldPatchAnthropicMessagesPayload(ctx.model)) {
|
||||
return ctx.streamFn;
|
||||
}
|
||||
return createCloudflareAiGatewayAnthropicThinkingPrefillWrapper(ctx.streamFn);
|
||||
}
|
||||
|
||||
/** Test-only access to wrapper decisions and logger injection points. */
|
||||
export const testing = { log, shouldPatchAnthropicMessagesPayload };
|
||||
export { testing as __testing };
|
||||
16
extensions/cloudflare-ai-gateway/tsconfig.json
Normal file
16
extensions/cloudflare-ai-gateway/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../tsconfig.package-boundary.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": ["./*.ts", "./src/**/*.ts"],
|
||||
"exclude": [
|
||||
"./**/*.test.ts",
|
||||
"./dist/**",
|
||||
"./node_modules/**",
|
||||
"./src/test-support/**",
|
||||
"./src/**/*test-helpers.ts",
|
||||
"./src/**/*test-harness.ts",
|
||||
"./src/**/*test-support.ts"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user