iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / cloud-ai / src / worker.tsmain at aacbc74

import { newWorkersRpcResponse } from "capnweb";
import { IterateCloudApi, stampCloudGatewayMetadata } from "./ai-target.ts";
import {
  type AuthenticatedMind,
  type CloudAiAuthEnv,
  createMindAuthenticator,
  jsonError,
  type MindAuthenticatorOptions,
} from "./auth.ts";
import {
  CloudUsageLedger,
  createInMemoryOpenAiUsageStore,
  durableObjectUsageStore,
  type OpenAiUsageStore,
} from "./ledger.ts";
import {
  handleOpenAiVoiceOrTranscribe,
  type OpenAiVoiceRelayDeps,
  openAiProxySubpathOf,
} from "./openai-voice.ts";

export { CloudUsageLedger };

const ALLOWED_WS_UPSTREAMS = new Set(["openai/responses", "openai/v1/responses", "openai"]);

export type CloudAiEnv = CloudAiAuthEnv & {
  AI: Ai;
  CLOUD_AI_GATEWAY?: string;
  CLOUDFLARE_ACCOUNT_ID?: string;
  CLOUDFLARE_ANALYTICS_API_TOKEN?: string;
  /** Optional dedicated Cloudflare token with `AI Gateway - Run`; falls back to `CLOUDFLARE_ANALYTICS_API_TOKEN`. */
  CLOUDFLARE_AIG_TOKEN?: string;
  /** Iterate Cloud's OpenAI service-account key lent for Realtime Voice & Transcription. */
  OPENAI_API_KEY?: string;
  /** Per-mind SQLite Durable Object ledger storing OpenAI voice & transcription usage. */
  USAGE_LEDGER?: DurableObjectNamespace<CloudUsageLedger>;
};

export type CloudAiHandlerOptions = MindAuthenticatorOptions & {
  analyticsFetcher?: (request: Request) => Promise<Response>;
  gatewayWsFetcher?: (request: Request) => Promise<Response>;
  openAiVoiceDeps?: OpenAiVoiceRelayDeps;
  openAiUsageStore?: OpenAiUsageStore;
};

/** Whether a request URL belongs to Iterate Cloud AI:
 *  - `/api/cloud-ai` for direct Cap'n Web mind sessions
 *  - `/ai-ws/<provider>/<endpoint>` for direct AI Gateway WebSocket upgrades (OpenAI Responses WS)
 *  - `/openai-voice/<subpath>` for direct OpenAI Realtime Voice & Transcription
 *  - `/capnweb/<host>/...` when routed through a mind's `SecretProxy`
 *    (`/secrets/iterate-cloud` or `/secrets/openai` -> `https://.../capnweb`). */
export function handles({ pathname }: URL): boolean {
  return (
    pathname === "/api/cloud-ai" ||
    pathname.startsWith("/ai-ws/") ||
    pathname.startsWith("/openai-voice/") ||
    pathname === "/capnweb" ||
    pathname.startsWith("/capnweb/")
  );
}

/** Extracts the AI Gateway WebSocket subpath (`openai/responses`, etc.) when `pathname` targets
 *  `/ai-ws/<subpath>` directly or `/capnweb/<host>/ai-ws/<subpath>` via `SecretProxy`. */
export function aiWebSocketSubpathOf(pathname: string): string | null {
  if (pathname.startsWith("/ai-ws/")) return pathname.slice("/ai-ws/".length);
  const proxyMatch = /^\/capnweb\/[^/]+\/ai-ws\/(.+)$/.exec(pathname);
  return proxyMatch?.[1] || null;
}

