iterate.com / cloud

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

cloud / scripts / cloud-rehearsal / mind-app / mind.ts.txtmain at aacbc74

// mind.ts — ONE REHEARSAL OF ITERATE CLOUD'S SIGN-UP, AS ONE RpcTarget: `RehearsalMind`.
//
// COPIED FROM iterate/iterate-config apps/cloud/mind.ts at db9c004 (17 Nov 2026), so that the agent
// under rehearsal gets its instructions and its narrowed tools exactly as iterate Cloud's agent
// does: the same two contexts, the same rows, the same methods behind `itx.cloud`. When that file
// changes, bring the change here. WHAT DIFFERS, and nothing else should:
//   - CLOUDFLARE IS AN ADDRESS OF THE REHEARSAL: `cloudflare` in its first event, a fake Cloudflare
//     (iterate/private scripts/cloud-rehearsal) behind a tunnel. Every call that goes to
//     api.cloudflare.com at iterate Cloud goes there, with no access. Its address may end in one
//     secret path segment: the fake answers nothing without it. No consent, token or account
//     of a real person is involved, and none may be: `createRehearsal` refuses Cloudflare's own
//     address, and nothing here names a secret but the model's key.
//   - THE SANDBOX AND THE DEPLOY ARE THE FAKE'S (`POST <fake>/sandbox`, `POST <fake>/deploy`). A
//     background command's end is told by a schedule, where the real sandbox posts it.
//   - THE MODEL'S KEY is this mind's own: a ChatGPT plan, else an OpenAI API key.
//   - no sign-in with Cloudflare, no waiting list and no page: a member starts a rehearsal
//     (`itx.config.cloudRehearsal`, worker.ts) and opens its chat in the Dash.
//   - THE HAND-OVER IS AHEAD OF ITERATE CLOUD'S, AND IT IS REAL: `handOver({ domain, person, said,
//     notes })` writes one sign-up record and a row that sends it through the mind meld to the mind
//     at `domain`, signed by the mind that runs the rehearsal, and `handedOver({ domain })` says
//     whether it arrived. iterate Cloud's own gives the new mind the whole chat and a transcript
//     file (a pull request to iterate/iterate-config, branch `cloud-meld-handover`, makes it this).
//     It is the one call here that reaches a real mind: the one that runs at the domain the person
//     picked. Nothing of Cloudflare is in it.
//   - paths are under /apps/cloud-rehearsal/, and the config's method is `cloudRehearsalMind`.
//
// "A mind" here is iterate Cloud's own word for one sign-up: the record of the mind a person is
// about to get, made the moment they start, long before anything is deployed.
import { RpcTarget } from "cloudflare:workers";

/** The mind's root itx, as worker.ts hands it, typed by what is used below. */
// oxlint-disable-next-line typescript/no-explicit-any
type Itx = any;
type ItxOf = () => Itx & Disposable;

export const MINDS = "/apps/cloud-rehearsal/minds/";
export const MIND = /^mind_[a-z2-7]{20}$/;
export const pathOf = (mind: string) => `${MINDS}${mind}`;
/** The rehearsal that a context's path names, or a throw. */
export function mindOf(path: unknown) {
  const mind = typeof path === "string" && path.startsWith(MINDS) ? path.slice(MINDS.length) : "";
  if (!MIND.test(mind)) throw new Error(`cloud-rehearsal: ${JSON.stringify(path)} is no rehearsal`);
  return mind;
}

/** { userId, email, connectUrl, cloudflare, guide }: a rehearsal's first event of its own. */
export const STARTED = "cloud/wizard-started";
const CONTEXT_ADDED = "events.iterate.com/agent/context-added";
/** The sign-up record that `handOver` sends to the new mind, and the line between its two parts (the template's cloud-handover.ts reads both). */
const HANDED_OVER = "events.iterate.com/cloud/installation-handed-over";
const HANDOVER_NOTES_MARK = "[iterate Cloud: notes for the onboarding agent]";
/** The row that sends this rehearsal's record to the mind at `domain`. */
const sendsTo = (domain: string) => `to-${domain.replaceAll(".", "-")}`;
/** A domain, as deploy() takes it. */
const DOMAIN = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
/** The domain a hand-over names, lower case, or a throw. */
function domainOf(domain: unknown, method: string) {
  const lower = typeof domain === "string" ? domain.toLowerCase() : "";
  if (!DOMAIN.test(lower)) throw new Error(`itx.cloud.${method}: domain is a domain, like ada-labs.com`);
  return lower;
}
const RULE_CONFIGURED = "events.iterate.com/itx/rewrite-rule-configured";

