Skip to content
Myr

loop.ts

This file

Path

scripts/lib/swarm/loop.ts

484 lines · 13.7 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

1import { Brand } from "@repo/brand";2import type { AnswerView } from "@repo/protocol/domain/answer";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { ProjectName } from "@repo/protocol/ids";5import type { Refusal } from "@repo/protocol/refusal";6import { explain } from "@repo/protocol/render";7import {8  Array,9  Clock,10  Config,11  Console,12  Data,13  Duration,14  Effect,15  FileSystem,16  Option,17  Ref,18} from "effect";19import type { ChildProcessSpawner } from "effect/process";2021import { drivers, sessionDirOf } from "./harnesses/index.ts";22import { awaitSettledOutcome } from "./outcome.ts";23import type { AskStatus } from "./outcome.ts";24import { endsClaim } from "./plan.ts";25import type { Assignment } from "./plan.ts";26import type { AgentOutcome, AgentRun } from "./results.ts";27import type { Contributor } from "./roster.ts";28import { headlessView, Turn } from "./views/headless.ts";29import type { SwarmView } from "./views/headless.ts";30import { scrubbed, SwarmFailed } from "./workspace.ts";31import type { AgentWorkspace } from "./workspace.ts";3233export type RunAgent = (input: {34  readonly assignment: Assignment;35  readonly workspace: AgentWorkspace;36  readonly brief: string;37  readonly maxContinuations: 3;38  readonly timeoutMs: number;39  readonly project?: ProjectName;40  readonly view?: SwarmView;41}) => Effect.Effect<42  AgentRun,43  never,44  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem45>;4647export const startCommand = (input: {48  readonly contributor: Contributor;49  readonly brief: string;50  readonly dir: string;51}): readonly string[] => {52  const { adapter, handle, harness, model } = input.contributor;5354  return drivers[harness].start({55    adapter,56    brief: input.brief,57    model,58    sessionDir: sessionDirOf(input.dir),59    sessionKey: handle,60    workspace: {61      clone: `${input.dir}/clone`,62      dir: input.dir,63      env: {},64      redacted: [],65    },66  });67};6869/**70 * Nothing secret: the run's `SESSION_TOKENS`, cloud tokens and any parent71 * harness's session never reach a contributor's harness.72 */73const KEPT_FROM_SWARM = [74  "HOME",75  "USER",76  "LOGNAME",77  "SHELL",78  "TERM",79  "COLORTERM",80  "LANG",81  "LANGUAGE",82  "LC_ALL",83  "LC_CTYPE",84  "TZ",85  "TMPDIR",86  "XDG_CACHE_HOME",87  "XDG_DATA_HOME",88  "XDG_RUNTIME_DIR",89  "XDG_STATE_HOME",90  "HTTP_PROXY",91  "HTTPS_PROXY",92  "NO_PROXY",93  "http_proxy",94  "https_proxy",95  "no_proxy",96  "SSL_CERT_DIR",97  "SSL_CERT_FILE",98  "NODE_EXTRA_CA_CERTS",99] as const;100101const harnessEnv = (workspace: AgentWorkspace) =>102  Effect.gen(function* () {103    const kept = yield* Effect.forEach(KEPT_FROM_SWARM, (name) =>104      Config.option(Config.String(name)).pipe(105        Effect.map(Option.map((value) => [name, value] as const)),106        Effect.orElseSucceed(() => Option.none())107      )108    );109110    return {111      ...Object.fromEntries(Array.getSomes(kept)),112      ...workspace.env,113    };114  });115116export type Next = Data.TaggedEnum<{117  Resume: { readonly prompt: string; readonly nudge: boolean };118  Done: {119    readonly outcome: AgentOutcome;120    readonly landed: Option.Option<string>;121  };122}>;123124export const Next = Data.taggedEnum<Next>();125126export interface Progress {127  readonly attempts: number;128  readonly continuations: number;129  readonly nudged: boolean;130  readonly judged: readonly string[];131  readonly refusals: Readonly<Record<string, number>>;132  readonly landed: Option.Option<string>;133}134135const started: Progress = {136  attempts: 0,137  continuations: 0,138  judged: [],139  landed: Option.none(),140  nudged: false,141  refusals: {},142};143144export interface Step {145  readonly next: Next;146  readonly progress: Progress;147}148149const tally = (150  prior: Readonly<Record<string, number>>,151  refusals: readonly Refusal[]152) => {153  const counts = new Map(Object.entries(prior));154155  for (const { _tag } of refusals) {156    counts.set(_tag, (counts.get(_tag) ?? 0) + 1);157  }158159  return Object.fromEntries(counts);160};161162const short = (sha: string) => sha.slice(0, 7);163164// Retryable refusals that name nothing in the change to fix.165const platformSide: ReadonlySet<Refusal["_tag"]> = new Set([166  "Flake",167  "RepoBusy",168  "VerifierBlocked",169] as const satisfies readonly Refusal["_tag"][]);170171export const refusalPrompt = (input: {172  readonly answer: Pick<AnswerView, "ask" | "head">;173  readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;174  readonly project: string;175}) => {176  const status = `\`${Brand.cli} status --project ${input.project}\``;177178  const what = input.refusals.every(({ _tag }) => platformSide.has(_tag))179    ? [180        'This is not a fault in your change: the platform could not finish checking it. Change nothing; push the same work again with an empty commit (`git commit --allow-empty -m "Check again"`, then `git push`).',181        `Then run ${status} for the new verdict.`,182      ]183    : [184        `Next: ${Array.headNonEmpty(input.refusals).next}`,185        "",186        `Fix what the refusal names, commit, and push again; then run ${status} for the new verdict.`,187      ];188189  return [190    `Your answer to ${input.answer.ask} at ${short(input.answer.head)} was refused:`,191    "",192    ...explain(input.refusals),193    "",194    ...what,195  ].join("\n");196};197198export const nudgePrompt = (input: {199  readonly ask: string;200  readonly remote: string;201  readonly project: string;202  readonly since: Option.Option<string>;203}) =>204  [205    Option.match(input.since, {206      onNone: () =>207        `No answer of yours to ${input.ask} has reached the platform yet.`,208      onSome: (head) =>209        `No new answer of yours to ${input.ask} has reached the platform since ${short(head)}.`,210    }),211    `Commit your change and push it to ${input.remote} with \`git push\`. If git printed refusals in its \`remote:\` lines, fix what they name first, then push again.`,212    `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,213  ].join("\n");214215/**216 * An answer already judged is no new answer. Refusals of every new answer are217 * counted, since an agent may push again within one session.218 */219export const afterSettle = (input: {220  readonly status: AskStatus;221  readonly progress: Progress;222  readonly maxContinuations: number;223  readonly ask: string;224  readonly project: Option.Option<string>;225  /** With no new answer, a broken harness fails the run: a nudge cannot help. */226  readonly broke: Option.Option<string>;227}): Step => {228  const { maxContinuations, progress } = input;229230  const project = Option.getOrElse(231    Option.orElse(input.project, () =>232      Option.map(input.status.claim, (claim) => claim.project)233    ),234    () => "<project>"235  );236237  const canContinue = progress.continuations < maxContinuations;238239  const fresh = Option.filter(240    input.status.answer,241    ({ requestId }) => !progress.judged.includes(requestId)242  );243244  const done = (outcome: AgentOutcome, at: Progress = progress) => ({245    next: Next.Done({ landed: at.landed, outcome }),246    progress: at,247  });248249  if (Option.isNone(fresh)) {250    if (Option.isSome(input.broke)) {251      return done("failed");252    }253254    if (!progress.nudged && canContinue) {255      return {256        next: Next.Resume({257          nudge: true,258          prompt: nudgePrompt({259            ask: input.ask,260            project,261            remote: Option.match(input.status.claim, {262              onNone: () => "origin",263              onSome: ({ remote }) => remote,264            }),265            // Status's latest answer here is one already judged, if any.266            since: Option.map(input.status.answer, ({ head }) => head),267          }),268        }),269        progress: {270          ...progress,271          continuations: progress.continuations + 1,272          nudged: true,273        },274      };275    }276277    return done(progress.judged.length === 0 ? "noAnswer" : "refused");278  }279280  const answer = fresh.value;281282  const unjudged = input.status.answers.filter(283    ({ requestId }) => !progress.judged.includes(requestId)284  );285286  const judged = {287    ...progress,288    judged: [...progress.judged, ...unjudged.map(({ requestId }) => requestId)],289    refusals: tally(290      progress.refusals,291      unjudged.flatMap(({ outcome }) =>292        Outcome.guards.Refused(outcome) ? outcome.refusals : []293      )294    ),295  };296297  return Outcome.match(answer.outcome, {298    AwaitingDecision: () => done("waiting", judged),299    AwaitingFinish: () => done("waiting", judged),300    // `awaitSettledOutcome` reads past every `Checking` until the run's301    // timeout ends it, so an answer still checking here ran out of time.302    Checking: () => done("timedOut", judged),303    Landed: ({ sha }) =>304      done("landed", { ...judged, landed: Option.some(sha) }),305    Refused: ({ refusals }) => {306      if (refusals.some(({ _tag }) => endsClaim.has(_tag)) || !canContinue) {307        return done("refused", judged);308      }309310      return {311        next: Next.Resume({312          nudge: false,313          prompt: refusalPrompt({ answer, project, refusals }),314        }),315        progress: { ...judged, continuations: progress.continuations + 1 },316      };317    },318    WaitingOnParent: () => done("waiting", judged),319  });320};321322const tagsOf = ({ answer }: AskStatus) =>323  Option.match(answer, {324    onNone: () => "",325    onSome: ({ outcome }) =>326      Outcome.guards.Refused(outcome)327        ? outcome.refusals.map(({ _tag }) => _tag).join(", ")328        : "",329  });330331const tokens = (count: number) =>332  count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;333334export const runAgent: RunAgent = (input) =>335  Effect.gen(function* () {336    const { assignment, workspace } = input;337    const { adapter, handle, harness, model } = assignment.contributor;338    const driver = drivers[harness];339    const view = input.view ?? headlessView;340    const project = Option.fromUndefinedOr(input.project);341    const begun = yield* Clock.currentTimeMillis;342    const progress = yield* Ref.make(started);343344    const say = (line: string) =>345      Console.error(scrubbed(`${handle}: ${line}`, workspace));346347    const pass = (348      turn: Turn,349      env: Readonly<Record<string, string>>350    ): Effect.Effect<351      AgentOutcome,352      SwarmFailed,353      ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem354    > =>355      Effect.gen(function* () {356        const attempts = (yield* Ref.get(progress)).attempts + 1;357358        const ran = yield* view.attempt({359          contributor: assignment.contributor,360          env,361          file: `${workspace.dir}/attempt-${attempts}.jsonl`,362          onSession: Ref.update(progress, (now) => ({363            ...now,364            attempts: Math.max(now.attempts, attempts),365          })),366          turn,367          workspace,368        });369370        const { session } = ran.heard;371372        const ended = Option.match(ran.code, {373          onNone: () => "still running",374          onSome: (code) => `exit ${code}`,375        });376377        if (Option.isNone(session)) {378          return yield* new SwarmFailed({379            reason: `${harness} ended (${ended}) before it started a session${ran.stderr === "" ? "" : `: ${ran.stderr}`}`,380          });381        }382383        yield* say(384          `attempt ${attempts} ${ran.heard.settled ? "settled" : "ended"} (${Option.getOrElse(ran.heard.stopReason, () => ended)}), ${tokens(ran.heard.input)} tokens in, ${tokens(ran.heard.output)} out`385        );386387        const status = yield* awaitSettledOutcome({388          ask: assignment.ask,389          project,390          workspace,391        });392393        const broke = Option.orElse(ran.heard.failure, () =>394          Option.filter(ran.code, (code) => code !== 0).pipe(395            Option.map((code) =>396              ran.stderr === "" ? `exit ${code}` : `exit ${code}: ${ran.stderr}`397            )398          )399        );400401        const step = afterSettle({402          ask: assignment.ask,403          broke,404          maxContinuations: input.maxContinuations,405          progress: yield* Ref.get(progress),406          project,407          status,408        });409410        yield* Ref.set(progress, step.progress);411412        if (Next.$is("Done")(step.next)) {413          if (step.next.outcome === "failed") {414            yield* say(415              `${harness} failed: ${Option.getOrElse(broke, () => "no reason given")}`416            );417          }418419          return step.next.outcome;420        }421422        yield* say(423          `${step.next.nudge ? "no new answer, so a nudge" : `refused ${tagsOf(status)}, so the refusal`} goes back into the session (continuation ${step.progress.continuations} of ${input.maxContinuations})`424        );425426        return yield* pass(427          Turn.Resume({ prompt: step.next.prompt, session: session.value }),428          env429        );430      });431432    const loop = Effect.gen(function* () {433      const fs = yield* FileSystem.FileSystem;434435      yield* Effect.forEach(436        driver.files(workspace),437        ({ content, path }) => fs.writeFileString(path, content),438        { discard: true }439      ).pipe(440        Effect.mapError(441          ({ message }) =>442            new SwarmFailed({443              reason: `${harness}'s settings: ${message}`,444            })445        )446      );447448      return yield* pass(449        Turn.Start({ brief: input.brief }),450        yield* harnessEnv(workspace)451      );452    });453454    const outcome = yield* loop.pipe(455      Effect.timeoutOption(Duration.millis(input.timeoutMs)),456      Effect.map(Option.getOrElse((): AgentOutcome => "timedOut")),457      Effect.catchTag(458        "SwarmFailed",459        ({ reason }): Effect.Effect<AgentOutcome> =>460          Effect.as(say(reason), "failed")461      )462    );463464    const finished = yield* Clock.currentTimeMillis;465    const at = yield* Ref.get(progress);466467    yield* say(`${outcome} after ${at.attempts} attempts`);468469    return {470      adapter,471      ask: assignment.ask,472      attempts: at.attempts,473      durationMs: finished - begun,474      handle,475      harness,476      model,477      outcome,478      refusals: at.refusals,479      ...Option.match(at.landed, {480        onNone: () => ({}),481        onSome: (landed) => ({ landed }),482      }),483    };484  });