import { createContexta } from "./server.ts"; import type { AdContext } from "./types.ts"; import type { ConversationMessage } from "./classify.ts"; export interface TrustedConversation { context: Omit; messages: ConversationMessage[]; userTurn: number; } /** Framework-neutral Request -> Response route, with authentication supplied by the host. * Never implement loadContext by returning unverified JSON from the request body. */ export function createPartnerAdHandler(options: { baseUrl: string; apiKey: string; loadContext: (request: Request) => Promise; classifier?: (messages: ConversationMessage[]) => Promise; fetch?: typeof fetch; }) { const client = createContexta(options); return async (request: Request): Promise => { const reply = (value: unknown, status = 200) => Response.json(value, { status, headers: { "cache-control": "no-store" } }); if (request.method !== "POST") return reply({ ad: null, reason: "method_not_allowed" }, 405); try { const conversation = await options.loadContext(request); if (!conversation) return reply({ ad: null, reason: "not_eligible" }); return reply(await client.decideConversation(conversation)); } catch { return reply({ ad: null, reason: "unavailable" }); } }; }