iterate.com / cloud

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

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

import { MessageChannel } from "node:worker_threads";
import { newMessagePortRpcSession } from "capnweb";
import {
  identityHashOf,
  identityKeyIdOf,
  type IdentityRecord,
  identityRecordText,
  signIdentityRecord,
} from "iterate/mind-identity";
import { MIND_IDENTITY_PATH, type PublishedLog } from "iterate/mind-identity-log";
import {
  base64url,
  ITERATE_STATEMENT_HEADER,
  MIND_FETCH_STATEMENT_TYPE,
  signedMlDsa65,
  statementHeaderOf,
  statementText,
} from "iterate/signed";
import { expect, test } from "vitest";
import {
  IterateCloudApi,
  sanitizeExtraHeaders,
  stampCloudGatewayMetadata,
  stampWorkersAiTags,
} from "./ai-target.ts";
import {
  type CloudConfigurableContext,
  connectIterateCloud,
  type IterateCloudClientApi,
} from "./connect.ts";
import { createInMemoryOpenAiUsageStore } from "./ledger.ts";
import type { RelaySocketLike } from "./openai-voice.ts";
import { queryGatewaySpend } from "./usage.ts";
import { aiWebSocketSubpathOf, type CloudAiEnv, createCloudAiHandler, handles } from "./worker.ts";

const CLOUD_MIND_ID = "b".repeat(64);
const CLOUD_MIND_HOST = "iterate.iterate.com";

test("authenticates an enrolled mind over SecretProxy path and routes Cap'n Web calls with stamped metadata", async () => {
  const customer = await buildSignedTestMind("iterate.acme.example");
  const aiCalls: { model: string; inputs: Record<string, unknown>; options?: AiOptions }[] = [];
  const fakeAi = createFakeAi({
    onRun(model, inputs, options) {
      aiCalls.push({ model, inputs, options });
      return Promise.resolve({ response: "hello from cloud ai" });
    },
  });

  const handler = createCloudAiHandler({
    fetcher: (req) => servePublishedLogs([customer], req),
  });
  const env: CloudAiEnv = {
    AI: fakeAi,
    CLOUD_AI_GATEWAY: "iterate-cloud",
    MIND_ID: CLOUD_MIND_ID,
    MIND_HOSTNAME: CLOUD_MIND_HOST,
    ENROLMENTS: {
      enrolled: (mindId) => Promise.resolve(mindId === customer.mindId),
    },
  };

  const proxyUrl = "https://cloud.iterate.com/capnweb/cloud.iterate.com/api/cloud-ai";
  expect(handles(new URL(proxyUrl))).toBe(true);

  const authHeader = await signMindFetchHeader(customer, {
    toMind: CLOUD_MIND_HOST,
    method: "POST",
    url: proxyUrl,
  });

  // Cap'n Web batch framing (`["push", ["pipeline", 0, ["whoami"]]]\n["pull", 1]`) exercises the
  // full HTTP -> ML-DSA-65 auth -> enrolment -> `newWorkersRpcResponse` -> `IterateCloudApi` path.
  const rpcResponse = await handler.fetch(
    new Request(proxyUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: authHeader,
        "content-type": "text/plain;charset=UTF-8",
      },
      body: '["push",["pipeline",0,["whoami"],[]]]\n["pull",1]',
    }),
    env,
  );
  expect(rpcResponse).toMatchObject({ status: 200 });
  const wireText = await rpcResponse.text();
  expect(wireText).toContain(customer.mindId);
  expect(wireText).toContain("iterate.acme.example");
  expect(wireText).toContain("https://cloud.iterate.com/ai-ws/openai/responses");

  using session = openCapnwebLoopback(
    new IterateCloudApi(
      {
        mindId: customer.mindId,
        mindSlug: customer.hostname,
        expiresAtMs: Date.now() + 60_000,
      },
      { ai: fakeAi, gatewayId: "iterate-cloud" },
    ),
  );

  const identity = await session.client.whoami();
  expect(identity).toEqual({
    mindId: customer.mindId,
    mindSlug: "iterate.acme.example",
    gatewayId: "iterate-cloud",
  });

  const result = await session.client.ai.run(
    "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
    { prompt: "Summarize today's notes" },
    {
      tags: ["mind:spoofed", "feature:notes"],
      extraHeaders: {
        "cf-aig-collect-log": "false",
        "cf-aig-metadata": '{"mindId":"spoofed"}',
        Authorization: "Bearer should-be-stripped",
        "x-api-key": "should-be-stripped",
        "anthropic-beta": "prompt-caching-2024-07-31",
      },
      gateway: {
        id: "wrong-gateway-id",
        skipCache: true,
        metadata: {
          mindId: "spoofed-id",
          mindSlug: "spoofed.example",
          spendPlan: "house",
          "cf.internal": "ignored",
          streamPath: "/agents/assistant",
          context: "agent-turn",
          customKey1: "dropped-past-five-key-cap",
        },
      },
    },
  );

  expect(result).toEqual({ response: "hello from cloud ai" });
  expect(aiCalls).toHaveLength(1);
  const recorded = aiCalls[0]!;
  expect(recorded).toMatchObject({
    model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
    inputs: { prompt: "Summarize today's notes" },
    options: {
      tags: ["mind:iterate.acme.example", "feature:notes"],
      extraHeaders: {
        "anthropic-beta": "prompt-caching-2024-07-31",
        "cf-aig-collect-log-payload": "false",
      },
      gateway: {
        id: "iterate-cloud",
        skipCache: true,
        collectLog: true,
        metadata: {
          mindId: customer.mindId,
          mindSlug: "iterate.acme.example",
          // an enrolled mind cannot name its own plan
          spendPlan: "standard",
          streamPath: "/agents/assistant",
          context: "agent-turn",
        },
      },
    },
  });
  expect(Object.keys(recorded.options?.gateway?.metadata || {})).toEqual([
    "mindId",
    "mindSlug",
    "spendPlan",
    "streamPath",
    "context",
  ]);
  expect(recorded.options?.extraHeaders).not.toHaveProperty("Authorization");
  expect(recorded.options?.extraHeaders).not.toHaveProperty("x-api-key");
  expect(recorded.options?.extraHeaders).not.toHaveProperty("cf-aig-collect-log");
});

