import githubRequest from 'kody:@kentcdodds/github/request' import { DevinApiError, clampInt } from './client.ts' import { type AttentionMessage, type AttentionPr, normalizePrState, parsePrUrl, } from './attention.ts' import { listMessages, type SessionMessage } from '../sessions.ts' /** GitHub account alias passed to `@kentcdodds/github/request` by default. */ export const DEFAULT_GITHUB_ACCOUNT = 'kent' export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } /** Retry Devin 429/5xx a couple of times with short backoff. */ export async function withRetry(fn: () => Promise, retries = 2): Promise { let attempt = 0 while (true) { try { return await fn() } catch (error) { const status = error instanceof DevinApiError ? error.status : 0 const retryable = status === 429 || status >= 500 if (!retryable || attempt >= retries) throw error attempt += 1 await sleep(400 * 2 ** attempt) } } } /** All messages for a session (chronological), following cursors up to `maxPages`. */ export async function fetchAllMessages( devinId: string, orgId?: string, maxPages = 5, ): Promise { const items: SessionMessage[] = [] let after: string | undefined for (let page = 0; page < maxPages; page++) { const result = await withRetry(() => listMessages({ devinId, orgId, first: 200, after }), ) items.push(...(result.items ?? [])) if (!result.has_next_page || !result.end_cursor) break after = result.end_cursor } return items } /** Run `fn` over `items` with at most `limit` in flight. */ export async function mapConcurrent( items: T[], limit: number, fn: (item: T, index: number) => Promise, shouldStart: () => boolean = () => true, ): Promise<{ results: Array; started: number }> { const results: Array = new Array(items.length) let next = 0 async function worker() { while (next < items.length && shouldStart()) { const index = next++ results[index] = await fn(items[index]!, index) } } const size = clampInt(limit, 1, 64, 8) await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker)) return { results, started: next } } type GithubPr = { state?: string merged?: boolean merged_at?: string | null merge_commit_sha?: string | null } /** Read one PR's state and merge commit from GitHub. */ export async function fetchGithubPr( pr: AttentionPr, account: string, ): Promise { const parsed = parsePrUrl(pr.url) if (!parsed) return pr const response = (await githubRequest({ account: account as never, path: `/repos/${parsed.owner}/${parsed.repo}/pulls/${parsed.number}`, timeoutMs: 8000, })) as { ok?: boolean; status?: number; data?: GithubPr } if (!response?.ok || !response.data) { throw new Error(`GitHub PR read failed (${String(response?.status ?? 'error')})`) } const data = response.data const merged = Boolean(data.merged || data.merged_at) return { url: pr.url, state: merged ? 'merged' : normalizePrState(data.state), mergeCommit: merged ? (data.merge_commit_sha ?? null) : null, } } /** * Whether `liveCommit` contains `mergeCommit` (GitHub compare base...head is * `ahead` or `identical`). Null when GitHub cannot say. */ export async function commitIncludedIn( prUrl: string, mergeCommit: string, liveCommit: string, account: string, ): Promise { const parsed = parsePrUrl(prUrl) if (!parsed) return null const response = (await githubRequest({ account: account as never, path: `/repos/${parsed.owner}/${parsed.repo}/compare/${encodeURIComponent(mergeCommit)}...${encodeURIComponent(liveCommit)}`, query: { per_page: '1' }, timeoutMs: 8000, })) as { ok?: boolean; data?: { status?: string } } if (!response?.ok) return null const status = response.data?.status if (status === 'ahead' || status === 'identical') return true if (status === 'behind' || status === 'diverged') return false return null }