export function createCloudAiHandler(options: CloudAiHandlerOptions = {}) {
  const authenticate = createMindAuthenticator(options);
  const wsFetcher = options.gatewayWsFetcher || ((request: Request) => fetch(request));
  const fallbackUsageStore = options.openAiUsageStore || createInMemoryOpenAiUsageStore();

  return {
    async fetch(request: Request, env: CloudAiEnv): Promise<Response> {
      const url = new URL(request.url);
      if (!handles(url)) return jsonError(404, "Not found");
      if (request.method !== "GET" && request.method !== "POST") {
        return jsonError(405, "Method not allowed");
      }

      const authResult = await authenticate(request, env);
      if ("response" in authResult) return authResult.response;

      const usageStore = env.USAGE_LEDGER
        ? durableObjectUsageStore(env.USAGE_LEDGER)
        : fallbackUsageStore;

      const openAiSubpath = openAiProxySubpathOf(url.pathname);
      if (openAiSubpath) {
        return handleOpenAiVoiceOrTranscribe({
          request,
          url,
          subpath: openAiSubpath,
          caller: authResult.caller,
          openAiApiKey: env.OPENAI_API_KEY,
          usageStore,
          deps: options.openAiVoiceDeps,
        });
      }

      const gatewayId = env.CLOUD_AI_GATEWAY || "iterate-cloud";
      const wsSubpath = aiWebSocketSubpathOf(url.pathname);
      if (wsSubpath) {
        return forwardAiGatewayWebSocket(
          request,
          url,
          wsSubpath,
          authResult.caller,
          gatewayId,
          env,
          wsFetcher,
        );
      }

      const analytics =
        env.CLOUDFLARE_ACCOUNT_ID && env.CLOUDFLARE_ANALYTICS_API_TOKEN
          ? {
              accountId: env.CLOUDFLARE_ACCOUNT_ID,
              apiToken: env.CLOUDFLARE_ANALYTICS_API_TOKEN,
              fetcher: options.analyticsFetcher,
            }
          : undefined;

      return newWorkersRpcResponse(
        request,
        new IterateCloudApi(authResult.caller, {
          ai: env.AI,
          gatewayId,
          cloudOrigin: url.origin,
          analytics,
          openAiUsageStore: usageStore,
          ownMind: { id: env.MIND_ID, hostname: env.MIND_HOSTNAME },
        }),
      );
    },
  } satisfies ExportedHandler<CloudAiEnv>;
}

async function forwardAiGatewayWebSocket(
  request: Request,
  url: URL,
  subpath: string,
  caller: AuthenticatedMind,
  gatewayId: string,
  env: CloudAiEnv,
  wsFetcher: (request: Request) => Promise<Response>,
): Promise<Response> {
  if (!ALLOWED_WS_UPSTREAMS.has(subpath)) {
    return jsonError(404, `unsupported AI Gateway WebSocket path: ${subpath}`);
  }
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
    return jsonError(426, "AI Gateway WebSocket endpoint requires Upgrade: websocket");
  }
  const gatewayToken = env.CLOUDFLARE_AIG_TOKEN || env.CLOUDFLARE_ANALYTICS_API_TOKEN;
  if (!env.CLOUDFLARE_ACCOUNT_ID || !gatewayToken) {
    return jsonError(503, "AI Gateway WebSocket credentials are not configured", {
      "retry-after": "5",
    });
  }

  const metadata = stampCloudGatewayMetadata(caller, {
    streamPath: request.headers.get("x-iterate-stream-path") || undefined,
    context: request.headers.get("x-iterate-context") || "agent-turn",
  });

  const headers = new Headers();
  headers.set("upgrade", "websocket");
  headers.set("connection", "Upgrade");
  const protocol = request.headers.get("sec-websocket-protocol");
  if (protocol) headers.set("sec-websocket-protocol", protocol);
  const openAiBeta = request.headers.get("openai-beta");
  if (openAiBeta) headers.set("openai-beta", openAiBeta);
  headers.set("cf-aig-authorization", `Bearer ${gatewayToken}`);
  headers.set("cf-aig-metadata", JSON.stringify(metadata));
  headers.set("cf-aig-collect-log-payload", "false");

  const upstreamUrl = `https://gateway.ai.cloudflare.com/v1/${env.CLOUDFLARE_ACCOUNT_ID}/${gatewayId}/${subpath}${url.search}`;
  return wsFetcher(new Request(upstreamUrl, { method: "GET", headers }));
}

export default createCloudAiHandler();