test("streams raw SSE Response chunks over Cap'n Web for AgentProcessor turns and gateway.runRaw", async () => {
  const sseFrames = [
    'event: response.output_text.delta\ndata: {"delta":"Hello "}\n\n',
    'event: response.output_text.delta\ndata: {"delta":"world!"}\n\n',
    "event: response.completed\ndata: {}\n\n",
  ];

  const gatewayCalls: {
    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[];
    options?: Parameters<AiGateway["run"]>[1];
  }[] = [];

  const fakeAi = createFakeAi({
    onRun(model, _inputs, options) {
      if (options?.returnRawResponse) {
        return Promise.resolve(streamedResponseOf(sseFrames, "text/event-stream"));
      }
      if (model === "typesafe/jev") {
        return Promise.resolve(Response.json({ choice: "wake" }));
      }
      return Promise.resolve({ ok: true });
    },
    onGatewayRun(data, options) {
      gatewayCalls.push({ data, options });
      return Promise.resolve(Response.json({ id: "resp_123", output_text: "universal answer" }));
    },
  });

  const mindId = "c".repeat(64);
  using session = openCapnwebLoopback(
    new IterateCloudApi(
      {
        mindId,
        mindSlug: "iterate.streaming.example",
        expiresAtMs: Date.now() + 60_000,
      },
      { ai: fakeAi, gatewayId: "iterate-cloud" },
    ),
  );

  const raw = await session.client.ai.run(
    "openai/gpt-5.4-mini",
    { input: "Say hello", stream: true },
    {
      returnRawResponse: true,
      gateway: {
        id: "default",
        metadata: { streamPath: "/agents/chat", context: "agent-turn" },
      },
    },
  );

  expect(raw).toBeInstanceOf(Response);
  // `returnRawResponse: true` causes `CloudAiTarget.run` to return a `Response`, which Cap'n Web
  // reconstructs on the client with a live streaming body.
  const streamedText = await (raw as Response).text();
  expect(streamedText).toBe(sseFrames.join(""));

  // Non-streaming `ai.run` unwraps unexpected `Response` objects returned by Workers AI:
  const unwrapped = await session.client.ai.run("typesafe/jev", { messages: [] });
  expect(unwrapped).toEqual({ choice: "wake" });

  const universalJson = await session.client.ai.gateway("ignored-caller-id").run(
    {
      provider: "anthropic",
      endpoint: "v1/messages",
      headers: {
        "x-api-key": "caller-secret-stripped",
        "cf-aig-skip-cache": "true",
        "anthropic-version": "2023-06-01",
      },
      query: { model: "claude-sonnet-4-6", max_tokens: 64, messages: [] },
    },
    {
      gateway: { metadata: { mindId: "forged", streamPath: "/agents/coder" } },
    },
  );

  expect(universalJson).toEqual({ id: "resp_123", output_text: "universal answer" });
  expect(gatewayCalls).toHaveLength(1);
  expect(gatewayCalls[0]!).toMatchObject({
    data: {
      provider: "anthropic",
      endpoint: "v1/messages",
      headers: {
        "anthropic-version": "2023-06-01",
        "cf-aig-collect-log-payload": "false",
      },
    },
    options: {
      gateway: {
        id: "iterate-cloud",
        collectLog: true,
        metadata: {
          mindId,
          mindSlug: "iterate.streaming.example",
          streamPath: "/agents/coder",
        },
      },
    },
  });

  const models = await session.client.ai.models({ search: "llama" });
  expect(models).toEqual([{ id: "model_1", name: "@cf/meta/llama-3.3-70b-instruct-fp8-fast" }]);

  const search = await session.client.ai.websearch({ query: "cloudflare ai gateway spend limits" });
  expect(search).toMatchObject({
    items: [{ url: "https://developers.cloudflare.com/ai-gateway/", title: "AI Gateway" }],
    metadata: { query: "cloudflare ai gateway spend limits" },
  });
});

test("refuses unenrolled minds (403), broken enrolment bindings (503), tampered statements (401), and rolled-back identity logs (401)", async () => {
  const enrolledMind = await buildSignedTestMind("iterate.enrolled.example");
  const unenrolledMind = await buildSignedTestMind("iterate.outsider.example");
  const transientMind = await buildSignedTestMind("iterate.transient.example");
  let currentEnrolled = enrolledMind;

  const handler = createCloudAiHandler({
    fetcher: (req) => servePublishedLogs([currentEnrolled, unenrolledMind, transientMind], req),
  });

  const targetUrl = "https://cloud.iterate.com/api/cloud-ai";
  const baseEnv: CloudAiEnv = {
    AI: createFakeAi(),
    MIND_ID: CLOUD_MIND_ID,
    MIND_HOSTNAME: CLOUD_MIND_HOST,
    ENROLMENTS: {
      enrolled: (mindId) => Promise.resolve(mindId === enrolledMind.mindId),
    },
  };

  // 1. Missing header -> 401
  const missing = await handler.fetch(new Request(targetUrl), baseEnv);
  expect(missing).toMatchObject({ status: 401 });

  // 2. Signed for a different URL -> 401
  const wrongUrlHeader = await signMindFetchHeader(enrolledMind, {
    toMind: CLOUD_MIND_ID,
    method: "GET",
    url: "https://cloud.iterate.com/other-path",
  });
  const wrongUrl = await handler.fetch(
    new Request(targetUrl, { headers: { [ITERATE_STATEMENT_HEADER]: wrongUrlHeader } }),
    baseEnv,
  );
  expect(wrongUrl).toMatchObject({ status: 401 });

  // 3. Unenrolled mind with valid ML-DSA-65 signature -> 403, then immediately accepted (200) once enrolled (no negative cache)
  const outsiderHeader = await signMindFetchHeader(unenrolledMind, {
    toMind: CLOUD_MIND_ID,
    method: "GET",
    url: targetUrl,
  });
  const forbidden = await handler.fetch(
    new Request(targetUrl, { headers: { [ITERATE_STATEMENT_HEADER]: outsiderHeader } }),
    baseEnv,
  );
  expect(forbidden).toMatchObject({ status: 403 });

  const nowEnrolledHeader = await signMindFetchHeader(unenrolledMind, {
    toMind: CLOUD_MIND_ID,
    method: "POST",
    url: targetUrl,
  });
  const acceptedAfterEnrol = await handler.fetch(
    new Request(targetUrl, {
      method: "POST",
      headers: { [ITERATE_STATEMENT_HEADER]: nowEnrolledHeader, "content-type": "text/plain" },
      body: "",
    }),
    {
      ...baseEnv,
      ENROLMENTS: { enrolled: () => Promise.resolve(true) },
    },
  );
  expect(acceptedAfterEnrol).toMatchObject({ status: 200 });

  // 4. Transient ENROLMENTS error -> 503 with Retry-After
  const transientHeader = await signMindFetchHeader(transientMind, {
    toMind: CLOUD_MIND_ID,
    method: "GET",
    url: targetUrl,
  });
  const brokenEnrolments = await handler.fetch(
    new Request(targetUrl, { headers: { [ITERATE_STATEMENT_HEADER]: transientHeader } }),
    {
      ...baseEnv,
      ENROLMENTS: {
        enrolled: () => Promise.reject(new Error("RPC connection lost")),
      },
    },
  );
  expect(brokenEnrolments).toMatchObject({ status: 503 });
  expect(brokenEnrolments.headers.get("retry-after")).toBe("5");

  // 5. Monotonic identity-log protection: advance enrolledMind to position 3 (revoking the first
  //    working key), authenticate once with the new key, then attempt to serve the older position-2
  //    log + old key signature -> refused with 401!
  const rotated = await rotateMindWorkingKey(enrolledMind);
  currentEnrolled = rotated;
  const rotatedHeader = await signMindFetchHeader(rotated, {
    toMind: CLOUD_MIND_ID,
    method: "POST",
    url: targetUrl,
  });
  const accepted = await handler.fetch(
    new Request(targetUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: rotatedHeader,
        "content-type": "text/plain;charset=UTF-8",
      },
      body: '["push",["pipeline",0,["whoami"],[]]]\n["pull",1]',
    }),
    baseEnv,
  );
  expect(accepted).toMatchObject({ status: 200 });

  // Second request with the current rotated key exercises incremental `?after=<head>` verification:
  const secondAccepted = await handler.fetch(
    new Request(targetUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: rotatedHeader,
        "content-type": "text/plain;charset=UTF-8",
      },
      body: '["push",["pipeline",0,["whoami"],[]]]\n["pull",1]',
    }),
    baseEnv,
  );
  expect(secondAccepted).toMatchObject({ status: 200 });

  // Roll the origin's served log back to position 2 and replay a fresh signature from the old key:
  currentEnrolled = enrolledMind;
  const staleKeyHeader = await signMindFetchHeader(enrolledMind, {
    toMind: CLOUD_MIND_ID,
    method: "POST",
    url: targetUrl,
  });
  const replayAttempt = await handler.fetch(
    new Request(targetUrl, {
      method: "POST",
      headers: { [ITERATE_STATEMENT_HEADER]: staleKeyHeader },
    }),
    baseEnv,
  );
  expect(replayAttempt).toMatchObject({ status: 401 });
});

