重构主控编排与运行时预热链路,统一工作区提示词/专家调度协议并补齐 wiki 记忆注入与写回闭环。

同时收敛启动与运维脚本默认行为(含 wiki worker)、更新 Admin 可观测性与相关测试,降低首轮时延并提高运行稳定性。

Made-with: Cursor
This commit is contained in:
oliver 2026-04-26 08:34:33 +08:00
parent 4a23b715a2
commit dbbe3add6a
14438 changed files with 2693620 additions and 2546 deletions

View file

@ -0,0 +1,14 @@
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";

View file

@ -0,0 +1,75 @@
import {
coerceSecretRef,
resolveNonEnvSecretRefApiKeyMarker,
} from "openclaw/plugin-sdk/provider-auth";
import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
import {
buildCloudflareAiGatewayModelDefinition,
resolveCloudflareAiGatewayBaseUrl,
} from "./models.js";
export type CloudflareAiGatewayCredential =
| {
type?: string;
keyRef?: unknown;
key?: unknown;
metadata?: {
accountId?: unknown;
gatewayId?: unknown;
};
}
| undefined;
export 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);
}
export 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),
};
}
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()],
};
}

View file

@ -0,0 +1,221 @@
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import {
applyAuthProfileConfig,
buildApiKeyCredential,
ensureApiKeyFromOptionEnvOrPrompt,
ensureAuthProfileStore,
listProfilesForProvider,
normalizeApiKeyInput,
normalizeOptionalSecretInput,
upsertAuthProfile,
validateApiKeyInput,
} from "openclaw/plugin-sdk/provider-auth";
import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
import { buildCloudflareAiGatewayCatalogProvider } from "./catalog-provider.js";
import { CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF } from "./models.js";
import { applyCloudflareAiGatewayConfig, buildCloudflareAiGatewayConfigPatch } from "./onboard.js";
const PROVIDER_ID = "cloudflare-ai-gateway";
const PROVIDER_ENV_VAR = "CLOUDFLARE_AI_GATEWAY_API_KEY";
const PROFILE_ID = "cloudflare-ai-gateway:default";
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;
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") {
const credential = ctx.toApiKeyCredential({
provider: PROVIDER_ID,
resolved,
metadata: { accountId, gatewayId },
});
if (!credential) {
return null;
}
upsertAuthProfile({
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,
});
},
});

View file

@ -0,0 +1,44 @@
import type { ModelDefinitionConfig } from "openclaw/plugin-sdk/provider-model-shared";
export const CLOUDFLARE_AI_GATEWAY_PROVIDER_ID = "cloudflare-ai-gateway";
export const CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_ID = "claude-sonnet-4-5";
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,
};
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.5",
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,
};
}
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`;
}

View file

@ -0,0 +1,91 @@
import {
applyAgentDefaultModelPrimary,
applyProviderConfigWithDefaultModel,
type OpenClawConfig,
} from "openclaw/plugin-sdk/provider-onboard";
import {
buildCloudflareAiGatewayModelDefinition,
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
resolveCloudflareAiGatewayBaseUrl,
} from "./models.js";
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",
},
},
},
},
};
}
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(),
});
}
export function applyCloudflareAiGatewayConfig(
cfg: OpenClawConfig,
params?: { accountId?: string; gatewayId?: string },
): OpenClawConfig {
return applyAgentDefaultModelPrimary(
applyCloudflareAiGatewayProviderConfig(cfg, params),
CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
);
}

View file

@ -0,0 +1,29 @@
{
"id": "cloudflare-ai-gateway",
"enabledByDefault": true,
"providers": ["cloudflare-ai-gateway"],
"providerAuthEnvVars": {
"cloudflare-ai-gateway": ["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": {}
}
}

View file

@ -0,0 +1,15 @@
{
"name": "@openclaw/cloudflare-ai-gateway-provider",
"version": "2026.4.20",
"private": true,
"description": "OpenClaw Cloudflare AI Gateway provider plugin",
"type": "module",
"devDependencies": {
"@openclaw/plugin-sdk": "workspace:*"
},
"openclaw": {
"extensions": [
"./index.ts"
]
}
}

View 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"
]
}