/** HOW A REHEARSAL STARTED: its first `cloud/wizard-started`, among its first 50 events: who plays
 *  the person, and where its Cloudflare is. */
export async function startOf(itx: Itx, mind: string): Promise<{ userId: string; email: string; cloudflare: string } | null> {
  const page = (await itx.cd(pathOf(mind)).readEvents(0, 50)) as { events: { type: string; payload?: Record<string, unknown> }[] };
  const started = page.events.find((event) => event.type === STARTED)?.payload;
  return started && typeof started.userId === "string" && typeof started.email === "string" && typeof started.cloudflare === "string"
    ? { userId: started.userId, email: started.email, cloudflare: started.cloudflare }
    : null;
}

/** The context the agent's scripts run in (`scriptRowsOf`). */
export const scriptsOf = (mind: string) => `${pathOf(mind)}/scripts`;
/** This rehearsal's RehearsalMind, as a row's target spells it. */
const mindCallOf = (mind: string) => `itx.builtins.cd("/").config.cloudRehearsalMind(${JSON.stringify(pathOf(mind))})`;
const row = (key: string, match: string, target: string | null, description: string) => ({ type: RULE_CONFIGURED, idempotencyKey: `${key}:${match}`, payload: { match, target, description } });

/** THE ROWS OF A REHEARSAL'S CONTEXT, in one append: what its two processors need. */
export function mindRowsOf(mind: string) {
  const M = mindCallOf(mind);
  const r = (match: string, target: string, description: string) => row("cloud-mind", match, target, description);
  return [
    r("itx.run", `itx.cd(${JSON.stringify(scriptsOf(mind))}).run`, "the agent's scripts run in the scripts' context, which reaches itx.cloud alone (apps/cloud-rehearsal/mind.ts)"),
    r("itx.fetch", `${M}.fetch(@)`, "the internet, with no secret but the model's key; Cloudflare's API goes to the rehearsal's fake"),
    r("itx.secrets.describe", `${M}.describeSecret(@)`, "whether the model's key is set"),
    r("itx.files.get", `${M}.file(@)`, "files under the rehearsal's own path (script results, attachments)"),
  ];
}

/** THE ROWS OF THE SCRIPTS' CONTEXT, in one append: the mask first, then what it gives back. */
export function scriptRowsOf(mind: string) {
  const p = JSON.stringify(pathOf(mind));
  const M = mindCallOf(mind);
  const r = (match: string, target: string | null, description: string) => row("cloud-scripts", match, target, description);
  return [
    r("itx", null, `the scripts of ${mind}'s agent in a rehearsal of iterate Cloud (apps/cloud-rehearsal/mind.ts): they reach only the rows below`),
    r("itx.run", "itx.builtins.run", "a script can be started here"),
    r("itx.cloud", M, "the agent's tools: connectCloudflare, makeAccount, cloudflare, sandbox, deploy, handOver, handedOver"),
    r(`itx.cd(${p}).readEvents`, `itx.builtins.cd(${p}).readEvents`, "the rehearsal's own log (the envelope's results[i].script())"),
    r(`itx.cd(${p}).append`, `${M}.envelopeAppend(@)`, "the envelope's setSummary, sendMessage and setPreamble, to the rehearsal's own log alone"),
    r("itx.files.get", `${M}.file(@)`, "files under the rehearsal's own path (the envelope's results[i].load())"),
  ];
}

// ---------------------------------------------------------------------------------------------
// The rehearsal's start.

/** The two processors of a rehearsal's context. Both load from the config, through the context's
 *  implicit `cd`. */