// The incident of 27 Nov 2026, 20:21:25 UTC: the Cloud held a mind's verified log, the read-on
// from it (`?after=<head>`) got ONE 500 from the mind's host, and that failure was kept for a
// minute. The agent's two retries, 2 and 4 seconds later, got the kept failure, and it paused.
test("a key-history read that the mind's host fails (5xx) is a 503 that is not kept, and the next request reads again; a host with no log stays a kept 401", async () => {
  const mind = await buildSignedTestMind("iterate.flaky-host.example");
  const gone = await buildSignedTestMind("iterate.no-log.example");
  let hostFails = false;
  const reads: string[] = [];
  const handler = createCloudAiHandler({
    fetcher: (req) => {
      reads.push(new URL(req.url).hostname + new URL(req.url).search);
      if (new URL(req.url).hostname === gone.hostname)
        return Promise.resolve(new Response("Not found", { status: 404 }));
      if (hostFails)
        return Promise.resolve(
          Response.json({ error: "D1_ERROR: Subrequest depth limit exceeded" }, { status: 500 }),
        );
      return servePublishedLogs([mind], req);
    },
  });
  const targetUrl = "https://cloud.iterate.com/api/cloud-ai";
  const env: CloudAiEnv = {
    AI: createFakeAi(),
    MIND_ID: CLOUD_MIND_ID,
    MIND_HOSTNAME: CLOUD_MIND_HOST,
    ENROLMENTS: { enrolled: () => Promise.resolve(true) },
  };
  const ask = async (from: SignedTestMind) =>
    handler.fetch(
      new Request(targetUrl, {
        method: "POST",
        headers: {
          [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(from, {
            toMind: CLOUD_MIND_ID,
            method: "POST",
            url: targetUrl,
          }),
          "content-type": "text/plain;charset=UTF-8",
        },
        body: '["push",["pipeline",0,["whoami"],[]]]\n["pull",1]',
      }),
      env,
    );

  // the Cloud reads the whole log once and holds its verified state
  expect(await ask(mind)).toMatchObject({ status: 200 });
  expect(reads).toEqual([mind.hostname]);

  // the read-on fails at the host: the request is refused, as one that may pass when asked again
  hostFails = true;
  const refused = await ask(mind);
  expect(refused).toMatchObject({ status: 503 });
  expect(refused.headers.get("retry-after")).toBe("5");
  expect(await refused.json()).toEqual({
    error: expect.stringContaining(`${mind.hostname} gave no keys now`),
  });

  // the host answers again: the agent's retry reads again and passes, well inside the minute
  hostFails = false;
  expect(await ask(mind)).toMatchObject({ status: 200 });
  const readOn = `${mind.hostname}?after=${mind.headHash}`;
  expect(reads).toEqual([mind.hostname, readOn, readOn]);

  // a host that answers with no log (404) is no passing failure: 401, and kept, so it is read once
  expect(await ask(gone)).toMatchObject({ status: 401 });
  expect(await ask(gone)).toMatchObject({ status: 401 });
  expect(reads.filter((read) => read.startsWith(gone.hostname))).toEqual([gone.hostname]);
});

test("serves a house account with no enrolment row, by its id and its hostname together, and nobody who only claims to be one", async () => {
  // the Cloud's own mind, and another of iterate's minds: each is an entry of the configuration
  const own = await buildSignedTestMind(CLOUD_MIND_HOST);
  const house = await buildSignedTestMind("iterate.house.example");
  // the same mind (the same log and keys) at a hostname that its entry does not name
  const ownElsewhere = { ...own, hostname: "iterate.elsewhere.example" };
  // another mind, with keys of its own
  const impostor = await buildSignedTestMind("iterate.impostor.example");
  const outsider = await buildSignedTestMind("iterate.stranger.example");
  const targetUrl = "https://cloud.iterate.com/api/cloud-ai";
  const whoami = '["push",["pipeline",0,["whoami"],[]]]\n["pull",1]';
  let asked = 0;
  const plans: unknown[] = [];
  const accounts = JSON.stringify({
    [own.mindId]: { hostname: own.hostname },
    [house.mindId]: { hostname: house.hostname },
  });
  const envOf = (houseAccounts: string | undefined, enrolled = false): CloudAiEnv => ({
    AI: createFakeAi({
      onRun: (_model, _inputs, options) => {
        plans.push(options?.gateway?.metadata?.spendPlan);
        return Promise.resolve({ ok: true });
      },
    }),
    MIND_ID: own.mindId,
    MIND_HOSTNAME: CLOUD_MIND_HOST,
    CLOUD_AI_HOUSE_ACCOUNTS: houseAccounts,
    // nobody is enrolled: a house account has no row
    ENROLMENTS: {
      enrolled: () => {
        asked += 1;
        return Promise.resolve(enrolled);
      },
    },
  });
  const post = async (
    served: SignedTestMind[],
    signer: SignedTestMind,
    env: CloudAiEnv,
    body = whoami,
  ) => {
    const handler = createCloudAiHandler({ fetcher: (req) => servePublishedLogs(served, req) });
    const header = await signMindFetchHeader(signer, {
      toMind: own.mindId,
      method: "POST",
      url: targetUrl,
    });
    return handler.fetch(
      new Request(targetUrl, {
        method: "POST",
        headers: {
          [ITERATE_STATEMENT_HEADER]: header,
          "content-type": "text/plain;charset=UTF-8",
        },
        body,
      }),
      env,
    );
  };

  // 1. The Cloud's own mind and another house account: served, and the enrolment is not asked
  for (const mind of [own, house]) {
    const served = await post([mind], mind, envOf(accounts));
    expect(served).toMatchObject({ status: 200 });
    expect(await served.text()).toContain(mind.mindId);
  }
  expect(asked).toBe(0);

  // 2. With no entry, the Cloud's own mind is a mind like any other: asked, and not enrolled.
  //    The code knows no mind by itself
  for (const none of [
    undefined,
    "{}",
    JSON.stringify({ [house.mindId]: { hostname: house.hostname } }),
  ]) {
    expect(await post([own], own, envOf(none))).toMatchObject({ status: 403 });
  }
  expect(asked).toBe(3);

  // 3. A configuration that does not parse names nobody
  for (const bad of ["not json", "[]", JSON.stringify({ [own.mindId]: { hostname: "" } })]) {
    expect(await post([own], own, envOf(bad))).toMatchObject({ status: 403 });
  }

  // 4. The same log from a hostname that it does not list is nobody's: refused before any entry
  expect(await post([ownElsewhere], ownElsewhere, envOf(accounts))).toMatchObject({ status: 401 });

  // 5. An entry whose hostname is another than the one the statement comes from does not count
  const elsewhereEntry = JSON.stringify({ [house.mindId]: { hostname: "iterate.other.example" } });
  expect(await post([house], house, envOf(elsewhereEntry))).toMatchObject({ status: 403 });

  // 6. A statement that claims a house account's id, signed by another mind's key: its log is
  //    not that id's
  const claimed = await post([impostor], { ...impostor, mindId: house.mindId }, envOf(accounts));
  expect(claimed).toMatchObject({ status: 401 });

  // 7. Any other mind is refused as before
  expect(await post([outsider], outsider, envOf(accounts))).toMatchObject({ status: 403 });

  // 8. THE SPEND PLAN that the gateway is told: `house` for a house account, `standard` for an
  //    enrolled mind, whatever plan the caller itself names
  const run =
    '["push",["pipeline",0,["ai","run"],["@cf/meta/llama-3.3-70b-instruct-fp8-fast",{"prompt":"hi"},{"gateway":{"metadata":{"spendPlan":"house"}}}]]]\n["pull",1]';
  expect(await post([house], house, envOf(accounts), run)).toMatchObject({ status: 200 });
  expect(await post([outsider], outsider, envOf(accounts, true), run)).toMatchObject({
    status: 200,
  });
  expect(plans).toEqual(["house", "standard"]);
});

test("queries per-mind AI Gateway spend from Cloudflare GraphQL and filters `ai.usage()` to the calling mind", async () => {
  const mindA = "1".repeat(64);
  const mindB = "2".repeat(64);
  let graphqlBody = "";

  const analyticsFetcher = async (request: Request) => {
    graphqlBody = await request.text();
    return Response.json({
      data: {
        viewer: {
          accounts: [
            {
              aiGatewayRequestsAdaptiveGroups: [
                {
                  count: 12,
                  dimensions: {
                    mindId: mindA,
                    mindSlug: "iterate.alpha.example",
                    provider: "openai",
                    model: "gpt-5.4-mini",
                  },
                  sum: {
                    cost: 0.42,
                    uncachedTokensIn: 14_000,
                    uncachedTokensOut: 3_500,
                    cachedTokensIn: 6_000,
                    cachedTokensOut: 0,
                  },
                },
                {
                  count: 5,
                  dimensions: {
                    mindId: mindB,
                    mindSlug: "iterate.beta.example",
                    provider: "anthropic",
                    model: "claude-sonnet-4-6",
                  },
                  sum: {
                    cost: 1.25,
                    uncachedTokensIn: 20_000,
                    uncachedTokensOut: 8_000,
                    cachedTokensIn: 0,
                    cachedTokensOut: 0,
                  },
                },
              ],
            },
          ],
        },
      },
      errors: null,
    });
  };

  const fullReport = await queryGatewaySpend({
    accountId: "acct_123",
    apiToken: "cf_analytics_token",
    gatewayId: "iterate-cloud",
    since: "2026-11-20T00:00:00.000Z",
    until: "2026-11-21T00:00:00.000Z",
    fetcher: analyticsFetcher,
  });

  expect(JSON.parse(graphqlBody)).toMatchObject({
    query: expect.stringContaining('metadataValue(key: "mindId")'),
    variables: {
      accountTag: "acct_123",
      gateway: "iterate-cloud",
    },
  });
  expect(fullReport).toMatchObject({
    gatewayId: "iterate-cloud",
    totalRequests: 17,
    totalCostUsd: 1.67,
    totalTokensIn: 40_000,
    totalTokensOut: 11_500,
    byMind: [
      {
        mindId: mindB,
        mindSlug: "iterate.beta.example",
        requests: 5,
        costUsd: 1.25,
        tokensIn: 20_000,
        tokensOut: 8_000,
      },
      {
        mindId: mindA,
        mindSlug: "iterate.alpha.example",
        requests: 12,
        costUsd: 0.42,
        tokensIn: 20_000,
        tokensOut: 3_500,
      },
    ],
  });

  using session = openCapnwebLoopback(
    new IterateCloudApi(
      {
        mindId: mindA,
        mindSlug: "iterate.alpha.example",
        expiresAtMs: Date.now() + 60_000,
      },
      {
        ai: createFakeAi(),
        gatewayId: "iterate-cloud",
        analytics: {
          accountId: "acct_123",
          apiToken: "cf_analytics_token",
          fetcher: analyticsFetcher,
        },
      },
    ),
  );

  // Calling `ai.usage()` as mindA never reveals mindB's spend or request rows:
  const mindAReport = await session.client.ai.usage({
    since: "2026-11-20T00:00:00.000Z",
    until: "2026-11-21T00:00:00.000Z",
  });
  expect(mindAReport).toMatchObject({
    totalRequests: 12,
    totalCostUsd: 0.42,
    byMind: [
      {
        mindId: mindA,
        mindSlug: "iterate.alpha.example",
        requests: 12,
        costUsd: 0.42,
      },
    ],
  });
});

test("connects `itx.iterateCloud` via SecretProxy and forwards authenticated OpenAI Responses WebSockets to AI Gateway", async () => {
  const setCalls: { path: string; options: unknown }[] = [];
  const appendedEvents: unknown[] = [];

  const rootContext: CloudConfigurableContext = {
    secrets: {
      describe: (path) => Promise.resolve({ path, set: false }),
      deleteIfProxy: (path) => Promise.resolve({ path, deleted: false }),
      set: (path, _material, options) => {
        setCalls.push({ path, options });
        return Promise.resolve({ path });
      },
    },
    append: (...events) => {
      appendedEvents.push(...events);
      return Promise.resolve(events);
    },
  };

  const connected = await connectIterateCloud(
    { cd: () => rootContext },
    {
      cloudOrigin: "https://cloud.iterate.com",
      cloudMind: "iterate.iterate.com",
    },
  );

  expect(connected).toEqual({
    secretPath: "/secrets/iterate-cloud",
    proxyUrl: "https://cloud.iterate.com/capnweb",
    capnwebUrl: "wss://cloud.iterate.com/api/cloud-ai",
    responsesWebSocketUrl: "https://cloud.iterate.com/ai-ws/openai/responses",
    replacedItxAi: true,
    openAiSecret: "proxy",
  });
  expect(setCalls).toEqual([
    {
      path: "/secrets/iterate-cloud",
      options: {
        urls: ["https://cloud.iterate.com"],
        placement: "header",
        proxy: {
          mind: "iterate.iterate.com",
          url: "https://cloud.iterate.com/capnweb",
        },
      },
    },
    {
      path: "/secrets/openai",
      options: {
        urls: ["https://api.openai.com"],
        placement: "header",
        proxy: {
          mind: "iterate.iterate.com",
          url: "https://cloud.iterate.com/capnweb",
        },
      },
    },
  ]);
  expect(appendedEvents).toHaveLength(2);
  expect(appendedEvents[0]).toMatchObject({
    type: "events.iterate.com/itx/rewrite-rule-configured",
    payload: { match: "itx.iterateCloud" },
  });
  expect(appendedEvents[1]).toMatchObject({
    type: "events.iterate.com/itx/rewrite-rule-configured",
    payload: { match: "itx.ai", target: "itx.iterateCloud.ai" },
  });

  // Verify `/capnweb/<host>/ai-ws/openai/responses` upgrade forwarding with stamped cf-aig-metadata:
  expect(aiWebSocketSubpathOf("/capnweb/cloud.iterate.com/ai-ws/openai/responses")).toBe(
    "openai/responses",
  );
  const customer = await buildSignedTestMind("iterate.ws-customer.example");
  let upstreamRequest: Request | null = null;
  const wsHandler = createCloudAiHandler({
    fetcher: (req) => servePublishedLogs([customer], req),
    gatewayWsFetcher: (req) => {
      upstreamRequest = req;
      return Promise.resolve(new Response("upgraded", { status: 200 }));
    },
  });
  const wsUrl = "https://cloud.iterate.com/capnweb/cloud.iterate.com/ai-ws/openai/responses";
  const wsAuth = await signMindFetchHeader(customer, {
    toMind: CLOUD_MIND_ID,
    method: "GET",
    url: wsUrl,
  });
  const wsRes = await wsHandler.fetch(
    new Request(wsUrl, {
      headers: {
        [ITERATE_STATEMENT_HEADER]: wsAuth,
        upgrade: "websocket",
        "x-iterate-stream-path": "/agents/ws-turn",
        "cf-aig-metadata": '{"mindId":"forged"}',
        authorization: "Bearer forged",
      },
    }),
    {
      AI: createFakeAi(),
      CLOUD_AI_GATEWAY: "iterate-cloud",
      CLOUDFLARE_ACCOUNT_ID: "acct_dev",
      CLOUDFLARE_AIG_TOKEN: "secret_aig_run_token",
      MIND_ID: CLOUD_MIND_ID,
      MIND_HOSTNAME: CLOUD_MIND_HOST,
      ENROLMENTS: { enrolled: (id) => Promise.resolve(id === customer.mindId) },
    },
  );
  expect(wsRes).toMatchObject({ status: 200 });
  expect(upstreamRequest).toMatchObject({
    url: "https://gateway.ai.cloudflare.com/v1/acct_dev/iterate-cloud/openai/responses",
  });
  expect(upstreamRequest!.headers.get("cf-aig-authorization")).toBe("Bearer secret_aig_run_token");
  expect(upstreamRequest!.headers.get("cf-aig-collect-log-payload")).toBe("false");
  expect(upstreamRequest!.headers.get("authorization")).toBeNull();
  expect(JSON.parse(upstreamRequest!.headers.get("cf-aig-metadata") || "{}")).toEqual({
    mindId: customer.mindId,
    mindSlug: "iterate.ws-customer.example",
    spendPlan: "standard",
    streamPath: "/agents/ws-turn",
    context: "agent-turn",
  });

  // Unit-check metadata/header/tag helper edge cases directly:
  expect(
    stampCloudGatewayMetadata(
      { mindId: "f".repeat(64), mindSlug: "iterate.unit.example" },
      { nested: { bad: true }, count: 3, active: false },
    ),
  ).toEqual({
    mindId: "f".repeat(64),
    mindSlug: "iterate.unit.example",
    spendPlan: "standard",
    count: 3,
    active: false,
  });
  // a house account's plan is the authenticator's word, and the caller's own key cannot change it
  expect(
    stampCloudGatewayMetadata(
      { mindId: "f".repeat(64), mindSlug: "iterate.unit.example", spendPlan: "house" },
      { spendPlan: "standard", streamPath: "/agents/a", context: "agent-turn", more: 1 },
    ),
  ).toEqual({
    mindId: "f".repeat(64),
    mindSlug: "iterate.unit.example",
    spendPlan: "house",
    streamPath: "/agents/a",
    context: "agent-turn",
  });
  expect(sanitizeExtraHeaders()).toEqual({ "cf-aig-collect-log-payload": "false" });
  expect(stampWorkersAiTags("iterate.unit.example")).toEqual(["mind:iterate.unit.example"]);
});

test("meters lent OpenAI realtime voice & transcription per mind and combines it into `itx.iterateCloud.usage()`", async () => {
  const mindA = await buildSignedTestMind("iterate.voice-a.example");
  const mindB = await buildSignedTestMind("iterate.voice-b.example");
  const usageStore = createInMemoryOpenAiUsageStore();
  let clockMs = Date.parse("2026-11-21T12:00:00.000Z");

  const openAiCalls: { method: string; url: string; auth: string | null }[] = [];
  const upstreamSockets: ReturnType<typeof createLinkedMockSockets>[] = [];

  const handler = createCloudAiHandler({
    fetcher: (req) => servePublishedLogs([mindA, mindB], req),
    openAiUsageStore: usageStore,
    openAiVoiceDeps: {
      now: () => clockMs,
      createSocketPair: () => {
        const linked = createLinkedMockSockets();
        return {
          client: linked.left as unknown as WebSocket,
          server: linked.right,
        };
      },
      fetcher: async (req) => {
        openAiCalls.push({
          method: req.method,
          url: req.url,
          auth: req.headers.get("authorization"),
        });
        const url = new URL(req.url);
        if (req.headers.get("upgrade") === "websocket") {
          const linked = createLinkedMockSockets();
          upstreamSockets.push(linked);
          const wsRes = new Response(null, { status: 200 });
          Object.defineProperty(wsRes, "webSocket", { value: linked.left });
          return wsRes;
        }
        if (url.pathname === "/v1/audio/transcriptions") {
          return Response.json({
            text: "hello world",
            usage: {
              type: "tokens",
              input_tokens: 1_000,
              output_tokens: 100,
              input_token_details: { text_tokens: 0, audio_tokens: 1_000 },
            },
          });
        }
        if (url.pathname === "/v1/live/sessions" && req.method === "POST") {
          return Response.json({
            transport: { sdp: "v=0..." },
            session: { id: "sess_webrtc_1" },
          });
        }
        if (url.pathname === "/v1/live/sessions/sess_webrtc_1/hangup") {
          return Response.json({ ok: true });
        }
        if (url.pathname === "/v1/realtime/client_secrets") {
          return Response.json({
            value: "ek_short_lived",
            expires_at: 1795332242,
            session: { id: "sess_stt_1" },
          });
        }
        return new Response("unexpected", { status: 404 });
      },
    },
    analyticsFetcher: () =>
      Promise.resolve(
        Response.json({
          data: {
            viewer: {
              accounts: [
                {
                  aiGatewayRequestsAdaptiveGroups: [
                    {
                      count: 4,
                      dimensions: {
                        mindId: mindA.mindId,
                        mindSlug: mindA.hostname,
                        provider: "openai",
                        model: "openai/gpt-6.2-sol",
                      },
                      sum: {
                        cost: 0.25,
                        uncachedTokensIn: 5_000,
                        uncachedTokensOut: 500,
                        cachedTokensIn: 0,
                        cachedTokensOut: 0,
                      },
                    },
                  ],
                },
              ],
            },
          },
          errors: null,
        }),
      ),
  });

  const env: CloudAiEnv = {
    AI: createFakeAi(),
    CLOUD_AI_GATEWAY: "iterate-cloud",
    CLOUDFLARE_ACCOUNT_ID: "acct_dev",
    CLOUDFLARE_ANALYTICS_API_TOKEN: "cf_analytics_token",
    OPENAI_API_KEY: "sk-proj-cloud-voice",
    MIND_ID: CLOUD_MIND_ID,
    MIND_HOSTNAME: CLOUD_MIND_HOST,
    ENROLMENTS: {
      enrolled: (id) => Promise.resolve(id === mindA.mindId || id === mindB.mindId),
    },
  };

  // 1. Preserve an owner's own `/secrets/openai` key in `connectIterateCloud`:
  const ownKeyContext: CloudConfigurableContext = {
    secrets: {
      describe: (path) =>
        Promise.resolve(path === "/secrets/openai" ? { path, set: true } : { path, set: false }),
      deleteIfProxy: (path) => Promise.resolve({ path, deleted: false }),
      set: (path) => Promise.resolve({ path }),
    },
    append: (...events) => Promise.resolve(events),
  };
  const ownKeyResult = await connectIterateCloud(
    { cd: () => ownKeyContext },
    { replaceItxAi: false },
  );
  expect(ownKeyResult).toMatchObject({ openAiSecret: "own-key", replacedItxAi: false });

  // 2. Batch HTTP transcription (`POST /capnweb/api.openai.com/v1/audio/transcriptions`):
  const sttUrl = "https://cloud.iterate.com/capnweb/api.openai.com/v1/audio/transcriptions";
  const sttForm = new FormData();
  sttForm.set("file", new Blob([new Uint8Array(3200)], { type: "audio/wav" }), "clip.wav");
  sttForm.set("model", "gpt-4o-mini-transcribe");
  const sttRes = await handler.fetch(
    new Request(sttUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: sttUrl,
        }),
      },
      body: sttForm,
    }),
    env,
  );
  expect(sttRes).toMatchObject({ status: 200 });
  expect(await sttRes.json()).toMatchObject({ text: "hello world" });

  // 3. Refuse `store: true` on `/v1/live/sessions`:
  const liveUrl = "https://cloud.iterate.com/capnweb/api.openai.com/v1/live/sessions";
  const refusedStoreRes = await handler.fetch(
    new Request(liveUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: liveUrl,
        }),
        "content-type": "application/json",
      },
      body: JSON.stringify({ store: true, session: { model: "gpt-live-1" } }),
    }),
    env,
  );
  expect(refusedStoreRes).toMatchObject({ status: 400 });

  // 4. WebRTC GPT-Live session start (`POST /v1/live/sessions`), cross-mind hangup 403, then own hangup after 30s:
  const liveStartRes = await handler.fetch(
    new Request(liveUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: liveUrl,
        }),
        "content-type": "application/json",
      },
      body: JSON.stringify({
        session: { model: "gpt-live-1" },
        transport: { type: "webrtc", sdp: "v=0..." },
      }),
    }),
    env,
  );
  expect(liveStartRes).toMatchObject({ status: 200 });

  const hangupUrl =
    "https://cloud.iterate.com/capnweb/api.openai.com/v1/live/sessions/sess_webrtc_1/hangup";
  const crossMindHangup = await handler.fetch(
    new Request(hangupUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindB, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: hangupUrl,
        }),
      },
    }),
    env,
  );
  expect(crossMindHangup).toMatchObject({ status: 403 });

  clockMs += 30_000; // 30 seconds of active WebRTC GPT-Live ($0.025 at $0.05/min)
  const ownHangup = await handler.fetch(
    new Request(hangupUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: hangupUrl,
        }),
      },
    }),
    env,
  );
  expect(ownHangup).toMatchObject({ status: 200 });

  // 5. Server WebSocket GPT-Live (`GET /v1/live/sessions` with `Upgrade: websocket`, 60s = $0.05):
  const wsLiveRes = await handler.fetch(
    new Request(liveUrl, {
      method: "GET",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "GET",
          url: liveUrl,
        }),
        upgrade: "websocket",
      },
    }),
    env,
  );
  const clientLiveWs = (wsLiveRes as Response & { webSocket?: RelaySocketLike }).webSocket!;
  expect(clientLiveWs).toBeDefined();
  clientLiveWs.send(JSON.stringify({ type: "session.start", session: { model: "gpt-live-1" } }));
  clockMs += 60_000; // 60 seconds = $0.05
  clientLiveWs.close(1000, "done");

  // 6. Realtime transcription WebSocket (`GET /v1/realtime?intent=transcription`) + client secret:
  const wsSttUrl =
    "https://cloud.iterate.com/capnweb/api.openai.com/v1/realtime?intent=transcription";
  const wsSttRes = await handler.fetch(
    new Request(wsSttUrl, {
      method: "GET",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "GET",
          url: wsSttUrl,
        }),
        upgrade: "websocket",
      },
    }),
    env,
  );
  const clientSttWs = (wsSttRes as Response & { webSocket?: RelaySocketLike }).webSocket!;
  // 24 kHz PCM16 = 48,000 bytes/s -> 480,000 bytes = 10s of audio (`$0.017/min * 10/60 = $0.00283333`)
  const tenSecBase64 = Buffer.alloc(480_000).toString("base64");
  clientSttWs.send(JSON.stringify({ type: "input_audio_buffer.append", audio: tenSecBase64 }));
  clientSttWs.close(1000, "done");

  const secretUrl = "https://cloud.iterate.com/capnweb/api.openai.com/v1/realtime/client_secrets";
  const secretRes = await handler.fetch(
    new Request(secretUrl, {
      method: "POST",
      headers: {
        [ITERATE_STATEMENT_HEADER]: await signMindFetchHeader(mindA, {
          toMind: CLOUD_MIND_ID,
          method: "POST",
          url: secretUrl,
        }),
        "content-type": "application/json",
      },
      body: JSON.stringify({
        expires_after: { anchor: "created_at", seconds: 60 },
        session: { type: "transcription" },
      }),
    }),
    env,
  );
  expect(secretRes).toMatchObject({ status: 200 });
  expect(openAiCalls.every((c) => c.auth === "Bearer sk-proj-cloud-voice")).toBe(true);

  // 7. Query unified `itx.iterateCloud.usage()` as mindA and verify mindB sees zero of mindA's spend:
  using sessionA = openCapnwebLoopback(
    new IterateCloudApi(
      { mindId: mindA.mindId, mindSlug: mindA.hostname, expiresAtMs: clockMs + 60_000 },
      {
        ai: createFakeAi(),
        gatewayId: "iterate-cloud",
        openAiUsageStore: usageStore,
        analytics: {
          accountId: "acct_dev",
          apiToken: "cf_analytics_token",
          fetcher: () =>
            Promise.resolve(
              Response.json({
                data: {
                  viewer: {
                    accounts: [
                      {
                        aiGatewayRequestsAdaptiveGroups: [
                          {
                            count: 4,
                            dimensions: {
                              mindId: mindA.mindId,
                              mindSlug: mindA.hostname,
                              provider: "openai",
                              model: "openai/gpt-6.2-sol",
                            },
                            sum: {
                              cost: 0.25,
                              uncachedTokensIn: 5_000,
                              uncachedTokensOut: 500,
                              cachedTokensIn: 0,
                              cachedTokensOut: 0,
                            },
                          },
                        ],
                      },
                    ],
                  },
                },
                errors: null,
              }),
            ),
        },
      },
    ),
  );

  const reportA = await sessionA.client.usage({
    since: "2026-11-21T00:00:00.000Z",
    until: "2026-11-22T00:00:00.000Z",
  });
  expect(reportA).toMatchObject({
    totalRequests: 9,
    aiGateway: { totalCostUsd: 0.25 },
    openAi: {
      clientSecretGrants: 1,
      byCategory: {
        voice: {
          requests: 2,
          costUsd: 0.075, // $0.025 (30s WebRTC) + $0.05 (60s WS)
          audioSeconds: 90,
        },
        transcription: {
          requests: 3,
        },
      },
    },
  });
  expect(reportA.totalCostUsd).toBeCloseTo(0.25 + 0.075 + 0.00175 + 0.017 / 6, 6);

  using sessionB = openCapnwebLoopback(
    new IterateCloudApi(
      { mindId: mindB.mindId, mindSlug: mindB.hostname, expiresAtMs: clockMs + 60_000 },
      { ai: createFakeAi(), gatewayId: "iterate-cloud", openAiUsageStore: usageStore },
    ),
  );
  const reportB = await sessionB.client.usage({
    since: "2026-11-21T00:00:00.000Z",
    until: "2026-11-22T00:00:00.000Z",
  });
  expect(reportB).toMatchObject({
    totalCostUsd: 0,
    openAi: { totalRequests: 0 },
  });
});

