iterate.com / cloud

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

cloud / scripts / cloud-rehearsal / install.tsmain at aacbc74

// install.ts — INSTALLS THE REHEARSAL APP INTO A MIND, once:
//
//   node scripts/cloud-rehearsal/install.ts --mind tthq.app
//
// It is one commit to the mind's config repo, and the only one: start.ts starts each rehearsal
// with a call, not a commit. The commit holds:
//   - apps/cloud-rehearsal/mind.ts and backend.ts, from mind-app/ here. They are copies of
//     iterate-config's apps/cloud (their headers say what differs), kept as .txt so that this
//     workspace neither typechecks nor lints another repo's code;
//   - two methods in api.ts, `itx.config.cloudRehearsalMind` and `itx.config.cloudRehearsal`;
//   - one line in agents.ts: a rehearsal's agent reads none of the mind's standing files.
// The mind must be on the default template: the places in api.ts and agents.ts are found by
// their text, and the install stops when one is not there. A second run changes only what differs.
import { spawnSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { parseArgs } from "node:util";

const here = import.meta.dirname;
const { values } = parseArgs({ options: { mind: { type: "string" } } });
if (!values.mind) throw new Error("usage: install.ts --mind <domain>");

const methods = `  /** \`itx.config.cloudRehearsalMind(path)\`: one rehearsal of iterate Cloud's sign-up
   *  (apps/cloud-rehearsal/mind.ts \`RehearsalMind\`), for the rows of its two contexts: the agent's
   *  tools, and the narrowing of itx for it. */
  cloudRehearsalMind(path: string) {
    return new RehearsalMind(() => this.getItx(), path);
  }

  /** \`itx.config.cloudRehearsal({ userId, email, cloudflare, guide })\`: starts one rehearsal, whose
   *  Cloudflare is the fake at \`cloudflare\` and whose agent is told \`guide\`. It answers
   *  \`{ mind, path }\`; the chat is the Dash's, at \`/agents/<path>\`. */
  async cloudRehearsal(input: unknown) {
    using itx = this.getItx();
    return await createRehearsal(itx, input);
  }

`;
const standingFiles = `AgentDurableObject.standingFiles = (path, files) =>
  // a rehearsal's agent reads nothing of this mind: its instructions come as a note
  // (apps/cloud-rehearsal/backend.ts), as iterate Cloud's own agent's do
  path.startsWith("/apps/cloud-rehearsal/minds/") ? [] : [...new Set(["AGENTS.md", "mind.md", ...files])];`;
const dashLinksImport = 'import { dashLink, type DashLinkInput } from "./apps/dash/links.ts";';
const slackMethod = "  /** `itx.config.slack(method, args)`:";
const templateStandingFiles =
  'AgentDurableObject.standingFiles = (_path, files) => [\n  ...new Set(["AGENTS.md", "mind.md", ...files]),\n];';

const script = `const swapOnce = (source, file, from, to) => {
  if (source.split(from).length !== 2) throw new Error(file + " is not the default template's: it does not have exactly one of " + JSON.stringify(from));
  return source.replace(from, () => to);
};
const repo = itx.repos.get("/repos/config");
const tip = await repo.tip();
const read = (path) => repo.readFile(path, { commitOid: tip }).catch(() => null);
const [api, agents, mind, backend] = await Promise.all([read("api.ts"), read("agents.ts"), read("apps/cloud-rehearsal/mind.ts"), read("apps/cloud-rehearsal/backend.ts")]);
const files = {
  "apps/cloud-rehearsal/mind.ts": ${JSON.stringify(readFileSync(join(here, "mind-app/mind.ts.txt"), "utf8"))},
  "apps/cloud-rehearsal/backend.ts": ${JSON.stringify(readFileSync(join(here, "mind-app/backend.ts.txt"), "utf8"))},
  "api.ts": api?.includes("cloudRehearsalMind")
    ? api
    : swapOnce(
        swapOnce(api ?? "", "api.ts", ${JSON.stringify(dashLinksImport)}, ${JSON.stringify(`${dashLinksImport}\nimport { createRehearsal, RehearsalMind } from "./apps/cloud-rehearsal/mind.ts";`)}),
        "api.ts",
        ${JSON.stringify(slackMethod)},
        ${JSON.stringify(methods + slackMethod)},
      ),
  "agents.ts": agents.includes("/apps/cloud-rehearsal/minds/") ? agents : swapOnce(agents, "agents.ts", ${JSON.stringify(templateStandingFiles)}, ${JSON.stringify(standingFiles)}),
};
const before = { "apps/cloud-rehearsal/mind.ts": mind, "apps/cloud-rehearsal/backend.ts": backend, "api.ts": api, "agents.ts": agents };
const changes = Object.entries(files).filter(([path, content]) => before[path] !== content).map(([path, content]) => ({ path, content }));
if (changes.length === 0) return "The rehearsal app is installed already, and nothing differs.";
// where the root log ends now: the outcome of the commit lands after it
const head = (await itx.readEvents(Number.MAX_SAFE_INTEGER, 1)).scannedThroughOffset;
const { commitOid } = await repo.commitFiles({ message: "apps/cloud-rehearsal: a rehearsal of iterate Cloud's sign-up, with its agent's rows and tools and a fake Cloudflare\\n\\nCopied from iterate/iterate-config apps/cloud.\\n\\nVia: scripts/cloud-rehearsal/install.ts", parent: tip, changes });
// An outcome names its commit in payload.trigger.commitOid, and a payload filter compares
// top-level fields alone: take each outcome after the head until one names this commit.
let outcome;
let after = head;
do {
  outcome = await itx.waitForEvent({ type: ["events.iterate.com/mind/worker-updated", "events.iterate.com/mind/worker-update-failed"], afterOffset: after, timeoutMs: 120000 });
  after = outcome.offset;
} while (outcome.payload.trigger?.commitOid !== commitOid);
if (outcome.payload.error) throw new Error(outcome.payload.error);
return "Installed in commit " + commitOid + ": " + changes.map((change) => change.path).join(", ");`;

mkdirSync(join(here, "runs.ignoreme"), { recursive: true });
const file = join(here, "runs.ignoreme", "install.js");
writeFileSync(file, script);
const result = spawnSync("iterate", ["itx", "run", "--mind", values.mind, "--file", file], {
  cwd: resolve(here, "../.."),
  encoding: "utf8",
  env: { ...process.env, ITERATE_SKIP_BROWSER_OPEN: "1" },
});
console.log(`${result.stdout}${result.stderr}`.trim());
process.exitCode = result.status === 0 ? 0 : 1;