iterate.com / cloud

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

cloud / internal-packages / cloud-clients / src / bot.tsmain at aacbc74

// bot.ts — THE CLOUD'S BOT AT X: one account of iterate's own (@iterate), which a person talks to
// by direct message or by mentioning it. The account is ours, so its tokens are kept here, sealed
// under the Cloud's key: they are the only tokens this Worker holds. A person's own X tokens stay
// in their deployment (worker.ts).
//
//   connect   an operator, once: X's consent as the bot's account (keys.ts `botLinkOf`)
//   push      X's own events as they happen (its Activity API, to worker.ts `pushed`): a post
//             that mentions the bot, and an unencrypted direct message. The bot's account is
//             subscribed to them at the first alarm after it is connected.
//   read      the net under the push, on the object's own alarm: what reached the bot since the
//             last read. Every minute while X does not push here, every five when it does.
//
// Either way, a message from an X account that a deployment linked goes to that deployment as
// `x/message-received` on `/integrations/<client>/<x user id>`, signed by the Cloud's key, once.
// A message from an account nobody linked is nobody's, and is dropped.
//
// NOT READ: a message typed in X's app is X's encrypted Chat. The API lists and pushes only
// "unencrypted" direct messages; a Chat message (`chat.received`) needs keys of the bot's own
// (docs.x.com/xchat). So a person reaches the bot today by mentioning it.
//   send      a deployment's reply, as the bot: a direct message to an account that deployment
//             linked, or one post under a mention the Cloud delivered to it, when that mention is
//             the person's own post and not their reply in someone else's conversation
//
// X's API as the old Cloud used it (packages/cloud src/x.ts, proven against X on 2026-11-08):
// https://docs.x.com/x-api/direct-messages/get-dm-events, /posts/get-user-mentions,
// /direct-messages/create-dm-by-participant, /posts/create-post. The push: /x-api/activity and
// /x-api/webhooks.
import { DurableObject } from "cloudflare:workers";
import { seal, unseal } from "./keys.ts";
import { cloudOf, HELD_MS, type Client, type Env } from "./worker.ts";
import {
  digits,
  fieldAt,
  listOf,
  POST_SUBSCRIPTION_PREFIX,
  postSubscriptionsConfig,
  type PostSubscription,
} from "./post-subscriptions.ts";

/** What the bot may do at X: read what reaches it, and answer. */
export const BOT_SCOPES = "tweet.read tweet.write users.read dm.read dm.write offline.access";

/** One message to the bot, as a deployment receives it. `reply` is where its answer goes. */
type Message = {
  kind: "dm" | "mention";
  /** X's id of the event: a direct message's event, or a post. */
  id: string;
  text: string;
  at: string;
  from: { xUserId: string };
  /** A mention's alone: whether it starts a conversation of the person's own. The bot answers in
   *  public only there; a mention inside someone else's conversation is answered by nobody. */
  ownThread?: boolean;
};

/** A deployment's answer: a direct message to the person, or a post in their mention's thread. */
export type Reply =
  | { kind: "dm"; to: string; text: string }
  | { kind: "mention"; inReplyTo: string; text: string };

type Tokens = { accessToken: string; refreshToken: string; expiresAt: number };
type Account = {
  /** The client's name in the Cloud's config. */
  name: string;
  /** The Cloud's public origin, as the connect saw it: where a reply is sent. */
  origin: string;
  self: { id: string; username: string };
  /** `Tokens`, sealed under the Cloud's key. */
  tokens: string;
};
/** The newest direct message and mention already read: null before the first read, `START` when
 *  that read found none. */
type Cursors = { dm: string | null; mention: string | null };
const START = "0";
/** Whether X pushes the bot's events here: the app's webhook at X, or why X said no, and when. */
type Push = { webhook: string; at: number } | { refused: string; at: number };

/** One delivery of X's Activity API, as far as the bot reads it: a post (`post.mention.create`)
 *  or direct messages (`dm.received`), for the account in `filter`. */