type SignedTestMind = {
  mindId: string;
  hostname: string;
  rootKeyPair: CryptoKeyPair;
  rootPublicKey: string;
  rootKeyId: string;
  workingPrivateKey: CryptoKey;
  workingKeyId: string;
  headHash: string;
  log: PublishedLog;
};

async function generateMlDsaKeyPair() {
  // Node 24's WebCrypto supports `ML-DSA-65` and `raw-public` export, which TypeScript's DOM
  // definitions only partially type.
  const pair = (await crypto.subtle.generateKey({ name: "ML-DSA-65" }, true, [
    "sign",
    "verify",
  ])) as CryptoKeyPair;
  const rawPublic = new Uint8Array(
    (await crypto.subtle.exportKey("raw-public" as "raw", pair.publicKey)) as ArrayBuffer,
  );
  const publicKey = base64url(rawPublic);
  const keyId = await identityKeyIdOf(publicKey);
  return { pair, publicKey, keyId };
}

async function buildSignedTestMind(hostname: string): Promise<SignedTestMind> {
  const root = await generateMlDsaKeyPair();
  const working = await generateMlDsaKeyPair();

  const genesisRecord: IdentityRecord = {
    version: 1,
    prev: null,
    nonce: base64url(crypto.getRandomValues(new Uint8Array(16))),
    rootKeys: [
      {
        signs: "raw",
        algorithm: "ML-DSA-65",
        publicKey: root.publicKey,
        label: "test-root",
      },
    ],
    threshold: 1,
    workingKeys: [],
    hostnames: [hostname],
    alsoKnownAs: [],
  };
  const genesisText = identityRecordText(genesisRecord);
  const mindId = await identityHashOf(genesisText);
  const genesisSig = await signIdentityRecord(genesisText, root.pair.privateKey, root.keyId);

  const secondRecord: IdentityRecord = {
    version: 1,
    prev: mindId,
    rootKeys: genesisRecord.rootKeys,
    threshold: 1,
    workingKeys: [
      {
        signs: "raw",
        algorithm: "ML-DSA-65",
        publicKey: working.publicKey,
        label: "stack-statements",
        purpose: "statements",
      },
    ],
    hostnames: [hostname],
    alsoKnownAs: [],
  };
  const secondText = identityRecordText(secondRecord);
  const secondHash = await identityHashOf(secondText);
  const secondSig = await signIdentityRecord(secondText, root.pair.privateKey, root.keyId);

  return {
    mindId,
    hostname,
    rootKeyPair: root.pair,
    rootPublicKey: root.publicKey,
    rootKeyId: root.keyId,
    workingPrivateKey: working.pair.privateKey,
    workingKeyId: working.keyId,
    headHash: secondHash,
    log: {
      version: 1,
      mind: mindId,
      head: secondHash,
      records: [
        { record: genesisText, signatures: [genesisSig] },
        { record: secondText, signatures: [secondSig] },
      ],
    },
  };
}

