Skip to content
Myr

herdr.ts

This file

Path

scripts/lib/swarm/views/herdr.ts

732 lines · 19.7 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

1/**2 * Outcomes come only from `<cli> status --json`; pane text is read only to3 * answer a harness's startup questions. An agent in a pane outlives its run4 * until its herdr workspace is closed.5 */6import type { ProjectName } from "@repo/protocol/ids";7import {8  Config,9  Duration,10  Effect,11  FileSystem,12  Option,13  Ref,14  Result,15  Schedule,16  Schema,17} from "effect";18import type { Path, Scope } from "effect";19import type { ChildProcessSpawner } from "effect/process";2021import { repoRoot } from "../../../../infra/stages.ts";22import { drivers, sessionDirOf } from "../harnesses/index.ts";23import type { Harness } from "../results.ts";24import type { Contributor } from "../roster.ts";25import { run, scrubbed, shellQuoted, SwarmFailed } from "../workspace.ts";26import type { AgentWorkspace } from "../workspace.ts";27import { followCounter, lastHeld } from "./counter.ts";28import { nothingHeard, Turn } from "./headless.ts";29import type { Attempted, SwarmView } from "./headless.ts";3031export const COUNTER = "counter";3233export interface Split {34  readonly slot: string;35  readonly from: string;36  readonly direction: "right" | "down";37  readonly ratio: number;38}3940const ABOVE_COUNTER = 0.85;4142const share = (ratio: number) => Math.round(ratio * 1000) / 1000;4344export const herdrLayout = (handles: readonly string[]): readonly Split[] => {45  const [first] = handles;4647  if (first === undefined) {48    return [];49  }5051  const across =52    handles.length <= 3 ? handles.length : Math.ceil(handles.length / 2);5354  const rows = [handles.slice(0, across), handles.slice(across)].filter(55    (row) => row.length > 056  );5758  const counter: Split = {59    direction: "down",60    from: first,61    ratio: ABOVE_COUNTER,62    slot: COUNTER,63  };6465  const secondRow = rows.flatMap((row, at) => {66    const [head] = row;6768    return at === 0 || head === undefined69      ? []70      : [{ direction: "down", from: first, ratio: 0.5, slot: head } as const];71  });7273  const columns = rows.flatMap((row) =>74    row.slice(1).map((slot, at): Split => ({75      direction: "right",76      from: row[at] ?? first,77      ratio: share(1 / (row.length - at)),78      slot,79    }))80  );8182  return [counter, ...secondRow, ...columns];83};8485const START_TIMEOUT_MS = 120_000;8687export const herdrStart = (input: {88  readonly handle: string;89  readonly kind: string;90  readonly pane: string;91  readonly argv: readonly string[];92}): readonly string[] => [93  "agent",94  "start",95  input.handle,96  "--kind",97  input.kind,98  "--pane",99  input.pane,100  "--timeout",101  String(START_TIMEOUT_MS),102  "--",103  ...input.argv,104];105106// `--wait` alone also matches `idle`, which a turn can end in; `--until done --until blocked` would hang.107export const herdrPrompt = (input: {108  readonly handle: string;109  readonly text: string;110}): readonly string[] => [111  "agent",112  "prompt",113  input.handle,114  input.text,115  "--wait",116];117118const HEADLESS_ONLY = {119  amp: {120    switches: ["--stream-json", "--no-archive-after-execute"],121    valued: ["-x"],122  },123  "claude-code": { switches: ["-p", "--verbose"], valued: ["--output-format"] },124  // `run` is OpenCode's headless subcommand; its interface takes no `-m`.125  opencode: { switches: ["run"], valued: ["--format", "-m"] },126  pi: { switches: ["-p"], valued: ["--mode"] },127} as const satisfies Readonly<128  Record<129    Harness,130    { readonly switches: readonly string[]; readonly valued: readonly string[] }131  >132>;133134// Marks the brief in a driver's argv so it can be taken out.135const BRIEF = "\u0000brief";136137export interface Launch {138  readonly kind: string;139  readonly argv: readonly string[];140  readonly env: Readonly<Record<string, string>>;141}142143/**144 * Reuses the headless driver's start flags (less `HEADLESS_ONLY` and the145 * brief), so the settings that keep a session safe are the same.146 */147export const interactiveLaunch = (input: {148  readonly contributor: Contributor;149  readonly dir: string;150}): Launch => {151  const { adapter, handle, harness, model } = input.contributor;152153  const [kind = harness, ...flags] = drivers[harness].start({154    adapter,155    brief: BRIEF,156    model,157    sessionDir: sessionDirOf(input.dir),158    sessionKey: handle,159    workspace: {160      clone: `${input.dir}/clone`,161      dir: input.dir,162      env: {},163      redacted: [],164    },165  });166167  const { switches, valued } = HEADLESS_ONLY[harness];168169  const argv = flags.filter((flag, at) => {170    const before = flags[at - 1] ?? "";171172    return (173      flag !== BRIEF &&174      !switches.some((one) => one === flag) &&175      !valued.some((one) => one === flag || one === before)176    );177  });178179  return {180    argv,181    env:182      harness === "opencode"183        ? { OPENCODE_CONFIG_CONTENT: JSON.stringify({ model }) }184        : {},185    kind,186  };187};188189class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {190  code: Schema.String,191  said: Schema.String,192  verb: Schema.String,193}) {194  override get message() {195    return `herdr ${this.verb}: ${this.code}: ${this.said}`;196  }197}198199const isRefused = Schema.is(HerdrRefused);200201const decodeRefusal = Schema.decodeUnknownOption(202  Schema.fromJsonString(203    Schema.Struct({204      error: Schema.Struct({ code: Schema.String, message: Schema.String }),205    })206  )207);208209const herdr = (args: readonly string[]) =>210  Effect.flatMap(run({ args, command: "herdr", env: {} }), (ran) => {211    if (ran.code === 0) {212      return Effect.succeed(ran.stdout);213    }214215    const verb = args.slice(0, 2).join(" ");216217    return Effect.fail(218      Option.match(decodeRefusal(ran.stderr), {219        onNone: () =>220          new HerdrRefused({221            code: `exit ${ran.code}`,222            said: ran.stderr.trim().slice(0, 500),223            verb,224          }),225        onSome: ({ error }) =>226          new HerdrRefused({ code: error.code, said: error.message, verb }),227      })228    );229  });230231const orFailed = <A, R>(232  effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>233): Effect.Effect<A, SwarmFailed, R> =>234  effect.pipe(235    Effect.catchTag("HerdrRefused", ({ message }) =>236      Effect.fail(new SwarmFailed({ reason: message }))237    )238  );239240const answerOf =241  <A, I>(schema: Schema.Codec<A, I>, what: string) =>242  (printed: string) =>243    Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(244      Effect.mapError(245        () =>246          new SwarmFailed({247            reason: `herdr ${what} answered without its JSON: ${printed.trim().slice(0, 300)}`,248          })249      )250    );251252const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });253254const WorkspaceMade = Schema.Struct({255  result: Schema.Struct({256    root_pane: PaneId,257    workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),258  }),259});260261const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });262263const AgentSeen = Schema.Struct({264  result: Schema.Struct({265    agent: Schema.Struct({266      agent_status: Schema.String,267      interactive_ready: Schema.optionalKey(Schema.Boolean),268    }),269  }),270});271272interface StartupQuestion {273  readonly asks: string;274  readonly keys: readonly string[];275}276277/**278 * Claude Code trusts the clone (it is the swarm's own) and declines CLAUDE.md279 * files above it. Any other question is left for the person at the panes.280 */281const STARTUP_QUESTIONS = {282  amp: [],283  "claude-code": [284    { asks: "Yes, I trust this folder", keys: ["down", "enter"] },285    { asks: "Allow external CLAUDE.md file imports?", keys: ["enter"] },286  ],287  opencode: [],288  pi: [],289} as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;290291const STARTUP_WAIT = Duration.minutes(3);292293const readyIn = (printed: string) =>294  Effect.map(295    answerOf(AgentSeen, "agent get")(printed),296    ({ result: { agent } }) =>297      agent.interactive_ready === true &&298      (agent.agent_status === "idle" || agent.agent_status === "done")299  );300301const pastStartup = (input: {302  readonly handle: string;303  readonly harness: Harness;304  readonly pane: string;305}) =>306  Effect.gen(function* () {307    const answered = yield* Ref.make<readonly string[]>([]);308309    const look = Effect.gen(function* () {310      const seen = yield* herdr(["agent", "get", input.handle]);311312      if (yield* readyIn(seen)) {313        return true;314      }315316      const shown = yield* herdr([317        "agent",318        "read",319        input.handle,320        "--source",321        "detection",322      ]);323324      const done = yield* Ref.get(answered);325326      const question = STARTUP_QUESTIONS[input.harness].find(327        ({ asks }) => shown.includes(asks) && !done.includes(asks)328      );329330      if (question !== undefined) {331        yield* Ref.set(answered, [...done, question.asks]);332        yield* herdr(["agent", "send-keys", input.handle, ...question.keys]);333      }334335      return false;336    });337338    const ready = yield* look.pipe(339      Effect.repeat({340        schedule: Schedule.spaced(Duration.seconds(1)),341        until: (isReady: boolean) => isReady,342      }),343      Effect.timeoutOption(STARTUP_WAIT)344    );345346    yield* Effect.fromOption(ready).pipe(347      Effect.mapError(348        () =>349          new SwarmFailed({350            reason: `${input.harness} is still blocked at startup in herdr pane ${input.pane}: answer it there, or run --view headless`,351          })352      )353    );354  });355356const PANE_OWNS = ["TERM", "COLORTERM"];357358const HERDR_NAMES = [359  "HERDR_BIN_PATH",360  "HERDR_ENV",361  "HERDR_PANE_ID",362  "HERDR_SOCKET_PATH",363  "HERDR_TAB_ID",364  "HERDR_WORKSPACE_ID",365];366367/**368 * The env arrives through a pipe, so no token is ever in a file, an argv or369 * on screen; the shell skips rc files so no user setup sits in between.370 */371export const paneShell = (input: {372  readonly fifo: string;373  readonly clone: string;374}) =>375  [376    "#!/bin/sh",377    "# One swarm contributor's herdr pane: their harness's env from the swarm",378    "# through a pipe, then a shell in their clone for herdr to start it in.",379    `exec env -i ${[...PANE_OWNS, ...HERDR_NAMES].map((name) => `${name}="\${${name}-}"`).join(" ")} /bin/sh -c '`,380    "set -a",381    '. "$1"',382    "set +a",383    'cd "$2" || exit 1',384    `case "\${SHELL##*/}" in`,385    '  zsh) exec "$SHELL" -f ;;',386    '  bash) exec "$SHELL" --noprofile --norc ;;',387    `  *) exec "\${SHELL:-/bin/sh}" ;;`,388    `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,389    "",390  ].join("\n");391392const envLines = (env: Readonly<Record<string, string>>) =>393  Object.entries(env)394    .filter(([name]) => !PANE_OWNS.includes(name))395    .map(([name, value]) => `${name}=${shellQuoted(value)}\n`)396    .join("");397398const ENV_READ_WAIT = Duration.seconds(30);399400const BUSY_RETRIES = 10;401402const SCRIPT_MODE = 0o700;403404const startIn = (input: {405  readonly contributor: Contributor;406  readonly env: Readonly<Record<string, string>>;407  readonly pane: string;408  readonly workspace: AgentWorkspace;409  readonly log: (text: string) => Effect.Effect<void, SwarmFailed>;410}) =>411  Effect.gen(function* () {412    const fs = yield* FileSystem.FileSystem;413    const { contributor, pane, workspace } = input;414    const { handle, harness } = contributor;415    const launch = interactiveLaunch({ contributor, dir: workspace.dir });416    const fifo = `${workspace.dir}/pane-env`;417    const script = `${workspace.dir}/pane-shell`;418419    const written = (what: string) =>420      Effect.mapError(421        ({ message }: { readonly message: string }) =>422          new SwarmFailed({ reason: `${handle}'s ${what}: ${message}` })423      );424425    yield* fs.remove(fifo, { force: true }).pipe(written("pipe"));426427    const made = yield* run({428      args: ["-m", "600", fifo],429      command: "mkfifo",430      env: {},431    });432433    if (made.code !== 0) {434      return yield* new SwarmFailed({435        reason: `${handle}'s pipe: mkfifo exited ${made.code}: ${made.stderr.trim()}`,436      });437    }438439    yield* fs440      .writeFileString(script, paneShell({ clone: workspace.clone, fifo }), {441        mode: SCRIPT_MODE,442      })443      .pipe(444        Effect.andThen(fs.chmod(script, SCRIPT_MODE)),445        written("pane script")446      );447448    yield* orFailed(449      herdr(["pane", "run", pane, `exec ${shellQuoted(script)}`])450    );451452    // Opening the pipe waits for the pane's script to read it.453    yield* fs454      .writeFileString(fifo, envLines({ ...input.env, ...launch.env }))455      .pipe(456        written("env"),457        Effect.timeoutOrElse({458          duration: ENV_READ_WAIT,459          orElse: () =>460            Effect.fail(461              new SwarmFailed({462                reason: `${handle}'s herdr pane ${pane} didn't read its env: is it at a shell prompt?`,463              })464            ),465        }),466        Effect.ensuring(Effect.ignore(fs.remove(fifo, { force: true })))467      );468469    const started = yield* herdr(470      herdrStart({ argv: launch.argv, handle, kind: launch.kind, pane })471    ).pipe(472      // The pane's shell may still be starting.473      Effect.retry({474        schedule: Schedule.spaced(Duration.seconds(1)),475        times: BUSY_RETRIES,476        while: (error) => isRefused(error) && error.code === "agent_pane_busy",477      }),478      Effect.catchIf(479        (error): error is HerdrRefused =>480          isRefused(error) && error.code === "agent_not_ready",481        (error) =>482          Effect.as(483            pastStartup({ handle, harness, pane }),484            JSON.stringify({ startup: error.said })485          )486      ),487      orFailed488    );489490    return yield* input.log(started);491  });492493const promptHeard = (input: {494  readonly name: string;495  readonly pane: string;496  readonly harness: Harness;497  readonly answer: Result.Result<string, HerdrRefused>;498}): Effect.Effect<Attempted, SwarmFailed> =>499  Result.match(input.answer, {500    onFailure: (refused) =>501      Effect.succeed({502        code: Option.some(1),503        heard: {504          ...nothingHeard,505          failure: Option.some(refused.message),506          session: Option.some(input.name),507        },508        stderr: refused.message,509      }),510    onSuccess: (printed) =>511      Effect.map(512        answerOf(AgentSeen, "agent prompt")(printed),513        ({ result: { agent } }): Attempted => {514          const blocked = agent.agent_status === "blocked";515516          return {517            code: Option.some(0),518            heard: {519              ...nothingHeard,520              failure: blocked521                ? Option.some(522                    `${input.harness} is blocked on a question in herdr pane ${input.pane}`523                  )524                : Option.none(),525              session: Option.some(input.name),526              settled: !blocked,527              stopReason: Option.some(agent.agent_status),528            },529            stderr: "",530          };531        }532      ),533  });534535export const herdrView = (panes: ReadonlyMap<string, string>): SwarmView => ({536  attempt: ({ contributor, env, file, onSession, turn, workspace }) =>537    Effect.gen(function* () {538      const fs = yield* FileSystem.FileSystem;539      const { handle, harness } = contributor;540541      const pane = yield* Effect.fromNullishOr(panes.get(handle)).pipe(542        Effect.mapError(543          () => new SwarmFailed({ reason: `${handle} has no herdr pane` })544        )545      );546547      const logged = Effect.mapError(548        ({ message }: { readonly message: string }) =>549          new SwarmFailed({ reason: `${handle}'s attempt log: ${message}` })550      );551552      const log = (text: string) =>553        fs554          .writeFileString(file, `${scrubbed(text, workspace).trim()}\n`, {555            flag: "a",556          })557          .pipe(logged);558559      yield* fs.writeFileString(file, "").pipe(logged);560561      const name = yield* Turn.$match(turn, {562        Resume: ({ session }) => Effect.succeed(session),563        Start: () =>564          Effect.as(565            startIn({ contributor, env, log, pane, workspace }),566            handle567          ),568      });569570      yield* onSession;571572      const text = Turn.$match(turn, {573        Resume: ({ prompt }) => prompt,574        Start: ({ brief }) => brief,575      });576577      const answer = yield* herdr(herdrPrompt({ handle: name, text })).pipe(578        Effect.map(Result.succeed),579        Effect.catchIf(isRefused, (refused) =>580          Effect.succeed(Result.fail(refused))581        )582      );583584      yield* log(585        Result.match(answer, {586          onFailure: ({ message }) => message,587          onSuccess: (printed) => printed,588        })589      );590591      return yield* promptHeard({ answer, harness, name, pane });592    }),593});594595const titleOf = ({596  handle,597  harness,598}: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;599600// Refuses outside a herdr pane: herdr says not to drive a session from outside it.601export const openHerdrView = (input: {602  readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];603  readonly project: ProjectName;604  readonly origin: string;605  readonly runDir: string;606}): Effect.Effect<607  { readonly view: SwarmView; readonly workspace: string },608  SwarmFailed,609  | ChildProcessSpawner.ChildProcessSpawner610  | FileSystem.FileSystem611  | Path.Path612  | Scope.Scope613> =>614  Effect.gen(function* () {615    const fs = yield* FileSystem.FileSystem;616617    const inHerdr = yield* Config.all({618      env: Config.option(Config.String("HERDR_ENV")),619      socket: Config.option(Config.String("HERDR_SOCKET_PATH")),620    }).pipe(621      Effect.map(622        ({ env, socket }) => Option.contains(env, "1") || Option.isSome(socket)623      ),624      Effect.orElseSucceed(() => false)625    );626627    if (!inHerdr) {628      return yield* new SwarmFailed({629        reason:630          "--view herdr opens its panes in the herdr session it runs in: start the swarm from a herdr pane (herdr --session demo), or name the session's socket in HERDR_SOCKET_PATH",631      });632    }633634    const from = yield* lastHeld(input.origin, input.project);635    const root = (yield* repoRoot).replace(/\/$/u, "");636    const counterFile = `${input.runDir}/counter.log`;637    const handles = input.contributors.map(({ handle }) => handle);638639    yield* fs640      .makeDirectory(input.runDir, { recursive: true })641      .pipe(642        Effect.mapError(643          ({ message }) =>644            new SwarmFailed({ reason: `the run's folder: ${message}` })645        )646      );647648    const made = yield* herdr([649      "workspace",650      "create",651      "--cwd",652      root,653      "--label",654      `swarm ${input.project}`,655      "--focus",656    ]).pipe(657      orFailed,658      Effect.flatMap(answerOf(WorkspaceMade, "workspace create"))659    );660661    const first = handles[0] ?? COUNTER;662663    const panes = yield* Effect.reduce(664      herdrLayout(handles),665      () => new Map([[first, made.result.root_pane.pane_id]]),666      (known, split) =>667        herdr([668          "pane",669          "split",670          known.get(split.from) ?? made.result.root_pane.pane_id,671          "--direction",672          split.direction,673          "--ratio",674          String(split.ratio),675          "--cwd",676          root,677          "--no-focus",678        ]).pipe(679          orFailed,680          Effect.flatMap(answerOf(PaneMade, "pane split")),681          Effect.map(({ result }) =>682            new Map(known).set(split.slot, result.pane.pane_id)683          )684        )685    );686687    const titles = [688      ...input.contributors.map((one) => [one.handle, titleOf(one)] as const),689      [COUNTER, `counter · ${input.project}`] as const,690    ];691692    yield* Effect.forEach(693      titles.flatMap(([slot, title]) =>694        Option.toArray(695          Option.map(Option.fromUndefinedOr(panes.get(slot)), (pane) => ({696            pane,697            title,698          }))699        )700      ),701      ({ pane, title }) => orFailed(herdr(["pane", "rename", pane, title])),702      { discard: true }703    );704705    yield* Effect.forkScoped(706      followCounter({707        file: counterFile,708        from,709        origin: input.origin,710        project: input.project,711      }).pipe(Effect.ignore)712    );713714    yield* Effect.forEach(715      Option.toArray(Option.fromUndefinedOr(panes.get(COUNTER))),716      (pane) =>717        orFailed(718          herdr([719            "pane",720            "run",721            pane,722            `clear; tail -n +1 -F ${shellQuoted(counterFile)}`,723          ])724        ),725      { discard: true }726    );727728    return {729      view: herdrView(panes),730      workspace: made.result.workspace.workspace_id,731    };732  });