headless.ts
This file
Path
scripts/lib/swarm/views/headless.ts
189 lines · 5.3 KiB · TypeScript
Last changed by
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
History of this fileTake it
Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8
lines 1–91why, one step back1import {2 Data,3 Duration,4 Effect,5 FileSystem,6 Fiber,7 Option,8 Stream,9} from "effect";10import { ChildProcess, ChildProcessSpawner } from "effect/process";1112import { drivers, HarnessEvent, sessionDirOf } from "../harnesses/index.ts";13import type { HarnessDriver } from "../harnesses/index.ts";14import type { Contributor } from "../roster.ts";15import { scrubbed, SwarmFailed } from "../workspace.ts";16import type { AgentWorkspace } from "../workspace.ts";1718export type Turn = Data.TaggedEnum<{19 Start: { readonly brief: string };20 Resume: { readonly session: string; readonly prompt: string };21}>;2223export const Turn = Data.taggedEnum<Turn>();2425export interface Heard {26 readonly session: Option.Option<string>;27 readonly settled: boolean;28 readonly stopReason: Option.Option<string>;29 readonly failure: Option.Option<string>;30 readonly input: number;31 readonly output: number;32}3334export const nothingHeard: Heard = {35 failure: Option.none(),36 input: 0,37 output: 0,38 session: Option.none(),39 settled: false,40 stopReason: Option.none(),41};4243export interface Attempted {44 readonly code: Option.Option<number>;45 readonly heard: Heard;46 readonly stderr: string;47}4849export interface ViewAttempt {50 readonly contributor: Contributor;51 readonly workspace: AgentWorkspace;52 readonly env: Readonly<Record<string, string>>;53 readonly file: string;54 readonly turn: Turn;55 readonly onSession: Effect.Effect<void>;56}5758export interface SwarmView {59 readonly attempt: (60 input: ViewAttempt61 ) => Effect.Effect<62 Attempted,63 SwarmFailed,64 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem65 >;66}6768const hear = (heard: Heard, event: HarnessEvent): Heard =>69 HarnessEvent.$match(event, {70 Failed: ({ reason }) => ({ ...heard, failure: Option.some(reason) }),71 SessionStarted: ({ id }) => ({ ...heard, session: Option.some(id) }),72 Settled: ({ stopReason }) => ({73 ...heard,74 settled: true,75 stopReason: Option.orElse(stopReason, () => heard.stopReason),76 }),77 Usage: ({ input, output, stopReason }) => ({78 ...heard,79 failure: Option.none(),80 input: heard.input + input,81 output: heard.output + output,82 stopReason: Option.orElse(stopReason, () => heard.stopReason),83 }),84 });8586const EXIT_GRACE = Duration.seconds(10);8788const KILL_GRACE = Duration.seconds(5);8990const STDERR_TAIL = 2000;91Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 92why, one step back92// A settled harness gets `EXIT_GRACE` to exit; then it is killed with its process group.Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8
lines 93–189why, one step back93const attempt = (input: {94 readonly argv: readonly string[];95 readonly driver: HarnessDriver;96 readonly env: Readonly<Record<string, string>>;97 readonly file: string;98 readonly workspace: AgentWorkspace;99 readonly onSession: Effect.Effect<void>;100}) =>101 Effect.scoped(102 Effect.gen(function* () {103 const fs = yield* FileSystem.FileSystem;104 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;105 const [command = "", ...args] = input.argv;106 const scrub = (text: string) => scrubbed(text, input.workspace);107108 yield* fs.writeFileString(input.file, "");109110 const child = yield* spawner.spawn(111 ChildProcess.make(command, args, {112 cwd: input.workspace.clone,113 env: { ...input.env },114 extendEnv: false,115 forceKillAfter: KILL_GRACE,116 stdin: "ignore",117 })118 );119120 const stderr = yield* child.stderr.pipe(121 Stream.decodeText(),122 Stream.runFold(123 () => "",124 (tail, text) => `${tail}${text}`.slice(-STDERR_TAIL)125 ),126 Effect.forkScoped127 );128129 const heard = yield* child.stdout.pipe(130 Stream.decodeText(),131 Stream.splitLines,132 Stream.tap((line) =>133 fs.writeFileString(input.file, `${scrub(line)}\n`, { flag: "a" })134 ),135 Stream.flatMap((line) => Stream.fromIterable(input.driver.parse(line))),136 Stream.tap((event) =>137 HarnessEvent.$is("SessionStarted")(event)138 ? input.onSession139 : Effect.void140 ),141 Stream.takeUntil(HarnessEvent.$is("Settled")),142 Stream.runFold(() => nothingHeard, hear)143 );144145 const code = yield* child.exitCode.pipe(146 Effect.timeoutOption(EXIT_GRACE),147 Effect.map(Option.map(Number))148 );149150 // A harness still running after its grace keeps its stderr open:151 // its tail is then not waited for.152 const tail = yield* Fiber.join(stderr).pipe(153 Effect.timeoutOption(Duration.seconds(1)),154 Effect.map(Option.getOrElse(() => ""))155 );156157 return { code, heard, stderr: scrub(tail).trim() };158 })159 ).pipe(160 Effect.mapError(161 ({ message }) =>162 new SwarmFailed({163 reason: `${input.argv[0] ?? "the harness"} didn't run: ${message}`,164 })165 )166 );167168export const headlessView: SwarmView = {169 attempt: ({ contributor, env, file, onSession, turn, workspace }) => {170 const { adapter, handle, harness, model } = contributor;171 const driver = drivers[harness];172173 const argv = Turn.$match(turn, {174 Resume: ({ prompt, session }) =>175 driver.resume({ adapter, model, prompt, session, workspace }),176 Start: ({ brief }) =>177 driver.start({178 adapter,179 brief,180 model,181 sessionDir: sessionDirOf(workspace.dir),182 sessionKey: handle,183 workspace,184 }),185 });186187 return attempt({ argv, driver, env, file, onSession, workspace });188 },189};