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

platform.ts

80 lines · 2.5 KB · TypeScript
/**
 * Thin port over the Kody capabilities the health feed uses (runList, runGet,
 * runUpdate, runUpdateBulk). Everything the feed asks of the platform goes
 * through here, so tests and the local mock can stand in for it.
 */
import { kody, packageContext } from 'kody:runtime'
import type { RunSnippet } from './fingerprint.ts'

export type ListedRun = RunSnippet & {
	id: string
	status?: string
	finished_at?: string | null
	duration_ms?: number | null
	error_triage?: string | null
}

export type RunListInput = {
	surface?: string
	status?: 'running' | 'success' | 'error'
	package_id?: string
	error_triage?: 'open' | 'ignored' | 'resolved' | 'all'
	since?: string
	limit?: number
	cursor?: string
}

export function selfPackageId(): string | null {
	return packageContext?.packageId || null
}

export async function runList(input: RunListInput): Promise<{ runs: ListedRun[]; next_cursor: string | null }> {
	const result = (await kody.runList!(input)) as { runs?: ListedRun[]; next_cursor?: string | null } | null
	return { runs: Array.isArray(result?.runs) ? result!.runs! : [], next_cursor: result?.next_cursor ?? null }
}

export async function runGet(runId: string): Promise<ListedRun | null> {
	const result = (await kody.runGet!({ run_id: runId })) as { run?: ListedRun } | null
	return result?.run ?? null
}

/** Best effort: the fingerprint row is the standing record, Activity triage is a courtesy. */
export async function softTriageRun(runId: string | null | undefined, triage: 'ignored' | 'resolved', note: string): Promise<boolean> {
	if (!runId) return false
	try {
		await kody.runUpdate!({ run_id: runId, triage, note: note.slice(0, 2000) })
		return true
	} catch {
		return false
	}
}

export async function softTriageRuns(runIds: string[], triage: 'ignored' | 'resolved', note: string): Promise<number> {
	let updated = 0
	const ids = [...new Set(runIds)]
	for (let i = 0; i < ids.length; i += 100) {
		try {
			const result = (await kody.runUpdateBulk!({ run_ids: ids.slice(i, i + 100), triage, note: note.slice(0, 2000) })) as {
				updated_count?: number
			} | null
			updated += result?.updated_count || 0
		} catch {
			// Best effort Activity drain.
		}
	}
	return updated
}

export async function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
	let timer: ReturnType<typeof setTimeout> | undefined
	try {
		return await Promise.race([
			promise,
			new Promise<T>((resolve) => {
				timer = setTimeout(() => resolve(fallback), ms)
			}),
		])
	} finally {
		if (timer) clearTimeout(timer)
	}
}