iterate.com / cloud

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

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

import { RpcTarget } from "capnweb";
import type { ItxWebSearchAnswer } from "iterate/api";
import { codedError } from "iterate/lib";
import { httpFailureKind } from "iterate/platform-retry";
import { isMindId } from "iterate/signed";
import { z } from "zod";
import type { AuthenticatedMind } from "./auth.ts";
import { createInMemoryOpenAiUsageStore, type OpenAiUsageStore } from "./ledger.ts";
import {
  combineCloudUsageReports,
  emptyGatewaySpendReport,
  type GatewaySpendReport,
  type IterateCloudUsageReport,
  type OpenAiUsageByMindInput,
  type OpenAiUsageByMindReport,
  openAiUsageByMindReport,
  queryGatewaySpend,
  resolveUsageWindow,
  type UsageWindowInput,
} from "./usage.ts";

const ANSWER_MAX_BYTES = 10 * 1024 * 1024;
const WORKER_TAG_PATTERN = /^[A-Za-z0-9:./@-]{1,50}$/;

const WebSearchAnswer = z.looseObject({
  items: z.array(
    z.looseObject({ url: z.string(), title: z.string(), description: z.string().optional() }),
  ),
  metadata: z.looseObject({ query: z.string(), requestId: z.string(), latencyMs: z.number() }),
});

type GatewayMetadata = NonNullable<GatewayOptions["metadata"]>;

export type CloudAiDeps = {
  ai: Ai;
  gatewayId: string;
  cloudOrigin?: string;
  analytics?: {
    accountId: string;
    apiToken: string;
    fetcher?: (request: Request) => Promise<Response>;
  };
  openAiUsageStore?: OpenAiUsageStore;
  /** THE CLOUD'S OWN MIND (`MIND_ID` and `MIND_HOSTNAME` of the Worker): the one mind that reads
   *  every mind's spend (`IterateCloudApi.openAiUsageByMind`). With no id, no mind does. */
  ownMind?: { id?: string; hostname?: string };
};

/** Builds the AI Gateway `metadata` object for an authenticated mind. Cloudflare AI Gateway keeps
 *  at most 5 flat scalar (`string | number | boolean`) entries and strips `cf.*` keys, so `mindId`,
 *  `mindSlug` and `spendPlan` are locked in positions 1 to 3 where caller keys can neither
 *  overwrite them nor push them past the 5-entry cap. `spendPlan` says which spend rules of the
 *  gateway count the request (`SpendPlan` in ./auth.ts); a caller with none is `standard`. The
 *  caller's `streamPath` and `context` take the two entries that are left. */
export function stampCloudGatewayMetadata(
  caller: Pick<AuthenticatedMind, "mindId" | "mindSlug" | "spendPlan">,
  given?: Record<string, unknown>,
): GatewayMetadata {
  const out: GatewayMetadata = {
    mindId: caller.mindId,
    mindSlug: caller.mindSlug,
    spendPlan: caller.spendPlan || "standard",
  };
  if (!given) return out;

  for (const preferred of ["streamPath", "context"] as const) {
    const scalar = scalarMetadataValue(given[preferred]);
    if (scalar !== undefined) out[preferred] = scalar;
  }

  for (const [key, rawValue] of Object.entries(given)) {
    if (Object.keys(out).length >= 5) break;
    if (key in out || key.startsWith("cf.")) continue;
    if (!/^[A-Za-z0-9_.-]{1,64}$/.test(key)) continue;
    const scalar = scalarMetadataValue(rawValue);
    if (scalar !== undefined) out[key] = scalar;
  }

  return out;
}

function scalarMetadataValue(value: unknown): string | number | boolean | undefined {
  if (typeof value === "string") return value.slice(0, 128);
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "boolean") return value;
  return undefined;
}

/** Strips provider credentials and any caller-supplied `cf-aig-*` control headers (which could
 *  disable logging, override metadata, or alter caching/timeouts), then forces payload collection
 *  off so AI Gateway records cost, tokens, model, and `mindId` metadata without storing prompts. */