async function rotateMindWorkingKey(mind: SignedTestMind): Promise<SignedTestMind> {
  const nextWorking = await generateMlDsaKeyPair();
  const thirdRecord: IdentityRecord = {
    version: 1,
    prev: mind.headHash,
    rootKeys: [
      {
        signs: "raw",
        algorithm: "ML-DSA-65",
        publicKey: mind.rootPublicKey,
        label: "test-root",
      },
    ],
    threshold: 1,
    workingKeys: [
      {
        signs: "raw",
        algorithm: "ML-DSA-65",
        publicKey: nextWorking.publicKey,
        label: "rotated-statements",
        purpose: "statements",
      },
    ],
    hostnames: [mind.hostname],
    alsoKnownAs: [],
  };
  const thirdText = identityRecordText(thirdRecord);
  const thirdHash = await identityHashOf(thirdText);
  const thirdSig = await signIdentityRecord(thirdText, mind.rootKeyPair.privateKey, mind.rootKeyId);

  return {
    ...mind,
    workingPrivateKey: nextWorking.pair.privateKey,
    workingKeyId: nextWorking.keyId,
    headHash: thirdHash,
    log: {
      version: 1,
      mind: mind.mindId,
      head: thirdHash,
      records: [...mind.log.records, { record: thirdText, signatures: [thirdSig] }],
    },
  };
}