export type Pushed = {
  event_type?: string;
  filter?: { user_id?: string };
  payload?: {
    id?: string;
    text?: string;
    author_id?: string;
    created_at?: string;
    conversation_id?: string;
    direct_message_events?: {
      id?: string;
      created_timestamp?: string;
      message_create?: { sender_id?: string; message_data?: { text?: string } };
    }[];
  };
};

/** How long a delivered mention may be answered. */
const MENTION_ANSWERABLE_MS = 7 * 24 * 60 * 60_000;
/** How often the bot reads what reached it while X does not push: X allows a read of direct
 *  messages once a minute. */
const POLL_EVERY_MS = 60_000;

/** One per X client, by its name. */
export class Bot extends DurableObject<Env> {
  /** X spends a refresh token on use: two refreshes at once would lose the account. */
  #refreshing: Promise<string> | undefined;
  /** The last change of a public post subscription: the next waits for it (`#serially`). */
  #postChange: Promise<unknown> = Promise.resolve();

  /** The bot's account, from an operator's consent: its tokens sealed, the cursors started at what
   *  is newest now, so the account's history is nobody's inbox, and the first read a minute off. */
  async setAccount(
    name: string,
    origin: string,
    tokens: Tokens,
    self: Account["self"],
  ): Promise<void> {
    const { sealKey, clients } = await cloudOf(this.env);
    await this.ctx.storage.put<Account>("account", {
      name,
      origin,
      self,
      tokens: await seal(sealKey, { token: JSON.stringify(tokens), mind: "", client: name }),
    });
    const { cursors } = await inboxOf(clients[name]!, tokens.accessToken, self.id, {
      dm: null,
      mention: null,
    });
    await this.ctx.storage.put<Cursors>("cursors", cursors);
    await this.ctx.storage.setAlarm(Date.now() + POLL_EVERY_MS);
  }

