|
| 1 | +// https://docs.devin.ai/api-reference/sessions/list-sessions. |
| 2 | +import { DEVIN_API_BASE_URL, fetchFromDevin } from "./shared"; |
| 3 | + |
| 4 | +const DEFAULT_PAGE_SIZE = 100; |
| 5 | +const MAX_PAGES = 50; |
| 6 | + |
| 7 | +export interface DevinSession { |
| 8 | + session_id: string; |
| 9 | + status: string; |
| 10 | + created_at: string; |
| 11 | + updated_at: string; |
| 12 | + title?: string; |
| 13 | + pull_request: { |
| 14 | + url: string; |
| 15 | + } | null; |
| 16 | +} |
| 17 | + |
| 18 | +interface ListSessionsResponse { |
| 19 | + sessions: DevinSession[]; |
| 20 | +} |
| 21 | + |
| 22 | +interface ListSessionsOptions { |
| 23 | + limit?: number; |
| 24 | + offset?: number; |
| 25 | + status?: string; |
| 26 | +} |
| 27 | + |
| 28 | +export async function listDevinSessions( |
| 29 | + options: ListSessionsOptions = {}, |
| 30 | +): Promise<ListSessionsResponse> { |
| 31 | + const url = new URL(`${DEVIN_API_BASE_URL}/sessions`); |
| 32 | + const limit = options.limit ?? DEFAULT_PAGE_SIZE; |
| 33 | + const offset = options.offset ?? 0; |
| 34 | + |
| 35 | + url.searchParams.set("limit", limit.toString()); |
| 36 | + url.searchParams.set("offset", offset.toString()); |
| 37 | + |
| 38 | + if (options.status) { |
| 39 | + url.searchParams.set("status", options.status); |
| 40 | + } |
| 41 | + |
| 42 | + const response = await fetchFromDevin(url.toString(), { |
| 43 | + method: "GET", |
| 44 | + }); |
| 45 | + |
| 46 | + return (await response.json()) as ListSessionsResponse; |
| 47 | +} |
| 48 | + |
| 49 | +export async function findRunningSessionForPR( |
| 50 | + prUrl: string, |
| 51 | +): Promise<DevinSession | null> { |
| 52 | + let offset = 0; |
| 53 | + const limit = DEFAULT_PAGE_SIZE; |
| 54 | + |
| 55 | + for (let i = 0; i < MAX_PAGES; i++) { |
| 56 | + const { sessions } = await listDevinSessions({ |
| 57 | + limit, |
| 58 | + offset, |
| 59 | + status: "running", |
| 60 | + }); |
| 61 | + |
| 62 | + if (sessions.length === 0) { |
| 63 | + break; |
| 64 | + } |
| 65 | + |
| 66 | + const match = sessions.find( |
| 67 | + (session) => session.pull_request?.url === prUrl, |
| 68 | + ); |
| 69 | + if (match) { |
| 70 | + return match; |
| 71 | + } |
| 72 | + |
| 73 | + if (sessions.length < limit) { |
| 74 | + break; |
| 75 | + } |
| 76 | + |
| 77 | + offset += limit; |
| 78 | + } |
| 79 | + |
| 80 | + return null; |
| 81 | +} |
0 commit comments