Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/clef

Cloudflare Clef decision models via Workers AI (Jev-shaped noul/choice/score API).

FollowFork

Files

build-choice-from-events.ts

138 lines · 4.2 KB · TypeScript
/**
 * Pure helper: enabled state-machine events → Clef `choice` questions object.
 * Use when you want raw `./evaluate` instead of `./choose-transition`.
 *
 * @param events - Event id → description map, or `{ id, description }[]`.
 * @param options.questionKey - Answer key (default `transition`).
 * @param options.instructions - Choice instructions override.
 * @returns `{ questions, criteria, eventIds }` for evaluate / callers.
 *
 * @example
 * import buildChoiceFromEvents from 'kody:@kody/clef/build-choice-from-events'
 * const { questions } = buildChoiceFromEvents({
 *   RETRY: 'Retry the failed step',
 *   ESCALATE: 'Hand off to a human',
 * })
 */

import type {
	ChoiceQuestion,
	Questions,
	TransitionEvents,
} from './types.ts'
import { BuildChoiceFromEventsOptionsSchema, formatSchemaError, parse } from './schema.ts'

export type { TransitionEvents, TransitionEventListItem } from './types.ts'

export type BuildChoiceFromEventsOptions = {
	/** Named answer key in `questions` / `answers` (default `transition`). */
	questionKey?: string
	/** Override choice instructions. */
	instructions?: string
}

export type BuildChoiceFromEventsResult = {
	/** Ready for `evaluate({ questions })`. */
	questions: Questions
	/** Normalized criteria map (event id → description). */
	criteria: Record<string, string>
	/** Ordered event ids. */
	eventIds: string[]
	questionKey: string
}

const DEFAULT_QUESTION_KEY = 'transition'
const DEFAULT_INSTRUCTIONS =
	'Which enabled event should fire next to move toward the goal? Pick exactly one.'

/**
 * Normalize event map or list into a stable criteria Record.
 * Empty descriptions fall back to the event id.
 */
export function normalizeTransitionEvents(
	events: TransitionEvents | null | undefined,
): Record<string, string> {
	if (!events) return {}

	if (Array.isArray(events)) {
		const criteria: Record<string, string> = {}
		for (const item of events) {
			if (!item || typeof item !== 'object') continue
			const id = typeof item.id === 'string' ? item.id.trim() : ''
			if (!id) continue
			const description =
				typeof item.description === 'string' && item.description.trim()
					? item.description.trim()
					: id
			criteria[id] = description
		}
		return criteria
	}

	if (typeof events !== 'object') return {}

	const criteria: Record<string, string> = {}
	for (const [id, description] of Object.entries(events)) {
		const key = typeof id === 'string' ? id.trim() : ''
		if (!key) continue
		criteria[key] =
			typeof description === 'string' && description.trim()
				? description.trim()
				: key
	}
	return criteria
}

/**
 * Pure helper: enabled state-machine events → Clef `choice` questions object.
 * Use when you want raw `./evaluate` instead of `./choose-transition`.
 *
 * @param events - Event id → description map, or `{ id, description }[]`.
 * @param options.questionKey - Answer key (default `transition`).
 * @param options.instructions - Choice instructions override.
 * @returns `{ questions, criteria, eventIds }` for evaluate / callers.
 *
 * @example
 * import buildChoiceFromEvents from 'kody:@kody/clef/build-choice-from-events'
 * const { questions } = buildChoiceFromEvents({
 *   RETRY: 'Retry the failed step',
 *   ESCALATE: 'Hand off to a human',
 * })
 */
export default function buildChoiceFromEvents(
	events: TransitionEvents,
	options: BuildChoiceFromEventsOptions = {},
): BuildChoiceFromEventsResult {
	let parsedOptions: BuildChoiceFromEventsOptions = {}
	try {
		parsedOptions = parse(
			BuildChoiceFromEventsOptionsSchema,
			options ?? {},
		) as BuildChoiceFromEventsOptions
	} catch (error) {
		throw new Error(formatSchemaError(error))
	}
	const criteria = normalizeTransitionEvents(events)
	const eventIds = Object.keys(criteria)
	const questionKey =
		typeof parsedOptions.questionKey === 'string' && parsedOptions.questionKey.trim()
			? parsedOptions.questionKey.trim()
			: DEFAULT_QUESTION_KEY
	const instructions =
		typeof parsedOptions.instructions === 'string' && parsedOptions.instructions.trim()
			? parsedOptions.instructions.trim()
			: DEFAULT_INSTRUCTIONS

	const choice: ChoiceQuestion = {
		type: 'choice',
		instructions,
		criteria,
	}

	return {
		questions: { [questionKey]: choice },
		criteria,
		eventIds,
		questionKey,
	}
}