  /** The read. One that fails is tried again at the next: the cursors moved only as far as what
   *  was delivered, so nothing is skipped. While X pushes here the read is only the net under it. */
  override async alarm(): Promise<void> {
    const pushes = await this.#pushes();
    try {
      await this.#poll(pushes);
    } catch (error) {
      console.warn({ event: "bot.poll-failed", error: String(error).slice(0, 300) });
    }
    for (const kind of ["dm", "mention"]) {
      const seen = await this.ctx.storage.list<number>({ prefix: `seen:${kind}:`, limit: 128 });
      const old = [...seen].filter(([, at]) => Date.now() - at > HELD_MS).map(([key]) => key);
      if (old.length) await this.ctx.storage.delete(old);
    }
    await this.ctx.storage.setAlarm(Date.now() + (pushes ? 5 : 1) * POLL_EVERY_MS);
    await this.#sweepPostSubscriptions().catch((error) =>
      console.warn({
        event: "bot.post-subscription-sweep-failed",
        error: String(error).slice(0, 300),
      }),
    );
  }

  /** WHETHER X PUSHES THE BOT'S EVENTS HERE. Asked of X once the bot is connected, and again ten
   *  minutes after a refusal. Until X says yes the read goes on by the minute, and the log says
   *  why. */
  async #pushes(): Promise<boolean> {
    const account = await this.ctx.storage.get<Account>("account");
    const push = await this.ctx.storage.get<Push>("push");
    if (!account || (push && ("webhook" in push || Date.now() - push.at < 10 * POLL_EVERY_MS)))
      return !!push && "webhook" in push;
    const { name, origin, self } = account;
    try {
      const webhook = await subscribed(
        (await cloudOf(this.env)).clients[name]!,
        await this.#accessToken(name),
        `${origin}/clients/${name}/webhook`,
        self.id,
      );
      await this.ctx.storage.put<Push>("push", { webhook, at: Date.now() });
      console.info({ event: "bot.push-on", webhook });
      return true;
    } catch (error) {
      const refused = String(error).slice(0, 400);
      await this.ctx.storage.put<Push>("push", { refused, at: Date.now() });
      console.warn({ event: "bot.push-refused", error: refused, reads: "every minute" });
      return false;
    }
  }

  /** WHAT X PUSHED for the bot's account (worker.ts `pushed` checked that X signed it): each
   *  message in it goes the same way as one the read found. */
  async pushed(event: Pushed): Promise<void> {
    const account = await this.ctx.storage.get<Account>("account");
    if (!account || event.filter?.user_id !== account.self.id) return;
    const post = event.payload || {};
    const messages: Message[] =
      event.event_type === "post.mention.create" && post.id && post.author_id
        ? [
            {
              kind: "mention",
              id: post.id,
              text: post.text || "",
              at: post.created_at || "",
              from: { xUserId: post.author_id },
              ownThread: post.conversation_id === post.id,
            },
          ]
        : event.event_type === "dm.received"
          ? (post.direct_message_events || []).flatMap((each) =>
              each.id && each.message_create?.sender_id
                ? [
                    {
                      kind: "dm" as const,
                      id: each.id,
                      text: each.message_create.message_data?.text || "",
                      at: new Date(Number(each.created_timestamp) || Date.now()).toISOString(),
                      from: { xUserId: each.message_create.sender_id },
                    },
                  ]
                : [],
            )
          : [];
    for (const message of messages)
      if (message.from.xUserId !== account.self.id) await this.#relay(account, message);
  }

  /** `mind` watches `userId`'s public posts (the model: post-subscriptions.ts). A row with X's id,
   *  orphaned or not, takes the deployment in. Else X is asked first, with the app's token, and
   *  the row is stored only once X names its subscription: a refusal leaves no row, and the
   *  deployment asks again. The connected bot gives the client's name and the webhook. */
  async subscribePost(mind: string, userId: string): Promise<PostAnswer> {
    return this.#serially(async () => {
      const config = postSubscriptionsConfig(this.env.X_POST_SUBSCRIPTIONS);
      if (!config) return refused(403, "public post subscriptions are not enabled");
      if (!config.minds.includes(mind))
        return refused(403, `${mind} may not subscribe to public posts`);
      const key = `${POST_SUBSCRIPTION_PREFIX}${userId}`;
      const row = await this.ctx.storage.get<PostSubscription>(key);
      // one X has already, orphaned or not: an orphan with a deployment again is simply live again
      if (row?.subscriptionId) {
        await this.ctx.storage.put<PostSubscription>(key, {
          userId,
          minds: row.minds.includes(mind) ? row.minds : [...row.minds, mind],
          subscriptionId: row.subscriptionId,
        });
        return postAnswer(userId, true);
      }
      const rows = await this.ctx.storage.list({
        prefix: POST_SUBSCRIPTION_PREFIX,
        limit: config.limit,
      });
      if (rows.size >= config.limit) return refused(429, "subscription quota reached");
      const account = await this.ctx.storage.get<Account>("account");
      if (!account) return refused(503, "the bot is not connected");
      const push = await this.ctx.storage.get<Push>("push");
      if (!push || !("webhook" in push)) return refused(503, "X does not push to this Cloud yet");
      const x = await this.#postApi(account.name);
      if (!x) return refused(503, noAppToken);
      let created: { status: number; text: string };
      try {
        const answer = await fetch(`${x.api}/2/activity/subscriptions`, {
          method: "POST",
          headers: { authorization: x.authorization, "content-type": "application/json" },
          body: JSON.stringify({
            event_type: "post.create",
            filter: { user_id: userId },
            webhook_id: push.webhook,
            tag: "iterate-cloud-public-post",
          }),
          signal: AbortSignal.timeout(8000),
        });
        created = { status: answer.status, text: await answer.text() };
      } catch (error) {
        const said = String(error).slice(0, 200);
        console.warn({ event: "bot.post-subscribe-failed", userId, error: said });
        return refused(502, `X refused the subscription: ${said}`);
      }
      let subscriptionId = created.status < 300 ? createdId(created.text) : undefined;
      // X has it already: its 400 `DuplicateSubscription` (a 409 too), or a yes that names no id
      if (
        !subscriptionId &&
        (created.status < 300 || created.status === 409 || /duplicate|already/i.test(created.text))
      ) {
        subscriptionId = await listedId(x, userId);
        // X holds a subscription that this object cannot name, so cannot delete: every post it
        // brings is billed, and relayed to nobody. The log names the account for an operator.
        if (!subscriptionId) {
          console.error({
            event: "bot.post-subscription-unnamed",
            userId,
            status: created.status,
            answer: created.text.slice(0, 300),
          });
          return refused(502, "X has this subscription but did not name it");
        }
      }
      if (!subscriptionId) {
        console.warn({ event: "bot.post-subscribe-failed", userId, status: created.status });
        return refused(502, `X refused the subscription: HTTP ${created.status}`);
      }
      await this.ctx.storage.put<PostSubscription>(key, { userId, minds: [mind], subscriptionId });
      return postAnswer(userId, true);
    });
  }

  /** A deployment lets go of an account. The last one deletes the subscription at X; one X does
   *  not delete stays as an orphan, which the alarm deletes again. Either way the deployment's
   *  interest is gone. It works also while the service is off. */
  async unsubscribePost(mind: string, userId: string): Promise<PostAnswer> {
    return this.#serially(async () => {
      const key = `${POST_SUBSCRIPTION_PREFIX}${userId}`;
      const row = await this.ctx.storage.get<PostSubscription>(key);
      if (!row?.minds.includes(mind)) return postAnswer(userId, false);
      const minds = row.minds.filter((each) => each !== mind);
      if (minds.length) {
        await this.ctx.storage.put<PostSubscription>(key, { ...row, minds });
        return postAnswer(userId, false);
      }
      const error = await this.#deletePost(row);
      if (!error) {
        await this.ctx.storage.delete(key);
        return postAnswer(userId, false);
      }
      await this.ctx.storage.put<PostSubscription>(key, {
        ...row,
        minds: [],
        orphanedAt: row.orphanedAt || Date.now(),
      });
      console.warn({ event: "bot.post-unsubscribe-failed", userId, error });
      return postAnswer(userId, false);
    });
  }

  /** The accounts one deployment watches. */
  async postSubscriptionsOf(mind: string): Promise<{ userId: string; eventType: "post.create" }[]> {
    const rows = await this.ctx.storage.list<PostSubscription>({
      prefix: POST_SUBSCRIPTION_PREFIX,
    });
    return [...rows.values()]
      .filter((row) => row.minds.includes(mind))
      .map(({ userId }) => ({ userId, eventType: "post.create" }));
  }

  /** The deployments a post by `userId` goes to (worker.ts `Outbox`). */
  async postSubscribers(userId: string): Promise<string[]> {
    const row = await this.ctx.storage.get<PostSubscription>(
      `${POST_SUBSCRIPTION_PREFIX}${userId}`,
    );
    return row?.minds || [];
  }

  /** THE ORPHANS, from the alarm: each one's delete at X is tried again. One X still keeps after a
   *  day is dropped here with an error in the log that names it, so an operator deletes it at X:
   *  every post it brings is billed to the Cloud's X account. No orphan, no call to X. */
  async #sweepPostSubscriptions(): Promise<void> {
    const rows = await this.ctx.storage.list<PostSubscription>({
      prefix: POST_SUBSCRIPTION_PREFIX,
    });
    for (const [key, { orphanedAt }] of rows)
      if (orphanedAt)
        await this.#serially(async () => {
          // a subscribe since the list may have made it live again
          const row = await this.ctx.storage.get<PostSubscription>(key);
          if (!row?.orphanedAt) return;
          const error = await this.#deletePost(row);
          if (!error) return this.ctx.storage.delete(key);
          if (Date.now() - row.orphanedAt < HELD_MS) return;
          console.error({
            event: "bot.post-subscription-leaked",
            userId: row.userId,
            subscriptionId: row.subscriptionId,
          });
          await this.ctx.storage.delete(key);
        });
  }

  /** Delete one subscription at X: nothing when it is gone, or why X kept it. */
  async #deletePost(row: PostSubscription): Promise<string | undefined> {
    if (!row.subscriptionId) return undefined;
    try {
      const account = await this.ctx.storage.get<Account>("account");
      if (!account) return "the bot is not connected";
      const x = await this.#postApi(account.name);
      if (!x) return noAppToken;
      const answer = await fetch(`${x.api}/2/activity/subscriptions/${row.subscriptionId}`, {
        method: "DELETE",
        // no content-type: this request has no body
        headers: { authorization: x.authorization },
        signal: AbortSignal.timeout(8000),
      });
      const text = await answer.text();
      // gone already: X answers an id it does not have with 400 `SubscriptionIdInvalid`. A 400
      // `UserNotAuthorized` is no such answer: that token may not delete it.
      if (
        answer.status === 404 ||
        (answer.status === 400 && /SubscriptionIdInvalid|not found/i.test(text))
      )
        return undefined;
      let said: unknown;
      try {
        said = JSON.parse(text);
      } catch {
        said = null;
      }
      // X's own words go to the log: they say why it kept the subscription
      return answer.ok && fieldAt(said, "data", "deleted") === true
        ? undefined
        : `HTTP ${answer.status}: ${text.slice(0, 300)}`;
    } catch (error) {
      return String(error).slice(0, 200);
    }
  }

  /** X's API and the app's own token for it (worker.ts `ClientSecrets.bearerToken`). A public
   *  post subscription belongs to the app, not to the bot's account: X lets the bot's token make
   *  one, but not delete it. Nothing when the Cloud has no app token for this client. */
  async #postApi(name: string): Promise<PostApi | undefined> {
    const { clients, secrets } = await cloudOf(this.env);
    const token = secrets[name]?.bearerToken;
    return token ? { api: clients[name]!.api, authorization: `Bearer ${token}` } : undefined;
  }

  /** Run `change` once the change before it settled, whether it failed or not. */
  #serially<T>(change: () => Promise<T>): Promise<T> {
    const next = this.#postChange.then(change);
    this.#postChange = next.catch(() => undefined);
    return next;
  }

  /** Who the bot is, or null before an operator connected it. */
  async self(): Promise<Account["self"] | null> {
    return (await this.ctx.storage.get<Account>("account"))?.self || null;
  }

  /** What reached the bot since the last read, to the deployments that linked its senders, oldest
   *  first. The cursor moves with each message delivered, so a read that fails part way goes on
   *  from there and brings nothing twice. While X pushes (`pushes`), a message the read is the
   *  first to bring is one the push missed, and the log says so. */
  async #poll(pushes: boolean): Promise<void> {
    const account = await this.ctx.storage.get<Account>("account");
    if (!account) return;
    const { name } = account;
    const cloud = await cloudOf(this.env);
    const cursors = (await this.ctx.storage.get<Cursors>("cursors")) || { dm: null, mention: null };
    const read = await inboxOf(
      cloud.clients[name]!,
      await this.#accessToken(name),
      account.self.id,
      cursors,
    );
    for (const message of read.messages.toSorted((a, b) => order(a.id, b.id))) {
      if ((await this.#relay(account, message)) && pushes)
        console.warn({ event: "bot.read-fallback", kind: message.kind, id: message.id });
      cursors[message.kind === "dm" ? "dm" : "mention"] = message.id;
      await this.ctx.storage.put<Cursors>("cursors", cursors);
    }
    // past what was delivered: the newest listed of each kind, the bot's own messages among them
    await this.ctx.storage.put<Cursors>("cursors", read.cursors);
  }

  /** ONE MESSAGE TO THE DEPLOYMENTS that linked its sender, signed by the Cloud's key, once
   *  whichever way it came: true when this is the first time. The mark is taken before the
   *  message goes, so a push and a read of the same message make one event, and it comes back
   *  only when the message could not be handed on. */
  async #relay(account: Account, message: Message): Promise<boolean> {
    const seen = `seen:${message.kind}:${message.id}`;
    if (await this.ctx.storage.get(seen)) return false;
    await this.ctx.storage.put(seen, Date.now());
    const { name } = account;
    try {
      const routes = this.env.ROUTES.get(this.env.ROUTES.idFromName("routes"));
      const minds = await routes.mindsOf(name, message.from.xUserId);
      if (message.kind === "mention" && message.ownThread && minds.length)
        await this.ctx.storage.put(`mention:${message.id}`, {
          from: message.from.xUserId,
          at: Date.now(),
        });
      const at = Date.now();
      for (const mind of minds) {
        const outbox = this.env.OUTBOX.get(this.env.OUTBOX.idFromName(mind));
        // what is said: the deployment's outbox signs it when it sends it (worker.ts `statementFor`)
        await outbox.put(mind, {
          path: `/integrations/${name}/${message.from.xUserId}`,
          type: "events.iterate.com/x/message-received",
          payload: {
            ...message,
            bot: account.self,
            // where the deployment's answer goes, through its vault (the `ask` route of worker.ts)
            reply: `${account.origin}/clients/${name}/ask/reply`,
          },
          at,
        });
      }
    } catch (error) {
      await this.ctx.storage.delete(seen);
      throw error;
    }
    return true;
  }

  /** Who wrote a mention the bot may answer in public: one the Cloud delivered, that starts a
   *  conversation of the person's own, not yet answered, within a week. Null for any other post,
   *  so the bot posts nothing under a post a deployment merely names. */
  async mentionedBy(postId: string): Promise<string | null> {
    const mention = await this.ctx.storage.get<{ from: string; at: number }>(`mention:${postId}`);
    return mention && Date.now() - mention.at < MENTION_ANSWERABLE_MS ? mention.from : null;
  }

  /** Send `reply` as the bot. Answers X's id of what was sent. A mention is answered once: its
   *  record is taken before the post is sent, so two answers at once make one post, and it comes
   *  back only when X refused. */
  async send(name: string, reply: Reply): Promise<{ id: string }> {
    const { clients } = await cloudOf(this.env);
    const key = reply.kind === "mention" ? `mention:${reply.inReplyTo}` : "";
    const mention = key ? await this.ctx.storage.get<{ from: string; at: number }>(key) : undefined;
    if (key && !mention) throw new Error("this mention was already answered");
    if (key) await this.ctx.storage.delete(key);
    const answer = await fetch(
      reply.kind === "dm"
        ? `${clients[name]!.api}/2/dm_conversations/with/${encodeURIComponent(reply.to)}/messages`
        : `${clients[name]!.api}/2/tweets`,
      {
        method: "POST",
        headers: {
          authorization: `Bearer ${await this.#accessToken(name)}`,
          "content-type": "application/json",
        },
        body: JSON.stringify(
          reply.kind === "dm"
            ? { text: reply.text }
            : { text: reply.text, reply: { in_reply_to_tweet_id: reply.inReplyTo } },
        ),
      },
    );
    const sent = (await answer.json().catch(() => null)) as {
      data?: { id?: string; dm_event_id?: string };
    } | null;
    if (!answer.ok) {
      if (key) await this.ctx.storage.put(key, mention);
      throw new Error(`X refused the reply: HTTP ${answer.status}`);
    }
    return { id: sent?.data?.dm_event_id || sent?.data?.id || "" };
  }

  /** Whether an operator's link is used for the first time: one link connects one account. */
  async firstUseOfLink(until: number): Promise<boolean> {
    if (await this.ctx.storage.get(`link:${until}`)) return false;
    await this.ctx.storage.put(`link:${until}`, true);
    return true;
  }

  /** The bot's access token, refreshed when it is about to end. One refresh at a time. */
  async #accessToken(name: string): Promise<string> {
    this.#refreshing ||= this.#freshToken(name).finally(() => {
      this.#refreshing = undefined;
    });
    return this.#refreshing;
  }

  async #freshToken(name: string): Promise<string> {
    const { sealKey, clients, secrets } = await cloudOf(this.env);
    const account = (await this.ctx.storage.get<Account>("account"))!;
    const tokens = JSON.parse((await unseal(sealKey, account.tokens))!.token) as Tokens;
    if (tokens.expiresAt > Date.now() + 60_000) return tokens.accessToken;
    const client = clients[name]!;
    const next = await tokensOf(client, secrets[name]!.clientSecret, {
      grant_type: "refresh_token",
      refresh_token: tokens.refreshToken,
    });
    await this.ctx.storage.put<Account>("account", {
      ...account,
      tokens: await seal(sealKey, { token: JSON.stringify(next), mind: "", client: name }),
    });
    return next.accessToken;
  }
}