export function sanitizeExtraHeaders(given?: object): Record<string, string> {
  const cleaned: Record<string, string> = {};
  if (given) {
    for (const [name, value] of Object.entries(given)) {
      const lower = name.toLowerCase();
      if (lower.startsWith("cf-aig-") || lower === "authorization" || lower === "x-api-key") {
        continue;
      }
      if (typeof value === "string") cleaned[name] = value;
      else if (typeof value === "number" || typeof value === "boolean") {
        cleaned[name] = String(value);
      }
    }
  }
  cleaned["cf-aig-collect-log-payload"] = "false";
  return cleaned;
}

/** Builds Workers AI Neuron attribution `tags` (max 5 tags, `<= 50` chars `[A-Za-z0-9:./@-]`),
 *  always pinning `mind:<mindSlug>` first and dropping caller `mind:*` tags. */
export function stampWorkersAiTags(mindSlug: string, given?: string[]): string[] {
  const safeSlug = mindSlug.replace(/[^A-Za-z0-9:./@-]/g, "-").slice(0, 45);
  const tags = [`mind:${safeSlug}`];
  if (!given) return tags;
  for (const tag of given) {
    if (tags.length >= 5) break;
    if (!tag || tag.startsWith("mind:")) continue;
    if (WORKER_TAG_PATTERN.test(tag) && !tags.includes(tag)) tags.push(tag);
  }
  return tags;
}

/** Root Cap'n Web capability exposed to an enrolled mind as `itx.iterateCloud`. */
export class IterateCloudApi extends RpcTarget {
  readonly #caller: AuthenticatedMind;
  readonly #deps: CloudAiDeps;

  constructor(caller: AuthenticatedMind, deps: CloudAiDeps) {
    super();
    this.#caller = caller;
    this.#deps = deps;
  }

