import { devinRequest, resolveOrgId } from 'kody:@kentcdodds/devin/request' import { SELF_KODY_ID, type AutomationId, type DevinMode } from './shared.ts' /** Devin v3 create-session path; `{org_id}` is filled in by @kentcdodds/devin/request. */ export const devinCreateSessionPath = '/v3/organizations/{org_id}/sessions' export type DevinSessionRequest = { method: 'POST' path: typeof devinCreateSessionPath body: { prompt: string title: string tags: string[] repos: string[] devin_mode: DevinMode max_acu_limit?: number } } /** * Build the exact Devin create-session request a Devin automation sends. * dryRun returns this object; a live run sends it unchanged. */ export function buildDevinSessionRequest(input: { automation: AutomationId repo: string prompt: string devinMode: DevinMode maxAcuLimit: number | null }): DevinSessionRequest { const body: DevinSessionRequest['body'] = { prompt: input.prompt, title: `${input.automation} ${input.repo}`.slice(0, 80), tags: [SELF_KODY_ID, input.automation], repos: [input.repo], devin_mode: input.devinMode, } if (typeof input.maxAcuLimit === 'number' && input.maxAcuLimit > 0) { body.max_acu_limit = input.maxAcuLimit } return { method: 'POST', path: devinCreateSessionPath, body } } /** True when @kentcdodds/devin has an org id saved (never returns the id). */ export async function devinOrgConfigured() { try { return Boolean(await resolveOrgId()) } catch { return false } } /** Send a create-session request. Consumes ACUs. */ export async function launchDevinSession(request: DevinSessionRequest) { const result = await devinRequest({ path: request.path, method: request.method, body: request.body, }) const body = (result.body ?? {}) as { session_id?: string url?: string devin_mode?: string | null detail?: unknown title?: unknown } if (result.status < 200 || result.status >= 300) { const detail = typeof body.detail === 'string' ? body.detail : typeof body.title === 'string' ? body.title : '' throw new Error(`Devin create session failed (${result.status})${detail ? `: ${detail}` : ''}`) } return { sessionId: body.session_id ?? null, url: body.url ?? null, devinMode: body.devin_mode ?? null, } }