iterate.com / cloud

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

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

import type { ItxWebSearchAnswer, RewriteRuleConfigured, SecretProxy } from "iterate/api";
import type { StreamEventInput } from "iterate/stream/processor";
import type { CloudGatewayRunOptions } from "./ai-target.ts";
import type {
  GatewaySpendReport,
  IterateCloudUsageReport,
  OpenAiUsageByMindInput,
  OpenAiUsageByMindReport,
  UsageWindowInput,
} from "./usage.ts";

export interface IterateCloudAiClient {
  run(model: string, inputs: Record<string, unknown>, options?: AiOptions): Promise<unknown>;
  models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;
  websearch(
    request: Omit<AiWebSearchRequest, "gatewayId"> & { gatewayId?: string },
  ): Promise<ItxWebSearchAnswer>;
  gateway(gatewayId?: string): {
    run(
      data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
      options?: CloudGatewayRunOptions,
    ): Promise<unknown>;
    runRaw(
      data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
      options?: CloudGatewayRunOptions,
    ): Promise<Response>;
  };
  usage(window?: UsageWindowInput): Promise<GatewaySpendReport>;
}

export interface IterateCloudClientApi {
  whoami(): Promise<{
    mindId: string;
    mindSlug: string;
    gatewayId: string;
    responsesWebSocketUrl?: string;
  }>;
  /** Unified per-mind usage & USD spend across BOTH Cloudflare AI Gateway AND Iterate Cloud's
   *  lent OpenAI API key for realtime voice & transcription. */
  usage(window?: UsageWindowInput): Promise<IterateCloudUsageReport>;
  /** Every mind's OpenAI-direct spend (voice, transcription) by UTC day. The Cloud answers it to
   *  its own mind alone and refuses every other mind. */
  openAiUsageByMind(input?: OpenAiUsageByMindInput): Promise<OpenAiUsageByMindReport>;
  readonly ai: IterateCloudAiClient;
}

declare module "iterate/api" {
  interface InstalledAppRoots {
    iterateCloud: IterateCloudClientApi;
  }
}

export type CloudConfigurableContext = {
  secrets: {
    describe(path: string): Promise<{ path: string; set: boolean; proxy?: SecretProxy }>;
    deleteIfProxy(path: string): Promise<{ path: string; deleted: boolean }>;
    set(
      path: string,
      material: null,
      options: { urls: string[]; placement: "header"; proxy: SecretProxy },
    ): Promise<{ path: string }>;
  };
  append(...events: StreamEventInput[]): Promise<unknown>;
};

export type OpenAiSecretLendingStatus = "proxy" | "own-key" | "skipped";

export type ConnectIterateCloudOptions = {
  /** Iterate Cloud origin (default `"https://cloud.iterate.com"`). */
  cloudOrigin?: string;
  /** Iterate Cloud mind control-plane hostname or mind id (default `"iterate.iterate.com"`). */
  cloudMind?: string;
  /** Secret path holding the `SecretProxy` that signs requests and WebSockets as this mind. */
  secretPath?: string;
  /** Rewrite `itx.ai` -> `itx.iterateCloud.ai` so agents, `ai-linter`, and scripts use Iterate
   *  Cloud's `env.AI` + AI Gateway without code changes (default `true`). */
  replaceItxAi?: boolean;
  /** Also set `/secrets/openai` as a `SecretProxy` (`urls: ["https://api.openai.com"]`) for
   *  realtime voice & transcription when no owner key is already set (default `true`). */
  lendOpenAiKey?: boolean;
};