  whoami(): {
    mindId: string;
    mindSlug: string;
    gatewayId: string;
    responsesWebSocketUrl?: string;
  } {
    return {
      mindId: this.#caller.mindId,
      mindSlug: this.#caller.mindSlug,
      gatewayId: this.#deps.gatewayId,
      ...(this.#deps.cloudOrigin && {
        responsesWebSocketUrl: `${this.#deps.cloudOrigin}/ai-ws/openai/responses`,
      }),
    };
  }

  /** Unified per-mind usage & USD spend across BOTH Cloudflare AI Gateway (`itx.iterateCloud.ai`
   *  + `/ai-ws/openai/responses`) AND Iterate Cloud's lent OpenAI API key for realtime voice &
   *  transcription (`/secrets/openai` `SecretProxy` -> `/capnweb/api.openai.com/...`). */
  async usage(window?: UsageWindowInput): Promise<IterateCloudUsageReport> {
    const resolved = resolveUsageWindow(window);
    const store = this.#deps.openAiUsageStore || createInMemoryOpenAiUsageStore();
    const [aiGateway, openAi] = await Promise.all([
      this.#deps.analytics
        ? queryGatewaySpend({
            ...window,
            since: resolved.since,
            until: resolved.until,
            accountId: this.#deps.analytics.accountId,
            apiToken: this.#deps.analytics.apiToken,
            fetcher: this.#deps.analytics.fetcher,
            gatewayId: this.#deps.gatewayId,
            mindId: this.#caller.mindId,
          })
        : Promise.resolve(emptyGatewaySpendReport(this.#deps.gatewayId, resolved)),
      store.queryUsage({
        mindId: this.#caller.mindId,
        mindSlug: this.#caller.mindSlug,
        sinceMs: resolved.sinceMs,
        untilMs: resolved.untilMs,
      }),
    ]);
    return combineCloudUsageReports(this.#caller, aiGateway, openAi);
  }

  /** EVERY MIND'S OPENAI-DIRECT SPEND BY UTC DAY (voice and transcription on the Cloud's own
   *  OpenAI key), FOR THE CLOUD'S OWN MIND ALONE: its id is `ownMind.id`, proven by the caller's
   *  signed statement, and it wrote from `ownMind.hostname`. Any other mind is refused, a house
   *  account too: `usage()` answers a mind its own spend. The window is `usage()`'s, at most 31
   *  days. `minds` names ids to read beside the minds that the ledger lists. */
  async openAiUsageByMind(input?: OpenAiUsageByMindInput): Promise<OpenAiUsageByMindReport> {
    const own = this.#deps.ownMind;
    const isOwnMind =
      Boolean(own?.id) &&
      this.#caller.mindId === own?.id &&
      (!own.hostname || this.#caller.mindSlug === own.hostname);
    if (!isOwnMind) {
      throw codedError("INVALID_INPUT", "only iterate Cloud's own mind reads every mind's usage");
    }
    const given = input?.minds ?? [];
    if (!Array.isArray(given) || given.length > 200 || !given.every((id) => isMindId(id))) {
      throw codedError("INVALID_INPUT", "`minds` must be at most 200 mind ids");
    }
    const resolved = resolveUsageWindow(input);
    const store = this.#deps.openAiUsageStore || createInMemoryOpenAiUsageStore();
    const byDay = await store.queryUsageByDay({
      sinceMs: resolved.sinceMs,
      untilMs: resolved.untilMs,
      mindIds: given,
    });
    return openAiUsageByMindReport(resolved, byDay);
  }

  get ai(): CloudAiTarget {
    return new CloudAiTarget(this.#caller, this.#deps);
  }
}

/** Cap'n Web capability matching `itx.ai`'s model-execution surface (`run`, `models`, `websearch`,
 *  `gateway`), plus `usage` for per-mind AI Gateway spend inspection. Every model call is forced
 *  through Iterate Cloud's AI Gateway (`#deps.gatewayId`) with stamped `mindId` + `mindSlug`
 *  metadata; `toMarkdown` and gateway `getLog`/`patchLog` are intentionally omitted so no call
 *  bypasses AI Gateway attribution or reads another mind's logs. */
export class CloudAiTarget extends RpcTarget {
  readonly #caller: AuthenticatedMind;
  readonly #deps: CloudAiDeps;

  constructor(caller: AuthenticatedMind, deps: CloudAiDeps) {
    super();
    this.#caller = caller;
    this.#deps = deps;
  }

  async run(model: string, inputs: Record<string, unknown>, given?: AiOptions): Promise<unknown> {
    if (!model) {
      throw codedError("INVALID_INPUT", "ai.run requires a non-empty model identifier");
    }
    const metadata = stampCloudGatewayMetadata(this.#caller, given?.gateway?.metadata);
    const options: AiOptions = {
      ...given,
      tags: stampWorkersAiTags(this.#caller.mindSlug, given?.tags),
      extraHeaders: sanitizeExtraHeaders(given?.extraHeaders),
      gateway: {
        id: this.#deps.gatewayId,
        skipCache: given?.gateway?.skipCache,
        cacheTtl: given?.gateway?.cacheTtl,
        cacheKey: given?.gateway?.cacheKey,
        collectLog: true,
        metadata,
      },
    };
    const answer: unknown = await this.#deps.ai.run(model, inputs, options);
    // Workers AI / AI Gateway occasionally answers a `Response` holding JSON even when
    // `returnRawResponse` was not requested (observed live on `typesafe/jev` and `clef-flash`
    // beside concurrent streaming calls); unwrap non-streaming JSON responses for callers.
    if (!given?.returnRawResponse && !inputs.stream && answer instanceof Response) {
      return readBoundedBody(`ai.run(${model})`, answer);
    }
    return answer;
  }

  models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]> {
    return this.#deps.ai.models(params);
  }

  /** A WEB SEARCH CARRIES NO METADATA: the binding's request has no field for it. So the gateway's
   *  row names no mind and no plan, and no rule that splits or filters on a metadata entry counts
   *  it: the rule with no dimension alone bounds web searches. */
  async websearch(
    request: Omit<AiWebSearchRequest, "gatewayId"> & { gatewayId?: string },
  ): Promise<ItxWebSearchAnswer> {
    const answer = await this.#deps.ai.websearch({
      ...request,
      gatewayId: this.#deps.gatewayId,
    });
    return WebSearchAnswer.parse(await readBoundedBody("Web Search", answer));
  }

  gateway(_ignoredGatewayId?: string): CloudAiGatewayTarget {
    return new CloudAiGatewayTarget(
      this.#deps.ai.gateway(this.#deps.gatewayId),
      this.#deps.gatewayId,
      this.#caller,
    );
  }

  async usage(window?: UsageWindowInput): Promise<GatewaySpendReport> {
    if (!this.#deps.analytics) {
      throw codedError(
        "INVALID_INPUT",
        "Cloud AI analytics token is not configured on this Worker",
      );
    }
    return queryGatewaySpend({
      ...window,
      accountId: this.#deps.analytics.accountId,
      apiToken: this.#deps.analytics.apiToken,
      fetcher: this.#deps.analytics.fetcher,
      gatewayId: this.#deps.gatewayId,
      mindId: this.#caller.mindId,
    });
  }
}

export type CloudGatewayRunOptions = {
  gateway?: Partial<UniversalGatewayOptions>;
  extraHeaders?: Record<string, string>;
};

export class CloudAiGatewayTarget extends RpcTarget {
  readonly #gateway: AiGateway;
  readonly #gatewayId: string;
  readonly #caller: AuthenticatedMind;

  constructor(gateway: AiGateway, gatewayId: string, caller: AuthenticatedMind) {
    super();
    this.#gateway = gateway;
    this.#gatewayId = gatewayId;
    this.#caller = caller;
  }

  async run(
    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
    options?: CloudGatewayRunOptions,
  ): Promise<unknown> {
    const response = await this.runRaw(data, options);
    return readBoundedBody("AI Gateway run", response);
  }

  runRaw(
    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
    options?: CloudGatewayRunOptions,
  ): Promise<Response> {
    const sanitizedData = Array.isArray(data)
      ? data.map((item) => sanitizeUniversalRequest(item))
      : sanitizeUniversalRequest(data);
    const metadata = stampCloudGatewayMetadata(this.#caller, options?.gateway?.metadata);
    return this.#gateway.run(sanitizedData, {
      extraHeaders: sanitizeExtraHeaders(options?.extraHeaders),
      gateway: {
        id: this.#gatewayId,
        skipCache: options?.gateway?.skipCache,
        cacheTtl: options?.gateway?.cacheTtl,
        cacheKey: options?.gateway?.cacheKey,
        collectLog: true,
        metadata,
      },
    });
  }
}

function sanitizeUniversalRequest(request: AIGatewayUniversalRequest): AIGatewayUniversalRequest {
  return {
    ...request,
    headers: sanitizeExtraHeaders(request.headers),
  };
}

async function readBoundedBody(what: string, response: Response): Promise<unknown> {
  const bytes = await readBoundedBytes(what, response);
  if (!response.ok) {
    const detail = new TextDecoder().decode(bytes).slice(0, 1_000);
    const message = `${what} answered HTTP ${response.status}: ${detail}`;
    const kind = httpFailureKind(response);
    if (kind === "overloaded" || kind === "disconnected") {
      throw codedError("UNAVAILABLE", message, { status: response.status, failureKind: kind });
    }
    throw codedError("INVALID_INPUT", message, { status: response.status });
  }
  const contentType = response.headers.get("content-type") ?? "";
  if (contentType.includes("json")) return JSON.parse(new TextDecoder().decode(bytes));
  if (contentType.startsWith("text/")) return new TextDecoder().decode(bytes);
  return bytes;
}

async function readBoundedBytes(what: string, response: Response): Promise<Uint8Array> {
  if (!response.body) return new Uint8Array();
  const reader = response.body.getReader();
  const chunks: Uint8Array[] = [];
  let total = 0;
  try {
    for (let step = await reader.read(); !step.done; step = await reader.read()) {
      // `ReadableStreamDefaultReader` in Workers yields `Uint8Array` chunks on response bodies.
      const chunk = step.value as Uint8Array;
      total += chunk.byteLength;
      if (total > ANSWER_MAX_BYTES) {
        await reader.cancel();
        throw codedError(
          "INVALID_INPUT",
          `${what} answered more than ${ANSWER_MAX_BYTES} bytes, exceeding single-call limit`,
        );
      }
      chunks.push(chunk);
    }
  } finally {
    reader.releaseLock();
  }
  const out = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    out.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return out;
}