import { packageStorage, packages } from 'kody:runtime' import { DEFAULT_CLEF_MODEL, DEFAULT_GATEWAY_ID } from './types.ts' const settingNames = { accountId: 'cloudflareAccountId', gatewayId: 'cloudflareAiGatewayId', model: 'cloudflareClefModel', } as const export const cloudflareApiTokenPlaceholder = '{{secret:cloudflareApiToken}}' export const secretsNewUrl = 'https://kody.codes/account/secrets/new?name=cloudflareApiToken&description=Cloudflare%20API%20token%20for%20Workers%20AI%20%2F%20AI%20Gateway&allowedHosts=api.cloudflare.com%2Cgateway.ai.cloudflare.com&scope=user' function trimString(value: unknown) { return typeof value === 'string' ? value.trim() : '' } async function readLocal(name: string) { const storage = packageStorage() const stored = await storage.get(name) return trimString(stored) } export type NormalizedClefModel = { /** Full Workers AI id stored / returned in settings (`@cf/cloudflare/clef-flash`). */ fullId: string /** Short body `model` field required by Clef REST (`clef` | `clef-flash`). */ bodyModel: 'clef' | 'clef-flash' /** URL path segment (same as fullId). */ urlModel: string } /** * Normalize short or full Clef model ids. * Convention: package storage stores the full Workers AI id * (`@cf/cloudflare/clef-flash`); REST body uses short `clef-flash`. */ export function normalizeClefModel(raw?: string | null): NormalizedClefModel { const trimmed = trimString(raw).toLowerCase() if ( !trimmed || trimmed === 'clef-flash' || trimmed === '@cf/cloudflare/clef-flash' || trimmed === 'cloudflare/clef-flash' ) { return { fullId: '@cf/cloudflare/clef-flash', bodyModel: 'clef-flash', urlModel: '@cf/cloudflare/clef-flash', } } if ( trimmed === 'clef' || trimmed === '@cf/cloudflare/clef' || trimmed === 'cloudflare/clef' ) { return { fullId: '@cf/cloudflare/clef', bodyModel: 'clef', urlModel: '@cf/cloudflare/clef', } } if (trimmed.includes('clef') && !trimmed.includes('flash')) { return { fullId: '@cf/cloudflare/clef', bodyModel: 'clef', urlModel: '@cf/cloudflare/clef', } } return { fullId: DEFAULT_CLEF_MODEL, bodyModel: 'clef-flash', urlModel: DEFAULT_CLEF_MODEL, } } type FallbackIds = { accountId: string gatewayId: string source: 'ai-settings' | 'jev-settings' | 'none' } /** * Read account/gateway from sibling packages in *their* runtime. * Static `kody:@` imports stamp into this package and fail under the @kody * scope (and would see empty local storage) — invoke is required. */ async function invokeSettings( specifier: `kody:@${string}/${string}` | `kody:@${string}`, ): Promise<{ accountId: string; gatewayId: string }> { if (typeof packages?.invoke !== 'function') { return { accountId: '', gatewayId: '' } } try { const settings = (await packages.invoke(specifier, { exportName: './settings', params: {}, })) as { accountId?: unknown; gatewayId?: unknown } | null return { accountId: trimString(settings?.accountId), gatewayId: trimString(settings?.gatewayId), } } catch { return { accountId: '', gatewayId: '' } } } async function readSettingsFallback(): Promise { // Prefer @kentcdodds/ai/settings, then @kentcdodds/jev/settings. const ai = await invokeSettings('kody:@kentcdodds/ai') if (ai.accountId || ai.gatewayId) { return { ...ai, source: 'ai-settings' } } const jev = await invokeSettings('kody:@kentcdodds/jev') if (jev.accountId || jev.gatewayId) { return { ...jev, source: 'jev-settings' } } return { accountId: '', gatewayId: '', source: 'none' } } export async function resolveClefConfig(overrides: { accountId?: string gatewayId?: string model?: string } = {}) { const localAccountId = await readLocal(settingNames.accountId) const localGatewayId = await readLocal(settingNames.gatewayId) const localModel = await readLocal(settingNames.model) let accountId = trimString(overrides.accountId) || localAccountId let gatewayId = trimString(overrides.gatewayId) || localGatewayId let modelRaw = trimString(overrides.model) || localModel let fallbackSource: FallbackIds['source'] = 'none' if (!accountId || !gatewayId) { const fromFallback = await readSettingsFallback() fallbackSource = fromFallback.source if (!accountId && fromFallback.accountId) { accountId = fromFallback.accountId await packageStorage().set(settingNames.accountId, accountId) } if (!gatewayId) { gatewayId = fromFallback.gatewayId || DEFAULT_GATEWAY_ID if (fromFallback.gatewayId) { await packageStorage().set(settingNames.gatewayId, gatewayId) } } } if (!gatewayId) gatewayId = DEFAULT_GATEWAY_ID if (!modelRaw) modelRaw = DEFAULT_CLEF_MODEL const model = normalizeClefModel(modelRaw) return { accountId, gatewayId, model: model.fullId, bodyModel: model.bodyModel, urlModel: model.urlModel, sources: { accountId: trimString(overrides.accountId) ? 'override' : localAccountId ? 'clef-storage' : accountId ? fallbackSource === 'none' ? 'unknown' : fallbackSource : 'missing', gatewayId: trimString(overrides.gatewayId) ? 'override' : localGatewayId ? 'clef-storage' : fromGatewaySource(gatewayId, fallbackSource), model: trimString(overrides.model) ? 'override' : localModel ? 'clef-storage' : 'default', }, } } function fromGatewaySource( gatewayId: string, fallbackSource: FallbackIds['source'], ) { if (!gatewayId) return 'missing' if (fallbackSource === 'ai-settings' || fallbackSource === 'jev-settings') { return fallbackSource } return 'fallback' } export { settingNames, readLocal } export function missingSetup(accountId: string) { if (accountId) return undefined return { secretsNewUrl, settingsHint: 'Save cloudflareApiToken (user scope, hosts api.cloudflare.com). Then set accountId/gatewayId via kody:@kody/clef/settings — or leave them empty to reuse values already stored on @kentcdodds/ai/settings or @kentcdodds/jev/settings (gateway defaults to kody). Model defaults to @cf/cloudflare/clef-flash.', } }