Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

router.ts

121 lines · 3.7 KB · TypeScript
/**
 * Two-tier routing engine: clef-flash first, escalate to full clef when
 * confidence is below the project threshold. Uses the same credential('model')
 * pattern as factory triage.
 */
import { credential } from 'kody:runtime'
import { loadSettings } from '../../lib/settings.ts'
import { getRoutingConfig } from './config.ts'
import { buildRoutingRequestBody, parseRoutingChoice } from './request.ts'
import type { RoutingConfig, RoutingResult } from './types.ts'

type Signal = {
	title: string
	body: string
	source: string
	labels: string[]
	severity?: string
	projectId: string
}

async function callModel(
	signal: Signal,
	config: RoutingConfig,
	mode: 'flash' | 'full',
): Promise<{ ok: boolean; value?: string; confidence?: number; decidedBy?: string; error?: string }> {
	const settings = await loadSettings()
	if (!settings.cloudflareAccountId) {
		return { ok: false, error: 'cloudflareAccountId not set in factory settings' }
	}
	let client: { fetch: typeof fetch }
	try {
		client = (await credential('model')) as { fetch: typeof fetch }
	} catch (err) {
		return { ok: false, error: err instanceof Error ? err.message : String(err) }
	}
	const url =
		'https://api.cloudflare.com/client/v4/accounts/' +
		settings.cloudflareAccountId +
		'/ai/run'
	const body = buildRoutingRequestBody(signal, config)
	try {
		const res = await client.fetch(url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'cf-aig-gateway-id': settings.cloudflareAiGatewayId || 'kody',
				'x-kody-secret-resolution': 'headers-only',
				...(mode === 'flash' ? { 'x-kody-routing-mode': 'flash' } : {}),
			},
			body: JSON.stringify(body),
		})
		const text = await res.text()
		let data: unknown = text
		try { data = text ? JSON.parse(text) : null } catch { data = text }
		if (!res.ok) return { ok: false, error: `model HTTP ${res.status}` }
		const parsed = parseRoutingChoice(data)
		if (!parsed) return { ok: false, error: 'model returned no routing choice' }
		return { ok: true, value: parsed.value, confidence: parsed.confidence, decidedBy: parsed.decidedBy }
	} catch (err) {
		return { ok: false, error: err instanceof Error ? err.message : String(err) }
	}
}

export async function routeSignal(signal: Signal, opts?: { dryRun?: boolean }): Promise<RoutingResult> {
	const config = await getRoutingConfig(signal.projectId)
	if (!config.enabled) {
		return {
			destination: 'none',
			confidence: 1,
			modelUsed: null,
			escalated: false,
			reason: 'routing disabled for project',
			labels: [],
		}
	}

	const flash = await callModel(signal, config, 'flash')

	if (!flash.ok) {
		return {
			destination: 'board-card',
			confidence: 0,
			modelUsed: null,
			escalated: false,
			reason: `model unavailable (${flash.error ?? 'unknown'}); default to board card`,
			labels: ['model-unavailable'],
		}
	}

	let chosen = flash.value ?? 'ignore'
	let confidence = flash.confidence ?? 0
	let escalated = false
	let modelUsed: string | null = 'clef-flash'
	let decidedBy = flash.decidedBy

	if (confidence < config.confidenceThreshold) {
		const full = await callModel(signal, config, 'full')
		if (full.ok) {
			chosen = full.value ?? chosen
			confidence = full.confidence ?? confidence
			decidedBy = full.decidedBy
			escalated = true
			modelUsed = 'clef-full'
		}
	}

	const mapping = config.criteria[chosen]
	const destination = mapping?.destination ?? 'none'

	return {
		destination,
		confidence,
		modelUsed,
		escalated,
		reason: `routed to ${destination} (${chosen}, confidence ${confidence.toFixed(2)}${decidedBy ? `, decided by ${decidedBy}` : ''})`,
		labels: [chosen],
	}
}

export { getRoutingConfig, saveRoutingConfig, listRoutingConfigs, deleteRoutingConfig } from './config.ts'
export { defaultRoutingConfig } from './config.ts'