iterate.com / cloud

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

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

// backend.ts — THE REHEARSAL'S STREAM PROCESSOR `cloud`, on each rehearsal's context
// (/apps/cloud-rehearsal/minds/<mind>), beside the platform's `agent` processor. One rule: IF
// `cloud/wizard-started` happens (mind.ts `createRehearsal` appends it), THEN one append of the
// agent's config, its instructions, the free domain names (`cloud/domains-found`), and the note
// that starts the agent's first turn. No state, no model.
//
// COPIED FROM iterate/iterate-config apps/cloud/backend.ts at db9c004 (17 Nov 2026). WHAT DIFFERS:
// the instructions are the guide that the rehearsal's first event carries, where iterate Cloud
// reads its own onboarding.md; the model's key is this mind's own (mind.ts `MODEL_KEYS`); and the
// agent's config sets `llmRequestPolicy`, which iterate Cloud's does not yet (`AGENT_CONFIG`).
// ONE NOTE IS THE REHEARSAL'S OWN: where Cloudflare's
// dashboard is. The agent's calls go to the fake without its knowing (mind.ts), but a link that it
// writes for the person is its own words, so it must be told.
import { StreamProcessorDurableObject } from "iterate/sdk";
import { defineProcessorContract, StreamProcessor, type ProcessEventArgs } from "iterate/stream/processor";
import { z } from "zod";
import { MODEL_KEYS } from "./mind.ts";

const STARTED = "cloud/wizard-started";
/** { email, domains: [{ name }] }: names free to register now. The page draws them as buttons. */
const DOMAINS_FOUND = "cloud/domains-found";
const CONFIGURED = "events.iterate.com/agent/configured";
const CONTEXT_ADDED = "events.iterate.com/agent/context-added";

/** HOW THE REHEARSAL'S AGENT IS CONFIGURED, as iterate Cloud's: it answers an input at once, and
 *  it gets no note of the other agents of the mind that hosts it. The model's key is this mind's. */
const AGENT_CONFIG = {
  llm: { apiKeys: MODEL_KEYS, reasoningEffort: "low" },
  llmRequestDebounceMs: 0,
  // Not iterate Cloud's yet: the person's words cut short the answer the model is writing. A mind reads this field when its platform has it (iterate/private, branch `agent-llm-request-policy`), or when its agents.ts adds it from outside, as tthq.app's does (tasks/cloud-rehearsal.md). Any other mind drops it.
  llmRequestPolicy: { behaviour: "interrupt-current-request" },
  maxAutonomousTurns: 40,
  mindSnapshotEveryMs: 0,
};

const MAILBOXES = new Set(["gmail", "googlemail", "outlook", "hotmail", "icloud", "yahoo", "proton", "protonmail", "me", "live"]);

/** Names a person might want for their mind, made from their email alone: the "erate" names first,
 *  as "iterate" (jonas → jonaserate), then the plain ones, each as .com and as .dev. */
export function candidateNames(email: string) {
  const plain = (text: string) => text.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]/g, "");
  const [local = "", host = ""] = email.split("@");
  const [first = "", ...rest] = local.split("+")[0]!.split(/[._-]+/).map(plain);
  const last = rest.at(-1) ?? "";
  const company = plain(host.split(".").at(-2) ?? "");
  const erate = (name: string) => `${name.replace(/[aeiouy]$/, "")}erate`;
  const stems = [first && erate(first), last && erate(last), first + last, first && last && `${first}-${last}`, first && `hey${first}`, first && `${first}hq`, first && `${first}mind`, last, !company || MAILBOXES.has(company) ? "" : `${company}mind`];
  const good = [...new Set(stems.filter((stem) => stem.length >= 4 && stem.length <= 40))];
  return ["com", "dev"].flatMap((tld) => good.map((stem) => `${stem}.${tld}`));
}

/** The registries' own public lookups (RDAP), by top-level domain: 404 says that nobody holds the name. */
const REGISTRIES: Record<string, string> = { com: "https://rdap.verisign.com/com/v1/domain/", dev: "https://pubapi.registry.google/rdap/domain/" };

/** Which of `names` are free to register now. A lookup with no answer in 8 seconds says nothing. */
export async function freeOf(names: string[]) {
  const late = new Promise<null>((resolve) => setTimeout(() => resolve(null), 8000));
  const looked = await Promise.all(
    names.map(async (name) => {
      const lookup = fetch(REGISTRIES[name.split(".").at(-1)!] + name).then(
        (answer) => answer.status,
        () => null,
      );
      return (await Promise.race([lookup, late])) === 404 ? [name] : [];
    }),
  );
  return looked.flat();
}

const State = z.object({});
type State = z.output<typeof State>;
const CloudContract = defineProcessorContract({
  slug: "cloud",
  version: "2",
  description: "A rehearsal of iterate Cloud's sign-up: at its start, the agent's config and instructions, the free domain names, and the agent's first note (apps/cloud-rehearsal/backend.ts).",
  stateSchema: State,
  consumes: [STARTED],
  emits: [CONFIGURED, CONTEXT_ADDED, DOMAINS_FOUND],
});

class CloudProcessor extends StreamProcessor<State> {
  readonly contract = CloudContract;

  /** THE WIZARD STARTED. `blockProcessorWhile` holds the processor's cursor until the work ends,
   *  so a restart in the middle does it again; the keys let each event land once. */
  override processEvent({ event, append, blockProcessorWhile }: ProcessEventArgs<State>): undefined {
    if (event?.type !== STARTED) return;
    const { email, connectUrl, guide, cloudflare } = event.payload as { email: string; connectUrl: string; guide: string; cloudflare: string };
    blockProcessorWhile(async () => {
      const free = await freeOf(candidateNames(email));
      await append(
        { type: CONFIGURED, idempotencyKey: "cloud/config", payload: { config: AGENT_CONFIG } },
        // read by the agent, and no turn of its own: the note below starts the first one
        { type: CONTEXT_ADDED, idempotencyKey: "cloud/instructions", payload: { role: "developer", content: guide, llmRequestPolicy: { behaviour: "dont-trigger-request" } } },
        {
          type: CONTEXT_ADDED,
          idempotencyKey: "cloud/rehearsal-dashboard",
          payload: {
            role: "developer",
            content: `In this session, Cloudflare's dashboard is at ${cloudflare} , not https://dash.cloudflare.com . Write every link to a page of Cloudflare's dashboard with that address: ${cloudflare}/<account>/workers/plans , for example.`,
            llmRequestPolicy: { behaviour: "dont-trigger-request" },
          },
        },
        { type: DOMAINS_FOUND, idempotencyKey: DOMAINS_FOUND, payload: { email, domains: free.map((name) => ({ name })) } },
        {
          type: CONTEXT_ADDED,
          idempotencyKey: "cloud/start-note",
          payload: {
            role: "developer",
            content: `A person signed in with Cloudflare as ${email} and started a new mind. The app looked up domain names made from their address at the registries. Free to register now: ${free.join(", ") || "none of the names it tried"}. The page shows them these names as buttons. Their link to connect Cloudflare, good for one hour: ${connectUrl} . Greet the person and begin (step 1).`,
          },
        },
      ).catch((error: unknown) => (/IDEMPOTENCY_CONFLICT|idempotency key/i.test(`${(error as { code?: string })?.code ?? ""} ${String(error)}`) ? undefined : Promise.reject(error)));
    });
  }
}

export class CloudRehearsalDurableObject extends StreamProcessorDurableObject<State> {
  processor = new CloudProcessor();
}