const SOURCE = ["itx", ["cd", "/"], "config"];
const CLOUD_SPEC = { className: "CloudRehearsalDurableObject", mainModule: "apps/cloud-rehearsal/backend.ts", source: SOURCE, consumes: [STARTED] };
const AGENT_SPEC = { className: "AgentDurableObject", mainModule: "agents.ts", source: SOURCE };

/** Until the agent is born: its default config lands before `agent/created`, so the config of
 *  backend.ts, which comes later, is the one that counts. */
async function untilCreated(itx: Itx, mind: string) {
  for (const until = Date.now() + 20_000; Date.now() < until; await new Promise((resolve) => setTimeout(resolve, 500))) {
    const { events } = (await itx.cd(pathOf(mind)).readEvents(0, 100)) as { events: { type: string; payload?: { error?: unknown } }[] };
    if (events.some((event) => event.type === "events.iterate.com/agent/created")) return;
    const failed = events.find((event) => event.type === "events.iterate.com/agent/create-failed");
    if (failed) throw new Error(`cloud-rehearsal: the agent of ${mind} was not born: ${String(failed.payload?.error)}`);
  }
  throw new Error(`cloud-rehearsal: the agent of ${mind} was not born within 20 s`);
}

/** A NEW REHEARSAL, as apps/cloud/app.ts `createMind` makes a mind: the scripts' context, closed
 *  in one append; the rehearsal's rows, before any code runs there; the two processors; the
 *  agent's birth, by hand; and last `cloud/wizard-started`, from which backend.ts goes on. It
 *  carries what a rehearsal has of its own: where its Cloudflare is, and the guide to rehearse. */
export async function createRehearsal(itx: Itx, input: unknown) {
  const { userId, email, cloudflare, guide } = (input ?? {}) as Record<string, unknown>;
  if (typeof userId !== "string" || typeof email !== "string" || typeof cloudflare !== "string" || typeof guide !== "string")
    throw new Error("cloudRehearsal({ userId, email, cloudflare, guide }): four strings");
  if (guide.length === 0 || guide.length > 200_000) throw new Error("cloudRehearsal: the guide has 1 to 200,000 characters");
  const base = new URL(cloudflare);
  // a rehearsal never talks to Cloudflare: nothing here holds an access, and nothing may ask for one
  if (base.protocol !== "https:" || base.hostname === "cloudflare.com" || base.hostname.endsWith(".cloudflare.com") || !/^\/([A-Za-z0-9_-]{16,128}\/?)?$/.test(base.pathname) || base.search || base.hash)
    throw new Error("cloudRehearsal: `cloudflare` is the https origin of a fake Cloudflare, with at most one secret path segment, never Cloudflare's own");
  const address = `${base.origin}${base.pathname.replace(/\/$/, "")}`;
  const mind = `mind_${[...crypto.getRandomValues(new Uint8Array(20))].map((byte) => "abcdefghijklmnopqrstuvwxyz234567"[byte % 32]).join("")}`;
  const context = itx.cd(pathOf(mind));
  await itx.cd(scriptsOf(mind)).append(...scriptRowsOf(mind));
  await context.append(...mindRowsOf(mind));
  await context.processors.enable("cloud", CLOUD_SPEC);
  await context.processors.enable("agent", AGENT_SPEC);
  await context.append({ type: "events.iterate.com/agent/create-requested", idempotencyKey: "cloud/agent-create-requested", payload: {} });
  await untilCreated(itx, mind);
  await context.append({ type: STARTED, idempotencyKey: STARTED, payload: { userId, email, connectUrl: `${address}/connect`, cloudflare: address, guide } });
  return { mind, path: pathOf(mind) };
}

// ---------------------------------------------------------------------------------------------
// The model's key, and what a call may name.

