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

emit.ts

96 lines · 4.1 KB · TypeScript
/**
 * Package event emission for the factory. Never throws: a failed emit must
 * never break a wake, a card write, or a sweep.
 *
 * `kody:runtime` is read as a namespace so hosts (and test stubs) without an
 * `events` binding still load this module.
 */
import * as kodyRuntime from 'kody:runtime'
import { loadSettings } from '../lib/settings.ts'

export const TOPICS = {
	fingerprintQueued: '@kody/factory.health.fingerprint.queued',
	wakeStale: '@kody/factory.health.wake.stale',
	cardCreated: '@kody/factory.card.created',
	cardTriaged: '@kody/factory.card.triaged',
	wakeRequested: '@kody/factory.wake.requested',
	agentStartRequested: '@kody/factory.agent.start.requested',
	agentMessageRequested: '@kody/factory.agent.message.requested',
	agentCancelRequested: '@kody/factory.agent.cancel.requested',
	reportPosted: '@kody/factory.report.posted',
} as const
export type FactoryTopic = (typeof TOPICS)[keyof typeof TOPICS]

/** Payload budget below the platform's 64 KiB cap, leaving envelope headroom. */
export const EVENT_PAYLOAD_BUDGET = 56 * 1024
/** Prompt budget inside wake.requested. */
export const WAKE_PROMPT_BUDGET = 48 * 1024

export type EmitResult = { emitted: boolean; status?: string; skipped?: string; error?: string }

type Dispatch = (input: { topic: string; idempotencyKey: string; payload: Record<string, unknown> }) => Promise<unknown>

/** Test seam: replace the dispatcher (null restores the runtime binding). */
let dispatchOverride: Dispatch | null = null
export function setDispatchForTests(fn: Dispatch | null) {
	dispatchOverride = fn
}

function runtimeDispatch(): Dispatch | null {
	if (dispatchOverride) return dispatchOverride
	const events = (kodyRuntime as unknown as { events?: { dispatch?: Dispatch } | null }).events
	return events && typeof events.dispatch === 'function' ? (input) => events.dispatch!(input) : null
}

export function utf8Bytes(text: string): number {
	return new TextEncoder().encode(text).length
}

/** Clip to at most `max` UTF-8 bytes without splitting a code point. */
export function clipToBytes(text: string, max: number): string {
	if (utf8Bytes(text) <= max) return text
	let lo = 0
	let hi = text.length
	while (lo < hi) {
		const mid = Math.ceil((lo + hi) / 2)
		if (utf8Bytes(text.slice(0, mid)) <= max) lo = mid
		else hi = mid - 1
	}
	return text.slice(0, lo)
}

/** Idempotency keys: printable, bounded, stable. */
export function eventKey(...parts: Array<string | number | null | undefined>): string {
	return parts
		.map((p) => String(p ?? '').replace(/[^A-Za-z0-9_.:-]+/g, '_'))
		.join(':')
		.slice(0, 200)
}

export async function emitFactoryEvent(topic: FactoryTopic, idempotencyKey: string, payload: Record<string, unknown>): Promise<EmitResult> {
	const dispatch = runtimeDispatch()
	if (!dispatch) return { emitted: false, skipped: 'no-dispatch-binding' }
	const body = { schemaVersion: 1, occurredAt: new Date().toISOString(), ...payload }
	if (utf8Bytes(JSON.stringify(body)) > EVENT_PAYLOAD_BUDGET) return { emitted: false, skipped: 'payload-too-large' }
	try {
		const result = (await dispatch({ topic, idempotencyKey, payload: body })) as { status?: unknown } | null
		const status = result && typeof result === 'object' && result.status != null ? String(result.status) : 'ok'
		console.info(`factory event emit topic=${topic} key=${idempotencyKey} status=${status}`)
		return { emitted: true, status }
	} catch (error) {
		const detail = error instanceof Error ? error.message.replace(/\s+/g, ' ').slice(0, 200) : 'emit failed'
		console.error(`factory event emit failed topic=${topic} key=${idempotencyKey}: ${detail}`)
		return { emitted: false, error: detail }
	}
}

/** Health and card events go out only when `emitHealthEvents` is on. */
export async function emitHealthEvent(topic: FactoryTopic, idempotencyKey: string, payload: Record<string, unknown>): Promise<EmitResult> {
	try {
		const settings = await loadSettings()
		if (settings.emitHealthEvents !== true) return { emitted: false, skipped: 'emitHealthEvents-off' }
	} catch {
		return { emitted: false, skipped: 'settings-unreadable' }
	}
	return emitFactoryEvent(topic, idempotencyKey, payload)
}