async function signMindFetchHeader(
  mind: SignedTestMind,
  input: { toMind: string; method: string; url: string },
): Promise<string> {
  const now = Date.now();
  const text = statementText({
    mind: input.toMind,
    from: mind.mindId,
    fromHost: mind.hostname,
    path: "/",
    type: MIND_FETCH_STATEMENT_TYPE,
    payload: { method: input.method.toUpperCase(), url: input.url },
    at: now,
    expires: now + 300_000,
  });
  const envelope = await signedMlDsa65(text, mind.workingPrivateKey, mind.workingKeyId);
  return statementHeaderOf(envelope);
}

async function servePublishedLogs(minds: SignedTestMind[], request: Request): Promise<Response> {
  const url = new URL(request.url);
  if (url.pathname !== MIND_IDENTITY_PATH) {
    return new Response("Not found", { status: 404 });
  }
  const found = minds.find((candidate) => candidate.hostname === url.hostname);
  if (!found) return new Response("Unknown mind", { status: 404 });

  const after = url.searchParams.get("after");
  if (!after) return Response.json(found.log);

  const hashes = await Promise.all(found.log.records.map((entry) => identityHashOf(entry.record)));
  const index = hashes.indexOf(after);
  return Response.json({
    ...found.log,
    records: index === -1 ? [] : found.log.records.slice(index + 1),
  });
}

