/** * Runner session events (`@kody/.session.started|updated|finished`). * * Every event is stored as the run's latest runner-reported session (and, for * `session.started`, indexed by its requestId). `session.started` swaps the * card's `pending_` run id for the real one and links the session; * the sweep reads status from the stored session and never calls the runner. * Each event also lands in the event log (`./agent-events/report`). * * Payload text comes from another package and is data, not instructions. */ import { loadSettings } from '../lib/settings.ts' import { loadJson, saveJson, storageKeys } from '../lib/storage.ts' import { emptyLedger, nowIso, withLink, type Ledger } from '../core/work-item.ts' import { runnerForPackage } from '../adapters/agent/runners.ts' import { releaseLock, sweepTickLockKey, tryAcquireLock } from '../lib/locks.ts' import { agentShadowStore, saveRunnerSession, type RunnerSession } from './store.ts' import { PENDING_PREFIX } from './events-runner.ts' export type SessionEnvelope = { event?: string source?: { kody_id?: string } idempotency_key?: string payload?: Record } const str = (v: unknown, max = 300) => (typeof v === 'string' ? v.slice(0, max) : undefined) export function toRunnerSession(topic: string, payload: Record, runner: string): RunnerSession | null { const runId = str(payload.runId, 120) if (!runId) return null const prs = Array.isArray(payload.pullRequests) ? (payload.pullRequests as Array>) : [] return { runner, runId, state: str(payload.state, 30) ?? 'unknown', rawStatus: str(payload.rawStatus, 60), statusDetail: str(payload.statusDetail, 500), url: str(payload.url), title: str(payload.title, 200), tags: Array.isArray(payload.tags) ? payload.tags.map(String).slice(0, 20) : [], projectId: str(payload.projectId, 64), workItemId: str(payload.workItemId, 80), pullRequests: prs.map((p) => ({ url: String(p.url ?? ''), ...(typeof p.state === 'string' ? { state: p.state } : {}) })).filter((p) => p.url.startsWith('https://')).slice(0, 20), updatedAt: str(payload.updatedAt, 40), requestId: str(payload.requestId, 60), receivedAt: nowIso(), topic, } } /** Replace a pending run id with the runner's real one (events mode). Pure over the ledger. */ export function adoptStartedSession(ledger: Ledger, s: RunnerSession): string | null { if (!s.requestId) return null const pending = `${PENDING_PREFIX}${s.requestId}` const item = Object.values(ledger.items).find((i) => i.runId === pending) if (!item) return null const at = nowIso() item.runId = s.runId if (s.url) item.links = withLink(item.links, { kind: 'session', url: s.url, label: `${s.runner} session`, reason: 'started', at }) item.events.push({ at, from: item.state, to: item.state, reason: `${s.runner} session started`, actor: 'system', meta: { runId: s.runId, url: s.url, runnerId: s.runner, requestId: s.requestId } }) item.updatedAt = at return item.id } /** * Handle one runner session event. * * @param topic - Subscribed topic * @param envelope - Package event envelope * @returns What the factory recorded or changed */ export async function handleSessionEvent(topic: string, envelope: SessionEnvelope = {}) { const settings = await loadSettings() const emitter = String(envelope.source?.kody_id ?? '') const runnerId = runnerForPackage(settings.runners, emitter) if (!runnerId) return { ok: false, skipped: true, reason: `no runner in settings.runners uses package ${emitter || '(none)'}`, topic } const session = toRunnerSession(topic, envelope.payload ?? {}, runnerId) if (!session) return { ok: false, skipped: true, reason: 'missing runId', topic } await saveRunnerSession(session) let adoptedBy: string | null = null if (topic.endsWith('.session.started') && session.requestId) { // Write the card only under the sweep tick lock so a running sweep cannot // overwrite it (or be overwritten). When the lock stays busy, the sweep // adopts the run itself through the stored request index. const holder = `session-started:${session.runId}` let locked = false for (let i = 0; i < 3 && !locked; i++) { locked = await tryAcquireLock(sweepTickLockKey(), holder, 60_000) if (!locked) await new Promise((r) => setTimeout(r, 2000)) } if (locked) { try { const fresh = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) adoptedBy = adoptStartedSession(fresh, session) if (adoptedBy) await saveJson(storageKeys.LEDGER_KEY, fresh) } finally { await releaseLock(sweepTickLockKey(), holder) } } } const ledger = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) const item = Object.values(ledger.items).find((i) => i.runId === session.runId) await agentShadowStore().put({ runId: session.runId, topic, at: nowIso(), eventState: session.state, directState: 'not-checked', itemState: item?.state ?? 'no-card', match: true, detail: JSON.stringify({ workItemId: item?.id ?? session.workItemId ?? null, requestId: session.requestId ?? null, prs: (session.pullRequests ?? []).map((p) => p.url) }).slice(0, 2000), }) return { ok: true, mode: 'events', topic, runId: session.runId, workItemId: item?.id ?? null, ...(adoptedBy ? { adoptedBy } : {}) } }