/** A token request at X as the Cloud's own client (HTTP Basic), for the bot's account. */
export async function tokensOf(
  client: Client,
  clientSecret: string,
  form: Record<string, string>,
): Promise<Tokens> {
  const answer = await fetch(client.tokenEndpoint, {
    method: "POST",
    headers: {
      authorization: `Basic ${btoa(`${client.clientId}:${clientSecret}`)}`,
      "content-type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams(form),
  });
  const tokens = (await answer.json().catch(() => null)) as {
    access_token?: string;
    refresh_token?: string;
    expires_in?: number;
  } | null;
  if (!answer.ok || !tokens?.access_token || !tokens.refresh_token)
    throw new Error(`X gave the bot no tokens: HTTP ${answer.status}`);
  return {
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token,
    expiresAt: Date.now() + (tokens.expires_in || 7200) * 1000,
  };
}

/** X PUSHES THE BOT'S EVENTS TO `url`: the app's webhook there (the one X already has, or a new
 *  one, which X checks with its CRC before it answers) and one subscription for each kind of
 *  event, for the bot's account alone. All of it with the bot's own token. Answers the webhook's
 *  id; throws what X said when it refused. */
async function subscribed(
  client: Client,
  accessToken: string,
  url: string,
  self: string,
): Promise<string> {
  const x = async (path: string, body?: unknown) => {
    const answer = await fetch(`${client.api}${path}`, {
      method: body ? "POST" : "GET",
      headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
      body: body ? JSON.stringify(body) : undefined,
    });
    const said = (await answer.json().catch(() => null)) as { data?: unknown } | null;
    if (!answer.ok)
      throw new Error(
        `X answered ${answer.status} at ${body ? "POST" : "GET"} ${path.split("?")[0]}: ${JSON.stringify(said).slice(0, 240)}`,
      );
    return said?.data;
  };
  const webhooks = ((await x("/2/webhooks")) || []) as { id: string; url: string }[];
  const webhook =
    webhooks.find((each) => each.url === url)?.id ||
    ((await x("/2/webhooks", { url })) as { id: string }).id;
  // X refuses this list to some tokens that may still subscribe (production, 2026-11-11: 403), so
  // a list it does not give is an empty one, and a subscription it already has is no refusal
  const have = ((await x(`/2/activity/subscriptions?user_id=${self}`).catch(() => [])) || []) as {
    event_type?: string;
    filter?: { user_id?: string };
  }[];
  for (const event_type of ["post.mention.create", "dm.received"])
    if (!have.some((each) => each.event_type === event_type && each.filter?.user_id === self))
      await x("/2/activity/subscriptions", {
        event_type,
        filter: { user_id: self },
        webhook_id: webhook,
        tag: "iterate-cloud",
      }).catch((error) => {
        if (!/answered 409|duplicate|already/i.test(String(error))) throw error;
      });
  return webhook;
}

/** How many pages of each list one read takes. A minute that brings more than that many pages
 *  loses its oldest messages: the read stops there, and the cursor moves to the newest. */
const PAGES = 5;

/** X's ids grow with time, and a longer number is a later one: negative when `a` is the earlier. */
const order = (a: string, b: string) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);