function openCapnwebLoopback(target: IterateCloudApi) {
  const { port1, port2 } = new MessageChannel();
  // Node's `worker_threads.MessagePort` implements the runtime `MessagePort` contract expected by
  // `newMessagePortRpcSession`, though its TypeScript declaration omits DOM `EventTarget` methods.
  newMessagePortRpcSession(port1 as unknown as MessagePort, target);
  const client = newMessagePortRpcSession<IterateCloudClientApi>(port2 as unknown as MessagePort);
  return {
    client,
    [Symbol.dispose]() {
      port1.close();
      port2.close();
    },
  };
}

function streamedResponseOf(chunks: string[], contentType: string): Response {
  const encoder = new TextEncoder();
  const stream = new ReadableStream<Uint8Array>({
    start(controller) {
      for (const piece of chunks) {
        controller.enqueue(encoder.encode(piece));
      }
      controller.close();
    },
  });
  return new Response(stream, {
    status: 200,
    headers: { "content-type": contentType },
  });
}

function createFakeAi(hooks?: {
  onRun?: (model: string, inputs: Record<string, unknown>, options?: AiOptions) => Promise<unknown>;
  onGatewayRun?: (
    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
    options?: Parameters<AiGateway["run"]>[1],
  ) => Promise<Response>;
}): Ai {
  const gateway: AiGateway = {
    getLog: () => Promise.reject(new Error("getLog should not be exposed")),
    patchLog: () => Promise.reject(new Error("patchLog should not be exposed")),
    getUrl: (provider) =>
      Promise.resolve(`https://gateway.ai.cloudflare.com/v1/acct/iterate-cloud/${provider || ""}`),
    run: (data, options) =>
      hooks?.onGatewayRun
        ? hooks.onGatewayRun(data, options)
        : Promise.resolve(Response.json({ ok: true })),
  };
  // Partial test double implementing the `Ai` binding methods exercised by `CloudAiTarget`.
  return {
    run: (model: string, inputs: Record<string, unknown>, options?: AiOptions) =>
      hooks?.onRun ? hooks.onRun(model, inputs, options) : Promise.resolve({ ok: true }),
    models: () =>
      Promise.resolve([
        // Minimal model record matching the subset returned by Workers AI's catalog search.
        { id: "model_1", name: "@cf/meta/llama-3.3-70b-instruct-fp8-fast" } as AiModelsSearchObject,
      ]),
    websearch: (req: AiWebSearchRequest) =>
      Promise.resolve(
        Response.json({
          items: [{ url: "https://developers.cloudflare.com/ai-gateway/", title: "AI Gateway" }],
          metadata: {
            query: req.query,
            gatewayId: req.gatewayId,
            requestId: "req_1",
            latencyMs: 42,
          },
        }),
      ),
    gateway: () => gateway,
  } as unknown as Ai;
}

function createLinkedMockSockets(): { left: RelaySocketLike; right: RelaySocketLike } {
  type Listener = (event: { data?: unknown; code?: number; reason?: string }) => void;
  const leftListeners = {
    message: [] as Listener[],
    close: [] as Listener[],
    error: [] as Listener[],
  };
  const rightListeners = {
    message: [] as Listener[],
    close: [] as Listener[],
    error: [] as Listener[],
  };
  let closed = false;

  const makeEnd = (own: typeof leftListeners, peer: typeof rightListeners): RelaySocketLike => ({
    accept() {},
    send(data) {
      if (closed) return;
      for (const fn of peer.message) fn({ data });
    },
    close(code = 1000, reason = "") {
      if (closed) return;
      closed = true;
      for (const fn of peer.close) fn({ code, reason });
      for (const fn of own.close) fn({ code, reason });
    },
    addEventListener(type, listener) {
      own[type].push(listener);
    },
  });

  return {
    left: makeEnd(leftListeners, rightListeners),
    right: makeEnd(rightListeners, leftListeners),
  };
}