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

events-runner.ts

116 lines · 5.1 KB · TypeScript
/**
 * AgentRunner that talks to a runner package only through events. Start,
 * message, and cancel emit `@kody/factory.agent.*.requested`; status reads the
 * last `@kody/<runner>.session.*` event the factory stored. A started run has
 * the id `pending_<requestId>` until the runner's `session.started` arrives;
 * status resolves a pending id through the stored request index, and reports
 * the real `runId` so the caller can adopt it.
 */
import { TOPICS, emitFactoryEvent, clipToBytes, eventKey } from '../events/emit.ts'
import type { AgentRunner, AgentRunState, AgentStatusResult, AgentTask } from '../adapters/agent/types.ts'
import { loadRunnerSession, runIdForRequest, type RunnerSession } from './store.ts'

const PROMPT_BUDGET = 40 * 1024
const STATES = new Set<AgentRunState>(['queued', 'running', 'succeeded', 'failed', 'cancelled', 'timed_out', 'unknown'])

export const PENDING_PREFIX = 'pending_'

export type AgentStartRequest = {
	runner: string
	prompt: string
	title: string
	tags: string[]
	repos?: string[]
	projectId?: string
	workItemId?: string
	/** Runner-specific session mode (Devin reads it as `devin_mode`). */
	mode?: string
	/** Session budget hint for the runner (Devin: ACU limit). */
	maxAcuLimit?: number
	/** The runner checks the request and starts nothing. */
	dryRun?: boolean
}

/**
 * Ask the runner package to start a session. Returns the pending run id
 * (`pending_<requestId>`) that the runner's `session.started` later resolves.
 */
export async function requestAgentStart(req: AgentStartRequest): Promise<{ requestId: string; runId: string }> {
	const requestId = crypto.randomUUID().replace(/-/g, '').slice(0, 20)
	const r = await emitFactoryEvent(TOPICS.agentStartRequested, eventKey('agent-start', req.runner, req.workItemId ?? req.title.slice(0, 40), requestId), {
		runner: req.runner,
		requestId,
		prompt: clipToBytes(req.prompt, PROMPT_BUDGET),
		title: req.title.slice(0, 200),
		tags: req.tags.slice(0, 20),
		repos: (req.repos ?? []).slice(0, 10),
		...(req.projectId ? { projectId: req.projectId } : {}),
		...(req.workItemId ? { workItemId: req.workItemId } : {}),
		...(req.mode ? { mode: req.mode } : {}),
		...(typeof req.maxAcuLimit === 'number' && req.maxAcuLimit > 0 ? { maxAcuLimit: Math.floor(req.maxAcuLimit) } : {}),
		...(req.dryRun ? { dryRun: true } : {}),
	})
	if (!r.emitted) throw new Error(`could not request a ${req.runner} start: ${r.error ?? r.skipped ?? 'emit failed'}`)
	return { requestId, runId: `${PENDING_PREFIX}${requestId}` }
}

/** The latest runner-reported session for a run id, resolving `pending_<requestId>` ids. */
export async function resolveRunnerSession(runId: string): Promise<RunnerSession | null> {
	if (runId.startsWith(PENDING_PREFIX)) {
		const real = await runIdForRequest(runId.slice(PENDING_PREFIX.length))
		return real ? loadRunnerSession(real) : null
	}
	return loadRunnerSession(runId)
}

export function eventsRunner(runnerId: string, label = runnerId): AgentRunner {
	return {
		id: runnerId,
		displayName: `${label} (events)`,
		capabilities: ['implement', 'review', 'verify'],
		onComplete: { mode: 'poll', pollIntervalMs: 60_000 },
		async start(task: AgentTask) {
			if (task.dryRun) return { runId: `${runnerId}_dry_${crypto.randomUUID().replace(/-/g, '').slice(0, 20)}` }
			const { runId } = await requestAgentStart({
				runner: runnerId,
				prompt: task.prompt,
				title: `factory:${task.projectId}:${task.workItemId}`,
				tags: ['kody-factory', task.projectId, task.workItemId],
				repos: task.repoRef ? [task.repoRef] : [],
				projectId: task.projectId,
				workItemId: task.workItemId,
			})
			return { runId }
		},
		async status(runId: string): Promise<AgentStatusResult> {
			if (runId.includes('_dry_')) return { state: 'succeeded', summary: 'dry-run session' }
			const s = await resolveRunnerSession(runId)
			if (!s) {
				return runId.startsWith(PENDING_PREFIX)
					? { state: 'queued', summary: `waiting for ${runnerId} to report the started session` }
					: { state: 'unknown', summary: `no ${runnerId} session event yet` }
			}
			return {
				state: STATES.has(s.state as AgentRunState) ? (s.state as AgentRunState) : 'unknown',
				url: s.url,
				summary: s.statusDetail ?? s.title,
				updatedAt: s.updatedAt ?? s.receivedAt,
				pullRequests: (s.pullRequests ?? []).map((p) => ({ url: p.url, state: p.state ?? null })),
				...(s.runId !== runId ? { runId: s.runId } : {}),
			}
		},
		async message(runId: string, text: string) {
			if (runId.includes('_dry_')) return false
			const real = runId.startsWith(PENDING_PREFIX) ? (await resolveRunnerSession(runId))?.runId : runId
			if (!real) return false
			const r = await emitFactoryEvent(TOPICS.agentMessageRequested, eventKey('agent-message', runnerId, real, crypto.randomUUID().slice(0, 8)), { runner: runnerId, runId: real, text: clipToBytes(text, PROMPT_BUDGET) })
			return r.emitted
		},
		async cancel(runId: string) {
			if (runId.includes('_dry_')) return
			const real = runId.startsWith(PENDING_PREFIX) ? (await resolveRunnerSession(runId))?.runId : runId
			if (!real) return
			await emitFactoryEvent(TOPICS.agentCancelRequested, eventKey('agent-cancel', runnerId, real), { runner: runnerId, runId: real })
		},
	}
}