/** Connects an enrolled mind's root context `/` to Iterate Cloud's AI Gateway + OpenAI voice &
 *  transcription proxy using existing platform primitives — zero changes to `core/`:
 *
 *  1. Configures a `SecretProxy` at `/secrets/iterate-cloud` (`material: null`, `proxy: { mind, url }`)
 *     so `secrets-worker` signs outgoing HTTP and WebSocket upgrades with this mind's ML-DSA-65
 *     working key (`iterate-auth-statement: events.iterate.com/mind/fetch-requested`).
 *  2. Unless `lendOpenAiKey` is `false` (or the owner already stored their own `/secrets/openai` key),
 *     configures `/secrets/openai` as a `SecretProxy` (`urls: ["https://api.openai.com"]`) so
 *     realtime voice (`packages/voice`, `call/outbound.ts`) and transcription (`v1/audio/transcriptions`,
 *     `v1/realtime`) work out of the box and report into `itx.iterateCloud.usage()`.
 *  3. Appends a rewrite rule `itx.iterateCloud` -> `connectToCapnweb("wss://<cloudHost>/api/cloud-ai", ...)`
 *     exposing `itx.iterateCloud.whoami()`, `itx.iterateCloud.usage()`, and `itx.iterateCloud.ai.*`. */
export async function connectIterateCloud(
  itx: { cd(path: string): CloudConfigurableContext },
  options: ConnectIterateCloudOptions = {},
): Promise<{
  secretPath: string;
  proxyUrl: string;
  capnwebUrl: string;
  responsesWebSocketUrl: string;
  replacedItxAi: boolean;
  openAiSecret: OpenAiSecretLendingStatus;
}> {
  const originUrl = new URL(options.cloudOrigin || "https://cloud.iterate.com");
  if (originUrl.protocol !== "https:" || originUrl.pathname !== "/") {
    throw new Error("cloudOrigin must be an exact https:// origin with no path");
  }
  const cloudOrigin = originUrl.origin;
  const cloudMind = options.cloudMind || "iterate.iterate.com";
  const secretPath = options.secretPath || "/secrets/iterate-cloud";
  const proxyUrl = `${cloudOrigin}/capnweb`;
  const capnwebUrl = `wss://${originUrl.host}/api/cloud-ai`;
  const responsesWebSocketUrl = `${cloudOrigin}/ai-ws/openai/responses`;
  const replaceItxAi = options.replaceItxAi !== false;

  const root = itx.cd("/");
  await ensureSecretProxy(root, secretPath, [cloudOrigin], { mind: cloudMind, url: proxyUrl });

  let openAiSecret: OpenAiSecretLendingStatus = "skipped";
  if (options.lendOpenAiKey !== false) {
    openAiSecret = await ensureSecretProxy(root, "/secrets/openai", ["https://api.openai.com"], {
      mind: cloudMind,
      url: proxyUrl,
    });
  }

  const rules: { type: string; payload: RewriteRuleConfigured }[] = [
    {
      type: "events.iterate.com/itx/rewrite-rule-configured",
      payload: {
        match: "itx.iterateCloud",
        target: [
          "itx",
          ["cd", "/"],
          [
            "connectToCapnweb",
            capnwebUrl,
            {
              headers: {
                authorization: `Bearer getSecret(${JSON.stringify(secretPath)})`,
              },
            },
          ],
        ],
        description:
          "Iterate Cloud capabilities over Cap'n Web (`itx.iterateCloud.ai` and `itx.iterateCloud.usage()`).",
      },
    },
  ];

  if (replaceItxAi) {
    rules.push({
      type: "events.iterate.com/itx/rewrite-rule-configured",
      payload: {
        match: "itx.ai",
        target: "itx.iterateCloud.ai",
        description: "Route `itx.ai` through Iterate Cloud's AI Gateway (`itx.iterateCloud.ai`).",
      },
    });
  }

  await root.append(...rules);

  return {
    secretPath,
    proxyUrl,
    capnwebUrl,
    responsesWebSocketUrl,
    replacedItxAi: replaceItxAi,
    openAiSecret,
  };
}

async function ensureSecretProxy(
  root: CloudConfigurableContext,
  path: string,
  urls: string[],
  proxy: SecretProxy,
): Promise<"proxy" | "own-key"> {
  const existing = await root.secrets.describe(path);
  if (existing.set && !existing.proxy) {
    return "own-key";
  }
  const sameProxy =
    existing.set && existing.proxy?.mind === proxy.mind && existing.proxy.url === proxy.url;
  if (!sameProxy) {
    if (existing.set && existing.proxy) {
      await root.secrets.deleteIfProxy(path);
    }
    await root.secrets.set(path, null, {
      urls,
      placement: "header",
      proxy,
    });
  }
  return "proxy";
}