/** WHAT REACHED `self` SINCE THE CURSORS, and the newest id listed of each kind. X lists direct
 *  messages newest first with no `since`, so the read pages on until it meets one no later than
 *  the cursor (the cursor's own message may be gone); mentions take `since_id`. With no cursor
 *  nothing is a message yet: the cursor starts at the newest, so an account's history is not its
 *  inbox. The bot's own messages are not either. */
async function inboxOf(
  client: Client,
  accessToken: string,
  self: string,
  since: Cursors,
): Promise<{ messages: Message[]; cursors: Cursors }> {
  const listed = async (path: string, query: URLSearchParams) => {
    const answer = await fetch(`${client.api}${path}?${query}`, {
      headers: { authorization: `Bearer ${accessToken}` },
    });
    if (!answer.ok) throw new Error(`X listed nothing at ${path}: HTTP ${answer.status}`);
    return (await answer.json()) as {
      data?: Record<string, string>[];
      meta?: { next_token?: string };
    };
  };
  const messages: Message[] = [];
  const cursors = { ...since };

  const dms = new URLSearchParams({
    max_results: "50",
    event_types: "MessageCreate",
    "dm_event.fields": "sender_id,created_at,dm_conversation_id,text",
  });
  pages: for (let page = 0; page < PAGES; page += 1) {
    const { data = [], meta } = await listed("/2/dm_events", dms);
    if (page === 0) cursors.dm = data[0]?.id || since.dm || START;
    for (const event of data) {
      if (!since.dm || order(event.id!, since.dm) <= 0) break pages;
      if (event.sender_id !== self)
        messages.push({
          kind: "dm",
          id: event.id!,
          text: event.text || "",
          at: event.created_at!,
          from: { xUserId: event.sender_id! },
        });
    }
    if (!meta?.next_token || !data.length) break;
    dms.set("pagination_token", meta.next_token);
  }

  const mentions = new URLSearchParams({
    max_results: "20",
    "tweet.fields": "author_id,created_at,conversation_id",
  });
  if (since.mention && since.mention !== START) mentions.set("since_id", since.mention);
  for (let page = 0; page < PAGES; page += 1) {
    const { data = [], meta } = await listed(`/2/users/${self}/mentions`, mentions);
    if (page === 0) cursors.mention = data[0]?.id || since.mention || START;
    if (!since.mention) break;
    for (const post of data)
      if (post.author_id !== self)
        messages.push({
          kind: "mention",
          id: post.id!,
          text: post.text || "",
          at: post.created_at!,
          from: { xUserId: post.author_id! },
          // the first post of a conversation is its own conversation's id
          ownThread: post.conversation_id === post.id,
        });
    if (!meta?.next_token || !data.length) break;
    mentions.set("pagination_token", meta.next_token);
  }
  return { messages, cursors };
}

