75 lines · 3.2 KB
import { env } from "cloudflare:workers";
import type { ClefRequest, ClefResponse } from "./decide";
import { mockProvider } from "./mock";
import type { ChatMessage, MergeFixProvider, TokenUsage } from "./plan";
import { ModelCallError } from "./plan";
import type { ByokKey } from "./store";

const MAX_OUTPUT_TOKENS = 2048;

type ChatReply = {
  response?: unknown;
  choices?: Array<{ message?: { content?: unknown } }>;
  usage?: { prompt_tokens?: number; completion_tokens?: number; input_tokens?: number; output_tokens?: number };
};

function readReply(reply: ChatReply): { text: string; usage: TokenUsage } {
  const raw = reply.choices?.[0]?.message?.content ?? reply.response;
  if (typeof raw !== "string") throw new ModelCallError("The model returned no text");
  return {
    text: raw,
    usage: {
      inputTokens: reply.usage?.prompt_tokens ?? reply.usage?.input_tokens ?? 0,
      outputTokens: reply.usage?.completion_tokens ?? reply.usage?.output_tokens ?? 0,
    },
  };
}

type Unchecked = { run(model: string, inputs: unknown, options?: AiOptions): Promise<unknown> };

/**
 * Both models go through the instance's AI Gateway, tagged with the billed account so Gateway analytics
 * line up with `ai_usage`. With a bring-your-own key the generative call uses the account's provider
 * via Gateway's OpenAI-compatible endpoint; Clef always runs on Workers AI.
 */
export function gatewayProvider(input: { accountId: string; runId: string; byok: ByokKey | null }): MergeFixProvider {
  if (env.MERGEFIX_PROVIDER === "mock") return mockProvider();
  const gatewayId = env.MERGEFIX_GATEWAY_ID || "default";
  const metadata = { account_id: input.accountId, run_id: input.runId, feature: "mergefix" };
  const ai = env.AI as unknown as Unchecked;
  return {