/** The secrets that pay for the agent's loop, as its config names them (backend.ts), to OpenAI alone. */
export const MODEL_KEYS = ['getSecret("/secrets/chatgpt", { field: "accessToken" })', 'getSecret("/secrets/openai")'];
const MODEL_SECRETS = ["/secrets/chatgpt", "/secrets/openai"];
const MODEL_ORIGIN = "https://api.openai.com";
const CLOUDFLARE_ORIGIN = "https://api.cloudflare.com";
const NOT_CONNECTED = "Cloudflare is not connected. Make a link with itx.cloud.connectCloudflare() and give it to the person.";
/** The three appends of the agent loop's envelope (iterate-config jail.ts `ENVELOPE_APPENDS`). */
const ENVELOPE_APPENDS = ["events.iterate.com/agent/summary-updated", "events.iterate.com/agent/web-message-sent", "events.iterate.com/agent/preamble-entry-set"];

const decoded = (text: string) => {
  try {
    return decodeURIComponent(text);
  } catch {
    return text;
  }
};
/** Whether any of these values spells a secret's placeholder. */
const namesASecret = (...values: unknown[]) => values.some((value) => /getsecret/i.test(typeof value === "string" ? `${value} ${decoded(value)}` : (JSON.stringify(value ?? null) ?? "")));
const NAMES_A_SECRET = "A call names no secret: the person's Cloudflare access is added for you.";
const words = (error: unknown) => String((error as Error)?.message ?? error).slice(0, 300);

/** A long answer as its first characters and a word on how to get less; JSON as JSON when it fits. */
function cut(text: string, most: number, how: string): unknown {
  if (text.length > most) return { cut: `Only the first ${most} characters of the answer follow, as text: ${how}.`, text: text.slice(0, most) };
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}
const refused = (text: string, status = 403) => new Response(`${text}\n`, { status, headers: { "x-cloud-egress": "refused" } });
const JOBS = "/root/cloud";

// ---------------------------------------------------------------------------------------------
// The rehearsal.

export class RehearsalMind extends RpcTarget {
  readonly #itx: ItxOf;
  readonly #mind: string;
  readonly #path: string;

  constructor(itx: ItxOf, path: string) {
    super();
    this.#mind = mindOf(path);
    this.#path = pathOf(this.#mind);
    this.#itx = itx;
  }

  /** One request to the rehearsal's fake, as JSON in and text out. */
  async #toFake(itx: Itx, method: string, path: string, body?: unknown) {
    const start = await startOf(itx, this.#mind);
    if (!start) throw new Error("This rehearsal has not started yet.");
    const withBody = body !== undefined && method !== "GET";
    const answer: Response = await itx.fetch(
      new Request(`${start.cloudflare}${path}`, {
        method,
        headers: withBody ? { "content-type": "application/json" } : {},
        body: withBody ? JSON.stringify(body) : undefined,
        redirect: "manual",
      }),
    );
    return { status: answer.status, text: await answer.text().catch(() => ""), start };
  }