/** What a public post subscription's change answers: its state, or why it was refused. */
type PostAnswer =
  | { userId: string; eventType: "post.create"; subscribed: boolean }
  | { refused: { status: number; error: string } };
type PostApi = { api: string; authorization: string };
const noAppToken = "the Cloud has no app token for X";

const postAnswer = (userId: string, subscribed: boolean): PostAnswer => ({
  userId,
  eventType: "post.create",
  subscribed,
});
const refused = (status: number, error: string): PostAnswer => ({ refused: { status, error } });

/** X's id of a subscription it made: `data.subscription.subscription_id`. */
function createdId(text: string): string | undefined {
  let said: unknown;
  try {
    said = JSON.parse(text);
  } catch {
    return undefined;
  }
  return digits(fieldAt(said, "data", "subscription", "subscription_id"));
}

/** X's id of its subscription to `userId`'s posts, from its list. Some tokens may not read the
 *  list: then there is none. */
async function listedId(x: PostApi, userId: string): Promise<string | undefined> {
  try {
    const answer = await fetch(`${x.api}/2/activity/subscriptions`, {
      headers: { authorization: x.authorization },
      signal: AbortSignal.timeout(8000),
    });
    if (!answer.ok) return undefined;
    const said: unknown = await answer.json();
    const row = listOf(fieldAt(said, "data")).find(
      (each) =>
        fieldAt(each, "event_type") === "post.create" &&
        fieldAt(each, "filter", "user_id") === userId,
    );
    return digits(fieldAt(row, "subscription_id"));
  } catch {
    return undefined;
  }
}