Skip to content
Myr

swarm.ts

This file

Path

scripts/swarm.ts

531 lines · 14.6 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { AskListing } from "@repo/protocol/domain/ask";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Envelope } from "@repo/protocol/envelope";5import { Handle, sameHandle } from "@repo/protocol/ids";6import type { ProjectName } from "@repo/protocol/ids";7import type { Refusal } from "@repo/protocol/refusal";8import {9  Clock,10  Config,11  Console,12  DateTime,13  Effect,14  Option,15  Redacted,16  Result,17  Schema,18  Stdio,19} from "effect";2021import { isRecorded, readLedger, recordCreated } from "../infra/created.ts";22import {23  platformOrigin,24  recordedSubdomain,25  repoRoot,26  resources,27  subdomainFile,28} from "../infra/stages.ts";29import type { Stage } from "../infra/stages.ts";30import { optionsOf } from "./lib/swarm/args.ts";31import type { SwarmOptions } from "./lib/swarm/args.ts";32import { runAgent, startCommand } from "./lib/swarm/loop.ts";33import { planSwarm, SwarmPlan } from "./lib/swarm/plan.ts";34import type { Assignment } from "./lib/swarm/plan.ts";35import { brief } from "./lib/swarm/prompt.ts";36import {37  agentsFile,38  AgentsResult,39  runDir,40  SwarmDir,41  writeAgentsResult,42} from "./lib/swarm/results.ts";43import type { AgentRun } from "./lib/swarm/results.ts";44import { roster } from "./lib/swarm/roster.ts";45import { headlessView } from "./lib/swarm/views/headless.ts";46import type { SwarmView } from "./lib/swarm/views/headless.ts";47import { openHerdrView } from "./lib/swarm/views/herdr.ts";48import {49  anonymousEnv,50  cliEntry,51  personEnv,52  prepareWorkspace,53  run,54  scrubbed,55  shellQuoted,56  SwarmFailed,57  TOKEN_VARIABLE,58} from "./lib/swarm/workspace.ts";59import type { Ran } from "./lib/swarm/workspace.ts";6061const failed = (reason: string) => new SwarmFailed({ reason });6263const SESSIONS_VARIABLE = "SESSION_TOKENS";6465const originOf = (options: SwarmOptions) =>66  Option.match(options.url, {67    onNone: () =>68      recordedSubdomain.pipe(69        Effect.flatMap(Effect.fromOption),70        Effect.mapError(() =>71          failed(72            `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`73          )74        ),75        Effect.map((subdomain) => platformOrigin(options.stage, subdomain))76      ),77    onSome: Effect.succeed,78  });7980const cli = (81  args: readonly string[],82  env: Readonly<Record<string, string | undefined>>83) => run({ args: [cliEntry, ...args], command: "bun", env });8485const tagsOf = (refusals: readonly Refusal[]) =>86  refusals.map(({ _tag }) => _tag).join(", ");8788class Refused extends Schema.TaggedError<Refused>()("Refused", {89  reason: Schema.String,90  tags: Schema.Array(Schema.String),91}) {92  override get message() {93    return this.reason;94  }95}9697const envelopeOf =98  <A, I>(99    data: Schema.Codec<A, I>,100    what: string,101    scrub: (text: string) => string102  ) =>103  (ran: Ran): Effect.Effect<A, SwarmFailed | Refused> =>104    Effect.gen(function* () {105      const printed = ran.stderr.trim() === "" ? ran.stdout : ran.stderr;106107      const envelope: Envelope<A> = yield* Schema.decodeEffect(108        Schema.fromJsonString(Envelope(data))109      )(ran.stdout).pipe(110        Effect.mapError(() =>111          failed(112            scrub(113              `${what} exited ${ran.code} without its JSON: ${printed.trim().slice(0, 500)}`114            )115          )116        )117      );118119      if (envelope.ok) {120        return envelope.data;121      }122123      return yield* new Refused({124        reason: `${what}: refused ${tagsOf(envelope.refusals)}`,125        tags: envelope.refusals.map(({ _tag }) => _tag),126      });127    });128129const isRefused = Schema.is(Refused);130131const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });132133const listAsks = (origin: string, project: ProjectName) =>134  Effect.gen(function* () {135    const home = `${yield* SwarmDir}/anonymous`;136137    const listed = yield* cli(138      ["asks", "--project", project, "--json"],139      anonymousEnv({ configHome: home, platformUrl: origin })140    ).pipe(141      Effect.flatMap(142        envelopeOf(Listed, `asks --project ${project}`, (text) => text)143      ),144      Effect.mapError(({ reason }) => failed(reason))145    );146147    return listed.asks;148  });149150const planLines = (151  plan: SwarmPlan,152  origin: string,153  swarm: string154): readonly string[] => {155  const rows = plan.assignments.map(({ ask, contributor, territory }) => {156    const dir = `${swarm}/<run>/${contributor.handle}`;157158    const command = startCommand({ brief: "<brief>", contributor, dir })159      .map(shellQuoted)160      .join(" ");161162    return [163      contributor.handle,164      contributor.harness,165      contributor.model,166      ask,167      territory,168      `cd ${shellQuoted(`${dir}/clone`)} && ${command}`,169    ];170  });171172  const header = ["handle", "harness", "model", "ask", "territory", "command"];173174  const widths = header.map((title, column) =>175    Math.max(title.length, ...rows.map((row) => row[column]?.length ?? 0))176  );177178  const line = (cells: readonly string[]) =>179    cells180      .map((cell, column) =>181        column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)182      )183      .join("  ");184185  const nudged = plan.assignments.flatMap(({ contributor, nudge }) =>186    nudge === undefined187      ? []188      : [`nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`]189  );190191  return [192    `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,193    line(header),194    ...rows.map(line),195    `held: ${plan.held.length === 0 ? "none" : plan.held.join(", ")}`,196    ...nudged,197  ];198};199200const runName = Effect.map(DateTime.now, (now) =>201  DateTime.formatIso(now)202    .slice(0, 19)203    .replaceAll(/[-:]/gu, "")204    .replace("T", "-")205);206207const headCommit = Effect.gen(function* () {208  const root = yield* repoRoot;209210  const head = yield* run({211    args: ["-C", root, "rev-parse", "HEAD"],212    command: "git",213    env: {},214  });215216  return head.code === 0 && head.stdout.trim() !== ""217    ? head.stdout.trim()218    : yield* failed(`git rev-parse HEAD exited ${head.code}`);219});220221const decodeSessions = Schema.decodeUnknownEffect(222  Schema.fromJsonString(Schema.Record(Schema.String, Handle))223);224225/** A missing person fails before anything is claimed, naming them and never a token. */226const tokensFor = (handles: readonly Handle[]) =>227  Effect.gen(function* () {228    const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(229      Effect.mapError(() =>230        failed(231          `no ${SESSIONS_VARIABLE} in the environment: run the swarm under \`bunx varlock run --path apps/platform/ --\`, or with the stage's secrets in the env`232        )233      )234    );235236    const sessions = yield* decodeSessions(raw).pipe(237      Effect.mapError(() =>238        failed(`${SESSIONS_VARIABLE} is not a JSON object from token to handle`)239      )240    );241242    const tokens = new Map(243      handles.flatMap((handle) => {244        const token = Object.entries(sessions).find(([, person]) =>245          sameHandle(person, handle)246        )?.[0];247248        return token === undefined249          ? []250          : [[handle, Redacted.make(token)] as const];251      })252    );253254    const missing = handles.filter((handle) => !tokens.has(handle));255256    return missing.length === 0257      ? tokens258      : yield* failed(259          `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each to the stage's ${SESSIONS_VARIABLE} secret (in the stage's secrets file, STAGE_SECRETS_FILE), and to the env the swarm runs in, then run the swarm again`260        );261  });262263const recordFork = (stage: Stage, claim: ClaimView) =>264  Effect.gen(function* () {265    const namespace = resources(stage).projects;266267    const known = isRecorded(yield* readLedger, {268      kind: "repo",269      name: claim.fork,270      namespace,271      stage,272    });273274    if (!known) {275      yield* recordCreated({276        at: yield* DateTime.now,277        by: "swarm",278        kind: "repo",279        name: claim.fork,280        namespace,281        stage,282      });283    }284  }).pipe(285    Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))286  );287288const Claimed = Schema.Struct({ claim: ClaimView });289290const Shown = Schema.Struct({291  ask: Schema.Struct({ id: Schema.NonEmptyString }),292  brief: Schema.NonEmptyString,293});294295const contributorRun = (input: {296  readonly assignment: Assignment;297  readonly options: SwarmOptions;298  readonly origin: string;299  readonly run: string;300  readonly token: Redacted.Redacted;301  readonly view: SwarmView;302}) =>303  Effect.gen(function* () {304    const { assignment, options, origin, token } = input;305    const { contributor } = assignment;306    const { handle } = contributor;307    const started = yield* Clock.currentTimeMillis;308    const configHome = `${yield* runDir(input.run)}/${handle}/config`;309    const env = personEnv({ configHome, platformUrl: origin, token });310311    const scrub = (text: string) =>312      scrubbed(text, { env, redacted: [TOKEN_VARIABLE] });313314    const setup = Effect.gen(function* () {315      const { claim } = yield* cli(316        ["claim", assignment.ask, "--project", options.project, "--json"],317        env318      ).pipe(319        Effect.flatMap(320          envelopeOf(Claimed, `${handle}: claim ${assignment.ask}`, scrub)321        )322      );323324      yield* recordFork(options.stage, claim);325326      const page = yield* cli(327        ["ask", assignment.ask, "--project", options.project, "--json"],328        env329      ).pipe(330        Effect.flatMap(331          envelopeOf(Shown, `${handle}: ask ${assignment.ask}`, scrub)332        )333      );334335      const workspace = yield* prepareWorkspace({336        claim,337        contributor,338        platformUrl: origin,339        run: input.run,340        token,341      });342343      return {344        text: brief({345          ask: assignment.ask,346          askMarkdown: page.brief,347          nudge: Option.fromUndefinedOr(assignment.nudge),348          project: options.project,349          remote: claim.remote,350        }),351        workspace,352      };353    });354355    const ready = yield* Effect.result(setup);356357    if (Result.isFailure(ready)) {358      const { failure } = ready;359      const ended = yield* Clock.currentTimeMillis;360361      yield* Console.error(`${handle}: ${scrub(failure.reason)}`);362363      return {364        adapter: contributor.adapter,365        ask: assignment.ask,366        attempts: 0,367        durationMs: ended - started,368        handle,369        harness: contributor.harness,370        model: contributor.model,371        outcome: "failed",372        refusals: Object.fromEntries(373          (isRefused(failure) ? failure.tags : []).map((tag) => [tag, 1])374        ),375      } satisfies AgentRun;376    }377378    yield* Console.error(379      `${handle}: claimed ${assignment.ask}; workspace ${ready.success.workspace.dir}`380    );381382    return yield* runAgent({383      assignment,384      brief: ready.success.text,385      maxContinuations: 3,386      project: options.project,387      timeoutMs: options.timeoutMin * 60_000,388      view: input.view,389      workspace: ready.success.workspace,390    });391  });392393const runLine = ({394  ask,395  attempts,396  handle,397  harness,398  outcome,399  refusals,400}: AgentRun) => {401  const met = Object.entries(refusals)402    .map(([tag, count]) => `${tag}×${count}`)403    .join(", ");404405  return `${handle} (${harness}) ${ask}: ${outcome}, ${attempts} attempts${met === "" ? "" : `, refused ${met}`}`;406};407408const printJson = <S extends Schema.Top>(schema: S, value: S["Type"]) =>409  Effect.flatMap(410    Schema.encodeEffect(Schema.fromJsonString(schema))(value),411    Console.log412  ).pipe(Effect.orDie);413414export const main = (argv: readonly string[]) =>415  Effect.gen(function* () {416    const options = yield* optionsOf(argv);417    const origin = yield* originOf(options);418    const asks = yield* listAsks(origin, options.project);419420    const people =421      options.only.length === 0422        ? roster423        : roster.filter(({ handle }) => options.only.includes(handle));424425    const plan = yield* Effect.fromResult(426      planSwarm({427        asks,428        project: options.project,429        roster: people,430        scenario: options.scenario,431        stage: options.stage,432      })433    ).pipe(Effect.mapError(({ message }) => failed(message)));434435    const say = (line: string) =>436      options.json ? Effect.void : Console.log(line);437438    yield* Effect.forEach(planLines(plan, origin, yield* SwarmDir), say, {439      discard: true,440    });441442    if (options.dryRun) {443      yield* say("dry run: nothing claimed, no harness started");444445      if (options.json) {446        yield* printJson(SwarmPlan, plan);447      }448449      return;450    }451452    const tokens = yield* tokensFor(453      plan.assignments.map(({ contributor }) => contributor.handle)454    );455456    const name = yield* runName;457    const commit = yield* headCommit;458    const at = yield* DateTime.now;459460    const runs = yield* Effect.scoped(461      Effect.gen(function* () {462        const view =463          options.view === "herdr"464            ? yield* openHerdrView({465                contributors: plan.assignments.map(466                  ({ contributor }) => contributor467                ),468                origin,469                project: options.project,470                runDir: yield* runDir(name),471              }).pipe(472                Effect.tap(({ workspace }) =>473                  say(474                    `herdr: workspace ${workspace} holds the panes; close it with herdr workspace close ${workspace}`475                  )476                ),477                Effect.map(({ view: panes }) => panes)478              )479            : headlessView;480481        return yield* Effect.forEach(482          plan.assignments,483          (assignment) =>484            Effect.flatMap(485              Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),486              (token) =>487                contributorRun({488                  assignment,489                  options,490                  origin,491                  run: name,492                  token,493                  view,494                })495            ),496          { concurrency: 6 }497        ).pipe(Effect.mapError(() => failed("a contributor lost their token")));498      })499    );500501    const result: AgentsResult = {502      at,503      commit,504      project: options.project,505      runs,506      scenario: options.scenario,507      stage: options.stage,508      v: 1,509    };510511    yield* writeAgentsResult({ result, run: name }).pipe(512      Effect.mapError(({ message }) => failed(`agents.json: ${message}`))513    );514515    yield* Effect.forEach(runs.map(runLine), say, { discard: true });516    yield* say(`summary: ${agentsFile(yield* runDir(name))}`);517518    if (options.json) {519      yield* printJson(AgentsResult, result);520    }521  });522523if (import.meta.main) {524  BunRuntime.runMain(525    Effect.gen(function* () {526      const args = yield* (yield* Stdio.Stdio).args;527528      return yield* main(args);529    }).pipe(Effect.provide(BunServices.layer))530  );531}