  /** WHY CLOUDFLARE MAY NOT BE USED, or null: the fake's `GET /user` must answer, and name the
   *  person who plays (as iterate Cloud checks that an access is its owner's own). */
  async #refusal(itx: Itx): Promise<string | null> {
    const user = await this.#toFake(itx, "GET", "/client/v4/user");
    if (user.status === 401) return NOT_CONNECTED;
    let email: unknown;
    try {
      email = (JSON.parse(user.text) as { result?: { email?: unknown } }).result?.email;
    } catch {}
    if (user.status !== 200 || typeof email !== "string")
      return `Cloudflare refused the access (GET /user answered ${user.status}). It lives about an hour. Make a new link with itx.cloud.connectCloudflare().`;
    if (email.toLowerCase() !== user.start.email.toLowerCase())
      return `That access belongs to another Cloudflare login, so it was deleted. The person must connect with the login they signed in with, ${user.start.email}: make a new link with itx.cloud.connectCloudflare().`;
    return null;
  }

  /** `{ url }`: the link where the person gives Cloudflare access. */
  async connectCloudflare(_input?: unknown) {
    using itx = this.#itx();
    const start = await startOf(itx, this.#mind);
    if (!start) return { error: "This mind has no owner yet." };
    return { url: `${start.cloudflare}/connect`, note: "Send the person this link at once, as a markdown link. It works for one hour." };
  }

  /** A NEW CLOUDFLARE ACCOUNT for this mind, in the person's name. */
  async makeAccount(input?: unknown) {
    const call = (input ?? {}) as { name?: unknown };
    using itx = this.#itx();
    const start = await startOf(itx, this.#mind);
    if (!start) return { error: "This mind has no owner yet." };
    const slug = start.email.toLowerCase().split("@")[0]!.split("+")[0]!.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
    const name = typeof call.name === "string" && call.name.trim() ? call.name.trim().slice(0, 100) : `iterate-${slug || "mind"}`;
    const answer = await this.#toFake(itx, "POST", "/client/v4/accounts", { name, standalone: true });
    const made = (cut(answer.text, 4000, "the answer was long") as { result?: { id?: unknown; name?: unknown } } | null)?.result;
    if (answer.status === 200 && typeof made?.id === "string") return { id: made.id, name: String(made.name ?? name) };
    return { status: answer.status, body: cut(answer.text, 4000, "the answer was long"), error: "Cloudflare did not make the account. Go on with an account the person has: connectCloudflare()." };
  }

  /** `{ status, body }`: one request to Cloudflare's API as the person. */
  async cloudflare(input: unknown) {
    const call = (input ?? {}) as { method?: unknown; path?: unknown; body?: unknown };
    const method = typeof call.method === "string" ? call.method : "GET";
    if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) throw new Error("itx.cloud.cloudflare: method is GET, POST, PUT, PATCH or DELETE");
    if (typeof call.path !== "string" || !/^\/(?!\/)[^\s#\\]*$/.test(call.path) || call.path.length > 2000 || /(^|\/)(\.|%2e){1,2}(\/|\?|$)/i.test(call.path))
      throw new Error("itx.cloud.cloudflare: path is a path under /client/v4, like /zones?account.id=<account>");
    if (namesASecret(call.path, call.body)) return { error: NAMES_A_SECRET };
    using itx = this.#itx();
    const refusal = await this.#refusal(itx);
    if (refusal) return { error: refusal };
    const answer = await this.#toFake(itx, method, `/client/v4${call.path}`, call.body);
    return { status: answer.status, body: cut(answer.text, 20_000, "ask for less, with per_page or a filter") };
  }

  /** One bash command in the mind's own sandbox: `{ exitCode, stdout, stderr }`, or with
   *  `background` `{ job, log }`, and the end of the job starts the agent's next turn. The
   *  rehearsal's fake plays the sandbox. */
  async sandbox(input: unknown) {
    const call = (input ?? {}) as { command?: unknown; timeoutSeconds?: unknown; background?: unknown };
    if (typeof call.command !== "string" || !call.command.trim() || call.command.length > 8000) throw new Error("itx.cloud.sandbox: command is 1 to 8000 characters");
    if (namesASecret(call.command)) return { error: NAMES_A_SECRET };
    using itx = this.#itx();
    try {
      const answer = await this.#toFake(itx, "POST", "/sandbox", { command: call.command, timeoutSeconds: call.timeoutSeconds, background: call.background === true });
      const said = cut(answer.text, 14_000, "the output was long") as { job?: unknown; endsInSeconds?: unknown; exitCode?: unknown } | null;
      if (answer.status !== 200 || !said || typeof said !== "object") return { error: `The command did not answer: the sandbox said ${answer.status}` };
      if (typeof said.job === "string") return await this.#background(itx, said.job, Number(said.endsInSeconds) || 0, Number(said.exitCode) || 0);
      return said;
    } catch (error) {
      return { error: `The command did not answer: ${words(error)}` };
    }
  }

  /** THE DEPLOY, in the background: `{ job, log }`. The fake plays it, and says when it ends. */
  async deploy(input: unknown) {
    const call = (input ?? {}) as { accountId?: unknown; domain?: unknown; name?: unknown; withoutApiTokens?: unknown };
    if (typeof call.accountId !== "string" || !/^[0-9a-f]{32}$/.test(call.accountId)) throw new Error("itx.cloud.deploy: accountId is the account's id: 32 hexadecimal characters");
    if (typeof call.name !== "string" || !/^[a-z][a-z0-9-]{1,29}$/.test(call.name)) throw new Error("itx.cloud.deploy: name is lower case letters, digits and -, 2 to 30 characters, starting with a letter");
    const domain = typeof call.domain === "string" ? call.domain.toLowerCase() : undefined;
    if (domain !== undefined && !DOMAIN.test(domain)) throw new Error("itx.cloud.deploy: domain is a domain, like ada-labs.com");
    using itx = this.#itx();
    const refusal = await this.#refusal(itx);
    if (refusal) return { error: refusal };
    try {
      const answer = await this.#toFake(itx, "POST", "/deploy", { account: call.accountId, name: call.name, ...(domain ? { domain } : {}) });
      const said = cut(answer.text, 4000, "the answer was long") as { job?: unknown; error?: unknown } | null;
      if (answer.status !== 200 || typeof said?.job !== "string") return { error: `The deploy did not start: ${String(said?.error ?? answer.status)}` };
      const going = await this.#toFake(itx, "GET", `/deploy/${said.job}`);
      const left = (cut(going.text, 2000, "") as { secondsLeft?: unknown } | null)?.secondsLeft;
      return await this.#background(itx, said.job, Number(left) || 0, 0);
    } catch (error) {
      return { error: `The deploy did not start: ${words(error)}` };
    }
  }

  /** THE HAND-OVER TO THE NEW MIND, THROUGH THE MIND MELD. Not iterate Cloud's yet: a draft of what its
   *  `handOver` may become (tasks/cloud-rehearsal.md). It needs no model on the new mind, so it comes
   *  before the AI step. Two events on this rehearsal's context:
   *  - the sign-up record, `cloud/installation-handed-over`: what the person said, and the notes for
   *    the new mind's onboarding agent. The new mind reads it (the template's cloud-handover.ts).
   *  - a row that sends that record, and nothing else, to the mind at `domain`, signed by this mind.
   *    That mind takes it once its owner lets this mind in: `letIn`, the link this answers, is the
   *    owner's first sign-in there. `handedOver` says whether the record arrived.
   *  Both live in a context of their own per domain (`#handoverPath`), so a row sends its own
   *  domain's record and no other: a second domain gets a second context, row and record.
   *  A second call for one domain sends no second record: it answers the same link. */
  async handOver(input: unknown) {
    const call = (input ?? {}) as { domain?: unknown; person?: unknown; said?: unknown; notes?: unknown };
    if (typeof call.domain !== "string" || typeof call.said !== "string" || !call.said.trim())
      throw new Error("itx.cloud.handOver: { domain, said, person?, notes? }. `said`: what the person told you that their mind should know, close to their own words. `person`: their first name. `notes`: what you did not ask, or got no answer to.");
    const domain = domainOf(call.domain, "handOver");
    using itx = this.#itx();
    const start = await startOf(itx, this.#mind);
    if (!start) throw new Error("cloud: this rehearsal has no start");
    const own = new URL(await itx.url()).hostname;
    const clean = (text: unknown) => (typeof text === "string" ? text.replaceAll(HANDOVER_NOTES_MARK, "").trim() : "");
    const facts = [clean(call.person) && `- Name: ${clean(call.person)}`, `- Email: ${start.email}`, `- Their mind: https://${domain}/`].filter(Boolean);
    const summary = [
      `About the person, from their signup at iterate Cloud before this mind existed:\n${facts.join("\n")}`,
      `What they said about the mind (ask none of it again):\n${clean(call.said)}`,
      HANDOVER_NOTES_MARK,
      // The record arrives only through the meld, so whoever reads it can take this as done.
      [clean(call.notes), `The owner let ${own} in when they signed up, before they first wrote to you. That subject is done: do not raise it.`].filter(Boolean).join("\n\n"),
    ].join("\n\n");
    const taken = (error: unknown) => (/IDEMPOTENCY_CONFLICT|idempotency key/i.test(`${(error as { code?: string })?.code ?? ""} ${String(error)}`) ? "sent before" : Promise.reject(error));
    const record = await itx
      .cd(this.#handoverPath(domain))
      .append(
        { type: HANDED_OVER, idempotencyKey: `cloud/handed-over/${domain}`, payload: { handover: this.#mind, destination: domain, cloud: own, installation: this.#mind, summary } },
        { type: "events.iterate.com/itx/subscription-configured", idempotencyKey: `cloud/sends-to/${domain}`, payload: { name: sendsTo(domain), target: `itx.minds.get(${JSON.stringify(domain)}).deliverEvents`, consumes: [HANDED_OVER], afterOffset: 0 } },
      )
      .then(() => "sent", taken);
    return { record, letIn: `https://${domain}/let-in/${own}`, note: "Give the person letIn as a link. It signs them in to their mind and has them allow this with their passkey. Then ask handedOver({ domain }) until it answers arrived." };
  }

  /** WHETHER THE NEW MIND TOOK THE RECORD, which it does once its owner let this mind in: the row's
   *  cursor says so. A refused delivery is tried again later and later (1 s, 2 s, 4 s and on, up to
   *  30 minutes), so a call that finds the record not taken has the row try again now. */
  async handedOver(input: unknown) {
    const call = (input ?? {}) as { domain?: unknown };
    const domain = domainOf(call.domain, "handedOver");
    using itx = this.#itx();
    const context = itx.cd(this.#handoverPath(domain));
    const name = sendsTo(domain);
    const row = (await context.subscriptions.get(name)) as { cursor?: { confirmedOffset: number }; halted?: { error?: string } } | null;
    const record = (await context.waitForEvent({ type: HANDED_OVER, payload: { destination: domain }, afterOffset: 0, timeoutMs: 1000 }).catch(() => null)) as { offset: number } | null;
    if (!row || !record) return { error: `Nothing is on its way to ${domain}: call handOver first.` };
    if ((row.cursor?.confirmedOffset || 0) >= record.offset) return { arrived: true };
    await context.append({ type: "events.iterate.com/itx/subscription-delivery-resumed", payload: { name } });
    return { arrived: false, note: "Their mind has not taken it: its owner has not let this mind in yet, or did a moment ago. Ask again in 5 seconds." };
  }

  /** The context that holds the hand-over to one domain: its record and the row that sends it. */
  #handoverPath(domain: string) {
    return `${this.#path}/handovers/${sendsTo(domain)}`;
  }

  /** A command that runs on after this call. Its end is one developer note on the rehearsal's
   *  context, which starts the agent's next turn: the words iterate Cloud's sandbox posts. */
  async #background(itx: Itx, job: string, endsInSeconds: number, exitCode: number) {
    const id = job.replace(/[^a-z0-9]/gi, "").slice(-12) || "job";
    await itx.cd(this.#path).schedules.set({
      key: `cloud/job-ended:${id}`,
      when: { afterMs: Math.max(1, endsInSeconds) * 1000 },
      events: [
        {
          type: CONTEXT_ADDED,
          payload: { role: "developer", content: `The background command ${id} ended with exit code ${exitCode}. Its output is in ${JOBS}/job-${id}.log in the sandbox. Read what you need of it and go on.` },
        },
      ],
    });
    return { job: id, log: `${JOBS}/job-${id}.log`, note: "It runs in the background. You are told when it ends: end your turn, or read the log meanwhile." };
  }

  /** THE NARROWED EGRESS of this rehearsal, for its agent's loop: the internet with no secret, but
   *  the model's key to OpenAI; and Cloudflare's API, which is the rehearsal's fake. A WebSocket
   *  upgrade does not pass: a Response that holds a socket does not cross this RPC call, so the
   *  agent's loop then sends its model request over HTTP. */
  async fetch(...args: unknown[]): Promise<Response> {
    let request: Request;
    try {
      request = new Request(...(args as [RequestInfo, RequestInit?]));
    } catch (error) {
      return refused(`cloud: not a request (${words(error)})`, 400);
    }
    const url = new URL(request.url);
    if (request.headers.get("upgrade")?.toLowerCase() === "websocket") return refused("cloud: a WebSocket does not pass this egress; use HTTP", 426);
    const authorization = request.headers.get("authorization");
    const modelKey = url.origin === MODEL_ORIGIN && MODEL_KEYS.some((key) => authorization === `Bearer ${key}`);
    const others = [request.url, ...[...request.headers].filter(([name]) => !(modelKey && name === "authorization")).map(([, value]) => value)];
    if (namesASecret(...others)) return refused("cloud: a request names no secret; Cloudflare's API gets the person's access without one");
    let outgoing = new Request(request, { redirect: "manual" });
    if (url.origin === CLOUDFLARE_ORIGIN) {
      let start;
      {
        using itx = this.#itx();
        start = await startOf(itx, this.#mind);
      }
      if (!start) return refused("cloud: this rehearsal has not started yet");
      const headers = new Headers(request.headers);
      headers.delete("authorization");
      // the body is `outgoing`'s now: making it from `request` took it
      outgoing = new Request(`${start.cloudflare}${url.pathname}${url.search}`, { method: request.method, headers, body: outgoing.body, redirect: "manual" });
    }
    // The scope lives as long as the answer's body: released when the body ends, or at once when there is none.
    const itx = this.#itx();
    let answer: Response;
    try {
      answer = await itx.fetch(outgoing);
    } catch (error) {
      itx[Symbol.dispose]();
      throw error;
    }
    if (!answer.body || [101, 204, 205, 304].includes(answer.status)) {
      itx[Symbol.dispose]();
      return answer;
    }
    const { readable, writable } = new TransformStream();
    void answer.body
      .pipeTo(writable)
      .catch(() => {})
      .finally(() => itx[Symbol.dispose]());
    return new Response(readable, { status: answer.status, statusText: answer.statusText, headers: answer.headers });
  }

  /** The envelope's appends to the rehearsal's own log: three types alone, as `{ type, payload }`. */
  async envelopeAppend(...events: unknown[]) {
    if (events.length === 0) throw new Error("cloud: nothing to append");
    for (const event of events) {
      const keys = event && typeof event === "object" ? Object.keys(event) : [];
      const type = (event as { type?: unknown } | null)?.type;
      if (typeof type !== "string" || !ENVELOPE_APPENDS.includes(type) || keys.some((key) => key !== "type" && key !== "payload"))
        throw new Error(`cloud: a script appends to the mind's log only ${ENVELOPE_APPENDS.join(", ")} ({ type, payload }), not ${JSON.stringify(type)}`);
    }
    using itx = this.#itx();
    await itx.cd(this.#path).append(...events);
    return null;
  }

  /** `{ set }` for the model's keys alone: the agent's loop asks before each request. */
  async describeSecret(path: unknown) {
    if (typeof path !== "string" || !MODEL_SECRETS.includes(path)) throw new Error(`cloud: this mind describes ${MODEL_SECRETS.join(" and ")} alone`);
    using itx = this.#itx();
    const described = (await itx.secrets.describe(path)) as { set?: boolean };
    return { set: described?.set === true };
  }

  /** A file under the rehearsal's own path, as `itx.files.get(path)` hands it. */
  file(path: unknown) {
    if (typeof path !== "string" || path.length > 500 || !path.startsWith(`${this.#path}/`) || path.split("/").some((part) => part === "." || part === ".."))
      throw new Error(`cloud: a file under ${this.#path}/ alone, not ${JSON.stringify(path)}`);
    return new RehearsalFile(this.#itx, path);
  }
}

/** One file of a rehearsal, as `itx.files.get(path)` hands it. Each call reads or writes at once,
 *  with its own scope. */
class RehearsalFile extends RpcTarget {
  readonly #itx: ItxOf;
  readonly #path: string;
  constructor(itx: ItxOf, path: string) {
    super();
    this.#itx = itx;
    this.#path = path;
  }
  async bytes() {
    using itx = this.#itx();
    return new Uint8Array(await itx.files.get(this.#path).bytes());
  }
  async put(input: unknown) {
    using itx = this.#itx();
    return await itx.files.get(this.#path).put(input);
  }
  async url() {
    using itx = this.#itx();
    return await itx.files.get(this.#path).url();
  }
}