diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index e59cc2b79f32..52bd099ddeef 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -52,6 +52,10 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import { + deriveWorkflowGroups, + projectedSubagentsToRuntime, +} from "../../../../packages/client-runtime/src/state/subagentRuntime.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import type { McpThreadInvocationScope } from "./McpInvocationContext.ts"; @@ -1004,6 +1008,106 @@ it.layer(layerTest)("t3_workflow_run", (it) => { }), ); + it.effect( + "puts a judge's grown agents in their own round's phase, which reads as not started until they launch", + () => + Effect.gen(function* () { + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("grow-phase"); + const { subagentId } = yield* runs.run(parent.scope, { + name: "grow-phase", + stages: [ + { + id: "loop", + repeat: { + stages: [ + { id: "draft", agents: [{ id: "poet", task: "Write." }] }, + { + id: "critique", + agents: [ + { + id: "critic", + task: "Judge {{draft}}.", + resultSchema: { type: "object", required: ["ok"] }, + }, + ], + }, + ], + judge: "critic", + until: { path: "ok", equals: true }, + max: 2, + templates: { probe: { task: "Probe {{input.angle}}." } }, + }, + }, + ], + }); + yield* parent.endTurn; + const [poet] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* settleChild(poet!, "Draft."); + const critic = (yield* childrenOf(parent.threadId, subagentId, 2)).find( + (child) => child.id !== poet!.id, + )!; + const addAgents = ["probe-1", "probe-2"].map((key) => ({ + key, + template: "probe", + input: { angle: key }, + })); + yield* settleChild( + critic, + `\`\`\`json\n${JSON.stringify({ ok: false, addAgents, rerun: ["critique"] })}\n\`\`\``, + ); + + // The row as it stands once both grown agents are recorded, before either launches. + const row = yield* (yield* parentEvents(parent.threadId)).pipe( + Stream.filter(({ payload }) => + (payload.workflow?.agents ?? []).some((agent) => agent.label === "probe-2"), + ), + Stream.runHead, + Effect.map((event) => Option.getOrThrow(event).payload), + ); + const titles = row.workflow!.phases.map((phase) => phase.title); + assert.deepEqual(titles, [ + "draft · round 1", + "critique · round 1", + "draft · round 2", + "critique · round 2", + ]); + const grown = row.workflow!.agents.filter((agent) => agent.label.startsWith("probe-")); + assert.deepEqual( + grown.map((agent) => [agent.label, titles[agent.phaseIndex!], agent.state]), + [ + ["probe-1", "draft · round 2", "queued"], + ["probe-2", "draft · round 2", "queued"], + ], + ); + const phaseStates = (subagent: OrchestrationV2Subagent) => + deriveWorkflowGroups(projectedSubagentsToRuntime([subagent]))[0]!.phases.map((phase) => [ + phase.title, + phase.state, + ]); + assert.deepEqual(phaseStates(row), [ + ["draft · round 1", "done"], + ["critique · round 1", "done"], + ["draft · round 2", "pending"], + ["critique · round 2", "pending"], + ]); + + const probes = (yield* childrenOf(parent.threadId, subagentId, 4)).filter((child) => + child.title?.startsWith("draft.probe-"), + ); + assert.deepEqual(probes.map((child) => child.title).toSorted(), [ + "draft.probe-1#2", + "draft.probe-2#2", + ]); + for (const child of probes) yield* settleChild(child, "Probed."); + const last = (yield* childrenOf(parent.threadId, subagentId, 5)).find( + (child) => child.title === "critique.critic#2", + )!; + yield* settleChild(last, '```json\n{"ok":true}\n```'); + assert.equal((yield* ended(parent.threadId, subagentId))?.status, "completed"); + }), + ); + it.effect("resumes after a restart without relaunching a child and still wakes once", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/mcp/WorkflowRuns.ts b/apps/server/src/mcp/WorkflowRuns.ts index 43466780b809..1b8ac8e59f3f 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -36,6 +36,7 @@ import { agentStages, decodeWorkflowSpec, initialSnapshot, + phaseAgents, resumeWorkflow, WorkflowAgentOutcome, type WorkflowPort, @@ -171,7 +172,12 @@ function toRow( const { launches, ...state } = snapshot; const phases = workflowPhases(spec, snapshot); const agents = phases.flatMap(({ stage, round }, phaseIndex) => - stage.agents.map((agent) => ({ stage: stage.id, agent: agent.id, round, phaseIndex })), + phaseAgents(spec, snapshot, stage, round).map((agent) => ({ + stage: stage.id, + agent, + round, + phaseIndex, + })), ); return { workflow: { diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 3a048b758496..34054f1ec123 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -33,6 +33,8 @@ interface FakeOptions { interface FakeTask { readonly key: string; + readonly stage: string; + readonly round: number; readonly reply: Reply; readonly finishAt: number; readonly cancelled: Deferred.Deferred; @@ -116,10 +118,10 @@ const makeFake = (options: FakeOptions) => { ) { violations.push(`${start.key} restarted after its task was recorded`); } - for (const launch of persisted.at(-1)?.snapshot.launches ?? []) { - const samePhase = launch.stage === start.stage && launch.round === start.round; - if (!samePhase && launch.outcome === null) { - violations.push(`${start.key} started while ${recordKey(launch)} was live`); + for (const task of tasks.values()) { + const samePhase = task.stage === start.stage && task.round === start.round; + if (!samePhase && task.settled === null) { + violations.push(`${start.key} started while ${task.key} was live`); } } const existing = tasks.get(`task:${start.key}`); @@ -128,6 +130,8 @@ const makeFake = (options: FakeOptions) => { const now = yield* Clock.currentTimeMillis; tasks.set(`task:${start.key}`, { key: start.key, + stage: start.stage, + round: start.round, reply, finishAt: now + ("afterMs" in reply ? (reply.afterMs ?? 0) : 0), cancelled: yield* Deferred.make(), @@ -633,6 +637,18 @@ it.effect("rejects bad references and judges before any start", () => ], }, { name: "fb", stages: [{ id: "a", agents: [one("{{feedback}}")] }] }, + { name: "reserved-input", stages: [{ id: "input", agents: [one("x")] }] }, + { + name: "template-forward", + stages: [ + { id: "loop", repeat: { ...repeat(2), templates: { t: { task: "{{polish}}" } } } }, + { id: "polish", agents: [one("x")] }, + ], + }, + { + name: "template-repeat", + stages: [{ id: "loop", repeat: { ...repeat(2), templates: { t: { task: "{{loop}}" } } } }], + }, { name: "dup-repeat", stages: [draft, { id: "draft", repeat: repeat(2) }] }, { name: "judge", stages: [draft, { id: "loop", repeat: { ...repeat(2), judge: "writer" } }] }, { @@ -663,3 +679,316 @@ it.effect("rejects bad references and judges before any start", () => } }), ); + +/** Draft, probe, then a critic who judges and may grow the next round from two templates. */ +const grow = (max: number, extra: Record = {}) => ({ + name: "grow", + stages: [ + { + id: "loop", + repeat: { + stages: [ + { id: "draft", agents: [{ id: "poet", task: "Write {{feedback}}." }] }, + { id: "probe", agents: [{ id: "reader", task: "Read {{draft}}." }] }, + { + id: "critique", + agents: [{ id: "critic", task: "Judge {{probe}}.", resultSchema: VERDICT }], + }, + ], + judge: "critic", + until: { path: "verdict", equals: "accept" }, + max, + templates: { + rewrite: { task: "Rewrite {{draft.poet}} for {{input.focus}}." }, + redteam: { task: "Attack {{draft}} on {{input.angle}}." }, + }, + ...extra, + }, + }, + { id: "polish", agents: [{ id: "editor", task: "Polish {{draft}}." }] }, + ], +}); +const rewrite = (key: string, focus: string) => ({ key, template: "rewrite", input: { focus } }); +const redteam = (key: string, angle: string) => ({ + key, + template: "redteam", + input: { angle }, + stage: "probe", +}); + +/** The critic's structured result by round, rejecting unless told otherwise; others echo. */ +const judged = + (byRound: ReadonlyArray>) => + (start: WorkflowAgentStart): WorkflowAgentOutcome => + start.agent.id === "critic" + ? ok("judged", { verdict: "reject", ...byRound[start.round - 1] }) + : ok(start.key); +const judging = + (byRound: ReadonlyArray>) => (start: WorkflowAgentStart) => ({ + outcome: judged(byRound)(start), + }); + +/** Round 1 grows both stages; round 2 repeats a key, adds one, reruns only probe; round 3 accepts. */ +const GROWN = [ + { addAgents: [rewrite("rw-1", "rhythm"), redteam("rt-1", "cliche")] }, + { addAgents: [rewrite("rw-1", "again"), redteam("rt-2", "meter")], rerun: ["probe"] }, + { verdict: "accept" }, +]; + +const roster = (result: WorkflowResult, round: number) => { + const loop = result.stages[0]; + if (loop === undefined || !("rounds" in loop)) return []; + return (loop.rounds[round - 1]?.stages ?? []).flatMap((stage) => + stage.agents.map((agent) => `${stage.id}.${agent.id}:${agent.status}`), + ); +}; + +it.effect( + "grows the next round from the judge's addAgents, deduplicated by key across the run", + () => + Effect.gen(function* () { + const fake = makeFake({ reply: judging(GROWN) }); + + const result = yield* runWorkflow(fake.port, grow(4)); + + expect(result.status).toBe("completed"); + expect(result.stages[0]).toMatchObject({ exit: "accepted" }); + expect(fake.startCalls).toEqual([ + "draft.poet#1", + "probe.reader#1", + "critique.critic#1", + "draft.poet#2", + "draft.rw-1#2", + "probe.reader#2", + "probe.rt-1#2", + "critique.critic#2", + "probe.reader#3", + "probe.rt-2#3", + "critique.critic#3", + "polish.editor#1", + ]); + expect(fake.rendered.get("probe.rt-1#2")).toBe( + 'Attack {"poet":"draft.poet#2","rw-1":"draft.rw-1#2"} on cliche.', + ); + expect(roster(result, 3)).toEqual([ + "draft.poet:skipped", + "probe.reader:completed", + "probe.rt-2:completed", + "critique.critic:completed", + ]); + // Grown rows are recorded with the judge's result, before the next round starts anything. + const grown = fake.persisted.find(({ snapshot }) => + snapshot.launches.some((l) => recordKey(l) === "probe.rt-1#2"), + )!.snapshot; + expect( + grown.launches.filter((l) => l.round === 2).map((l) => [recordKey(l), l.taskId]), + ).toEqual([ + ["draft.rw-1#2", null], + ["probe.rt-1#2", null], + ]); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("exits after K consecutive dry votes, never on an invalid or missing judge result", () => + Effect.gen(function* () { + const dry = makeFake({ reply: judging([{ addAgents: [rewrite("rw-1", "x")] }]) }); + const dried = yield* runWorkflow(dry.port, grow(4, { dry: 2 })); + expect(dried.status).toBe("completed"); + expect(dried.stages[0]).toMatchObject({ exit: "dry" }); + expect(dry.created.filter((key) => key.startsWith("critique."))).toEqual([ + "critique.critic#1", + "critique.critic#2", + "critique.critic#3", + ]); + + // A rerun request is unresolved work, so those rounds never vote dry. + const busy = makeFake({ reply: judging([{ rerun: ["draft"] }, { rerun: ["draft"] }]) }); + expect((yield* runWorkflow(busy.port, grow(2, { dry: 1 }))).status).toBe("failed"); + + for (const bad of [ + { addAgents: [{ key: "x", template: "nope" }] }, + { addAgents: [{ key: "x", template: "rewrite", stage: "polish" }] }, + { rerun: ["polish"] }, + ]) { + const invalid = makeFake({ reply: judging([bad]) }); + expect((yield* runWorkflow(invalid.port, grow(3, { dry: 1 }))).status).toBe("failed"); + expect(invalid.created).not.toContain("draft.poet#2"); + } + const missing = makeFake({ reply: (start) => ({ outcome: ok(start.key) }) }); + expect((yield* runWorkflow(missing.port, grow(3, { dry: 1 }))).status).toBe("failed"); + expect(missing.created).not.toContain("draft.poet#2"); + }), +); + +it.effect("an accepting judge whose growth is invalid fails the run instead of passing", () => + Effect.gen(function* () { + for (const bad of [ + { verdict: "accept", rerun: ["polish"] }, + { verdict: "accept", addAgents: [{ key: "x", template: "nope" }] }, + { verdict: "accept", addAgents: "bad" }, + ]) { + const fake = makeFake({ reply: judging([bad]) }); + const result = yield* runWorkflow(fake.port, grow(3, { dry: 1 })); + expect({ bad, status: result.status }).toEqual({ bad, status: "failed" }); + expect(result.stages[0]).toMatchObject({ exit: null }); + expect(fake.created).not.toContain("polish.editor#1"); + } + for (const raw of [null, "bad", []]) { + const fake = makeFake({ + reply: (start) => ({ + outcome: start.agent.id === "critic" ? ok("judged", raw) : ok(start.key), + }), + }); + const result = yield* runWorkflow(fake.port, grow(3, { dry: 1 })); + expect({ raw, status: result.status }).toEqual({ raw, status: "failed" }); + } + }), +); + +it.effect("deduplicates grown keys across the whole run, not just the current repeat", () => + Effect.gen(function* () { + const second = { + id: "again", + repeat: { + stages: [ + { id: "redraft", agents: [{ id: "poet2", task: "Write." }] }, + { id: "recheck", agents: [{ id: "critic2", task: "Judge.", resultSchema: VERDICT }] }, + ], + judge: "critic2", + until: { path: "verdict", equals: "accept" }, + max: 2, + templates: { rewrite: { task: "Rewrite for {{input.focus}}." } }, + }, + }; + const spec = { + name: "two-loops", + stages: [{ id: "intro", agents: [{ id: "seed", task: "Seed." }] }, grow(2).stages[0], second], + }; + const judge = (start: WorkflowAgentStart, addAgents: ReadonlyArray) => + ok("judged", start.round === 1 ? { verdict: "reject", addAgents } : { verdict: "accept" }); + const fake = makeFake({ + reply: (start) => ({ + outcome: + start.agent.id === "critic" + ? judge(start, [rewrite("seed", "x"), rewrite("poet2", "w"), rewrite("gap", "y")]) + : start.agent.id === "critic2" + ? judge(start, [rewrite("gap", "z")]) + : ok(start.key), + }), + }); + + const result = yield* runWorkflow(fake.port, spec); + + expect(result.status).toBe("completed"); + // A static agent of a later repeat counts as seen before it ever runs. + expect(fake.created).not.toContain("draft.poet2#2"); + expect(fake.created.filter((key) => /\.(seed|gap)#/.test(key))).toEqual([ + "intro.seed#1", + "draft.gap#2", + ]); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("waits for grown agents before starting the next stage or judge", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: (start) => ({ + afterMs: start.agent.id === "rw-1" ? 10_000 : 1_000, + outcome: judged(GROWN)(start), + }), + }); + + const fiber = yield* Effect.forkChild(runWorkflow(fake.port, grow(4))); + yield* TestClock.adjust("1 minute"); + const result = yield* Fiber.join(fiber); + + expect(result.status).toBe("completed"); + expect(fake.startCalls.indexOf("probe.reader#2")).toBeGreaterThan( + fake.startCalls.indexOf("draft.rw-1#2"), + ); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("resumes a grown run without launching an instance twice", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: judging(GROWN), + crash: (snapshot) => + snapshot.launches.some((l) => recordKey(l) === "draft.rw-1#2" && l.taskId !== null) + ? "instead" + : undefined, + }); + + const result = yield* runOnce(fake, grow(4)); + + expect(result.status).toBe("completed"); + expect(fake.startCalls.filter((key) => key === "draft.rw-1#2")).toHaveLength(2); + expect(fake.created.filter((key) => key === "draft.rw-1#2")).toHaveLength(1); + expect(new Set(fake.created).size).toBe(fake.created.length); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("a stop after growth never starts a grown instance, across restart", () => + Effect.gen(function* () { + const spec = yield* decodeWorkflowSpec(grow(4)); + const fake = makeFake({ + reply: judging(GROWN), + crash: (snapshot) => + snapshot.launches.some((l) => recordKey(l) === "draft.rw-1#2") ? "after" : undefined, + }); + expect(Exit.isFailure(yield* Effect.exit(runWorkflow(fake.port, grow(4))))).toBe(true); + + const result = yield* resumeWorkflow(fake.port, spec, { ...fake.last()!, stop: true }); + + expect(result.status).toBe("cancelled"); + expect(fake.startCalls.filter((key) => key.endsWith("#2"))).toEqual([]); + expect( + fake + .last()! + .launches.filter((l) => l.round === 2) + .map((l) => [recordKey(l), l.outcome?.status]), + ).toEqual([["draft.rw-1#2", "cancelled"]]); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("never grows a round beyond max", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: (start) => ({ + outcome: judged([1, 2, 3].map((n) => ({ addAgents: [rewrite(`rw-${n}`, "x")] })))(start), + }), + }); + + const result = yield* runWorkflow(fake.port, grow(2)); + + expect(result.status).toBe("failed"); + expect( + fake.persisted.every(({ snapshot }) => snapshot.launches.every((l) => l.round <= 2)), + ).toBe(true); + expect(fake.created.filter((key) => key.endsWith("#3"))).toEqual([]); + }), +); + +it.effect("a run that grows survives a crash at, and instead of, every persist", () => + Effect.gen(function* () { + const check = (fake: Fake, result: WorkflowResult) => { + expect(result.status).toBe("completed"); + expect(fake.violations).toEqual([]); + expect(new Set(fake.created).size).toBe(fake.created.length); + for (const { snapshot } of fake.persisted) { + expect(decodeSnapshot(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot); + } + }; + yield* crashSweep(grow(4), judging(GROWN), check); + yield* crashSweep( + grow(4, { dry: 2 }), + judging([{ addAgents: [rewrite("rw-1", "x"), redteam("rt-1", "y")] }]), + check, + ); + }), +); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 6c359d838e6f..b010633d1caa 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -27,6 +27,8 @@ export type WorkflowAgent = typeof WorkflowAgent.Type; const AgentStage = Schema.Struct({ id: WorkflowId, agents: Schema.NonEmptyArray(WorkflowAgent) }); type AgentStage = typeof AgentStage.Type; +const RoundCount = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })); + const RepeatStage = Schema.Struct({ id: WorkflowId, repeat: Schema.Struct({ @@ -36,12 +38,39 @@ const RepeatStage = Schema.Struct({ path: TrimmedNonEmptyString, equals: Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), }), - max: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), + max: RoundCount, onExhausted: Schema.optional(Schema.Literals(["fail", "pass"])), + dry: Schema.optional(RoundCount), + templates: Schema.optional( + Schema.Record( + Schema.String, + Schema.Struct({ + task: WorkflowAgent.fields.task, + target: WorkflowAgent.fields.target, + resultSchema: WorkflowAgent.fields.resultSchema, + }), + ), + ), }), }); type RepeatStage = typeof RepeatStage.Type; +/** What a judge's structured result may ask of the next round, beyond `until`. */ +const Growth = Schema.Struct({ + addAgents: Schema.optional( + Schema.Array( + Schema.Struct({ + key: WorkflowId, + template: Schema.String, + input: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + stage: Schema.optional(Schema.String), + }), + ), + ), + rerun: Schema.optional(Schema.Array(Schema.String)), +}); +const decodeGrowth = Schema.decodeUnknownOption(Growth); + export const WorkflowSpec = Schema.Struct({ name: TrimmedNonEmptyString, stages: Schema.NonEmptyArray(Schema.Union([AgentStage, RepeatStage])), @@ -81,7 +110,7 @@ export const WorkflowSnapshot = Schema.Struct({ exits: Schema.Array( Schema.Struct({ stage: WorkflowId, - reason: Schema.Literals(["accepted", "exhausted"]), + reason: Schema.Literals(["accepted", "exhausted", "dry"]), round: Schema.Int, }), ), @@ -123,7 +152,7 @@ export type WorkflowResult = { | StageResult | { readonly id: string; - readonly exit: "accepted" | "exhausted" | null; + readonly exit: WorkflowSnapshot["exits"][number]["reason"] | null; readonly rounds: ReadonlyArray<{ readonly round: number; readonly stages: ReadonlyArray; @@ -145,11 +174,18 @@ const invalid = (message: string) => function referenceError(spec: WorkflowSpec): string | null { const ids = new Set(); const repeats = new Set(); - const order: Array<{ stage: AgentStage; repeat: RepeatStage | null }> = []; + const order: Array<{ + stage: { + readonly id: string; + readonly agents: ReadonlyArray>; + }; + repeat: RepeatStage | null; + }> = []; for (const stage of spec.stages) { const inner = "agents" in stage ? [stage] : stage.repeat.stages; for (const id of [stage.id, ...("agents" in stage ? [] : inner.map((s) => s.id))]) { - if (id === "feedback") return `"feedback" is reserved and cannot name a stage.`; + if (id === "feedback" || id === "input") + return `"${id}" is reserved and cannot name a stage.`; if (ids.has(id)) return `Duplicate stage id "${id}".`; ids.add(id); } @@ -164,6 +200,14 @@ function referenceError(spec: WorkflowSpec): string | null { } } for (const s of inner) order.push({ stage: s, repeat: "agents" in stage ? null : stage }); + // Templates check as if after the repeat's last stage: a grown agent may join any of them. + if (!("agents" in stage)) { + const agents = Object.entries(stage.repeat.templates ?? {}).map(([id, { task }]) => ({ + id, + task, + })); + order.push({ stage: { id: stage.id, agents }, repeat: stage }); + } } const index = new Map(order.map(({ stage }, i) => [stage.id, i])); for (const [position, { stage, repeat }] of order.entries()) { @@ -211,6 +255,38 @@ const asText = (value: unknown) => (typeof value === "string" ? value : JSON.str export const agentStages = (spec: WorkflowSpec) => spec.stages.flatMap((stage) => ("agents" in stage ? [stage] : stage.repeat.stages)); +const judgedIn = (state: WorkflowSnapshot, stage: RepeatStage, round: number) => + findLaunch(state, stage.repeat.stages.at(-1)?.id ?? "", round, stage.repeat.judge)?.outcome + ?.structuredResult; + +/** The judge's requests for the next round; null when it names a template or stage not in the repeat. */ +function growthOf(stage: RepeatStage, value: unknown) { + const growth = Option.getOrNull(decodeGrowth(value)); + if (growth === null) return null; + const { stages, templates = {} } = stage.repeat; + const ids = stages.map((s) => s.id); + const adds = (growth.addAgents ?? []).map((add) => ({ + ...add, + stage: add.stage ?? stages[0].id, + })); + const known = + adds.every((add) => ids.includes(add.stage) && Object.hasOwn(templates, add.template)) && + (growth.rerun ?? []).every((id) => ids.includes(id)); + return known ? { adds, rerun: growth.rerun ?? [] } : null; +} + +const isGrown = (stage: RepeatStage, launch: WorkflowLaunch) => + stage.repeat.stages.some( + (s) => s.id === launch.stage && !s.agents.some((agent) => agent.id === launch.agent), + ); + +/** Round 1 and the judge's stage always run; later rounds run what the last judge named, or all. */ +function runsAgain(stage: RepeatStage, state: WorkflowSnapshot, phaseId: string, round: number) { + if (round === 1 || phaseId === stage.repeat.stages.at(-1)?.id) return true; + const rerun = growthOf(stage, judgedIn(state, stage, round - 1))?.rerun ?? []; + return rerun.length === 0 || rerun.includes(phaseId); +} + /** Every stage the run shows, in order: a repeat's stages once per round it reached, round 1 up front. */ export function workflowPhases( spec: WorkflowSpec, @@ -232,14 +308,72 @@ export function workflowPhases( }); } -function renderTask(spec: WorkflowSpec, state: WorkflowSnapshot, template: string): string { +/** A phase's agents: its spec agents unless the last judge left the stage out, then those grown into it. */ +export function phaseAgents( + spec: WorkflowSpec, + state: WorkflowSnapshot, + stage: AgentStage, + round: number, +): ReadonlyArray { + const loop = spec.stages.find( + (s): s is RepeatStage => + !("agents" in s) && s.repeat.stages.some((inner) => inner.id === stage.id), + ); + if (loop === undefined) return stage.agents.map((agent) => agent.id); + const grown = state.launches.filter( + (l) => l.stage === stage.id && l.round === round && isGrown(loop, l), + ); + return [ + ...(runsAgain(loop, state, stage.id, round) ? stage.agents.map((agent) => agent.id) : []), + ...grown.map((l) => l.agent), + ]; +} + +/** The agents the last judge grew into `round`; keys are unique across the run, so seen keys are + * every spec agent and every launch outside this round's grown batch. */ +function grownFor(spec: WorkflowSpec, stage: RepeatStage, state: WorkflowSnapshot, round: number) { + const growth = growthOf(stage, judgedIn(state, stage, round - 1)); + const batch = state.launches.filter((l) => l.round === round && isGrown(stage, l)); + const seen = new Set([ + ...agentStages(spec).flatMap((s) => s.agents.map((agent) => agent.id)), + ...state.launches.filter((l) => !batch.includes(l)).map((l) => l.agent), + ]); + return (growth?.adds ?? []).filter(({ key }) => { + const fresh = !seen.has(key); + seen.add(key); + return fresh; + }); +} + +/** Consecutive dry votes ending at this round: rounds that grew nothing and asked for no rerun. */ +function dryStreak( + spec: WorkflowSpec, + stage: RepeatStage, + state: WorkflowSnapshot, + dryNow: boolean, +) { + const wasDry = (round: number) => + grownFor(spec, stage, state, round + 1).length === 0 && + !growthOf(stage, judgedIn(state, stage, round))?.rerun.length; + let streak = dryNow ? 1 : 0; + while (streak > 0 && streak < state.round && wasDry(state.round - streak)) streak += 1; + return streak; +} + +function renderTask( + spec: WorkflowSpec, + state: WorkflowSnapshot, + template: string, + input?: Readonly>, +): string { return template.replace(REFERENCE, (match, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { const stage = spec.stages[state.cursor]; if (stage === undefined || "agents" in stage) return match; - const judges = stage.repeat.stages.at(-1)?.id ?? ""; - const judge = findLaunch(state, judges, state.round - 1, stage.repeat.judge); - return JSON.stringify(judge?.outcome?.structuredResult ?? null); + return JSON.stringify(judgedIn(state, stage, state.round - 1) ?? null); + } + if (stageRef === "input" && input !== undefined) { + return agentRef === undefined ? JSON.stringify(input) : asText(input[agentRef] ?? null); } if (!agentStages(spec).some((stage) => stage.id === stageRef)) return match; const latest = new Map(); @@ -265,6 +399,7 @@ function accepts(until: RepeatStage["repeat"]["until"], value: unknown): boolean type Step = | { readonly _tag: "finish"; readonly status: typeof WorkflowRunStatus.Type } | { readonly _tag: "launch"; readonly stage: string; readonly agent: WorkflowAgent } + | { readonly _tag: "start" | "record"; readonly launch: WorkflowLaunch } | { readonly _tag: "advance"; readonly state: WorkflowSnapshot } | { readonly _tag: "wait" }; @@ -280,34 +415,83 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step } const stage = spec.stages[state.cursor]; if (stage === undefined) return finish("completed"); + const loop = "agents" in stage ? null : stage; const phase = "agents" in stage ? stage : stage.repeat.stages[state.phase]; if (phase === undefined) return finish("failed"); - const launches = phase.agents.map((agent) => ({ - agent, - launch: findLaunch(state, phase.id, state.round, agent.id), - })); - const unlaunched = launches.find(({ launch }) => launch === undefined); - if (unlaunched !== undefined) return { _tag: "launch", stage: phase.id, agent: unlaunched.agent }; - if (launches.some(({ launch }) => launch?.outcome === null)) return { _tag: "wait" }; + if (loop !== null && state.round > 1) { + // One row per update keeps each within the wire budget; all land before the round starts. + const recorded = state.launches.filter((l) => l.round === state.round && isGrown(loop, l)); + const add = grownFor(spec, loop, state, state.round).find( + ({ key }) => !recorded.some((l) => l.agent === key), + ); + if (add !== undefined) { + return { + _tag: "record", + launch: { + stage: add.stage, + round: state.round, + agent: add.key, + taskId: null, + cancelRequested: false, + outcome: null, + }, + }; + } + } + if (loop === null || runsAgain(loop, state, phase.id, state.round)) { + const unlaunched = phase.agents.find( + (agent) => findLaunch(state, phase.id, state.round, agent.id) === undefined, + ); + if (unlaunched !== undefined) return { _tag: "launch", stage: phase.id, agent: unlaunched }; + } + // Grown agents, and launches a crash cut off before their task id was recorded. + const current = state.launches.filter((l) => l.stage === phase.id && l.round === state.round); + const intent = current.find((l) => l.taskId === null && l.outcome === null); + if (intent !== undefined) return { _tag: "start", launch: intent }; + if (current.some((l) => l.outcome === null)) return { _tag: "wait" }; const next = { ...state, cursor: state.cursor + 1, round: 1, phase: 0 }; - if ("agents" in stage) return advance(next); - const { repeat } = stage; + if (loop === null) return advance(next); + const { repeat } = loop; if (state.phase < repeat.stages.length - 1) return advance({ ...state, phase: state.phase + 1 }); - const exit = (reason: "accepted" | "exhausted") => ({ + const exit = (reason: WorkflowSnapshot["exits"][number]["reason"]) => ({ ...next, - exits: [...state.exits, { stage: stage.id, reason, round: state.round }], + exits: [...state.exits, { stage: loop.id, reason, round: state.round }], }); - const judge = findLaunch(state, phase.id, state.round, repeat.judge); - if (accepts(repeat.until, judge?.outcome?.structuredResult)) return advance(exit("accepted")); - if (state.round < repeat.max) return advance({ ...state, round: state.round + 1, phase: 0 }); - return repeat.onExhausted === "pass" ? advance(exit("exhausted")) : finish("failed"); + const value = judgedIn(state, loop, state.round); + // A missing or malformed judge result fails the run; it never accepts or counts as dry. + const growth = growthOf(loop, value); + if (growth === null) return finish("failed"); + if (accepts(repeat.until, value)) return advance(exit("accepted")); + const grown = grownFor(spec, loop, state, state.round + 1); + const dryNow = grown.length === 0 && growth.rerun.length === 0; + if (repeat.dry !== undefined && dryStreak(spec, loop, state, dryNow) >= repeat.dry) { + return advance(exit("dry")); + } + if (state.round === repeat.max) { + return repeat.onExhausted === "pass" ? advance(exit("exhausted")) : finish("failed"); + } + return advance({ ...state, round: state.round + 1, phase: 0 }); } -const findAgent = (spec: WorkflowSpec, launch: WorkflowLaunch) => - agentStages(spec) - .find((stage) => stage.id === launch.stage) - ?.agents.find((agent) => agent.id === launch.agent); +/** A spec agent, or a grown one built from its template and the input its judge gave it. */ +function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: WorkflowLaunch) { + for (const stage of spec.stages) { + const phase = ("agents" in stage ? [stage] : stage.repeat.stages).find( + (s) => s.id === launch.stage, + ); + if (phase === undefined) continue; + const agent = phase.agents.find((a) => a.id === launch.agent); + if (agent !== undefined || "agents" in stage) return agent && { agent }; + const add = growthOf(stage, judgedIn(state, stage, launch.round - 1))?.adds.find( + (a) => a.key === launch.agent, + ); + const template = add && stage.repeat.templates?.[add.template]; + if (add === undefined || template === undefined) return undefined; + return { agent: { ...template, id: add.key }, input: add.input ?? {} }; + } + return undefined; +} type WorkflowEvent = | { readonly _tag: "settled"; readonly key: string; readonly outcome: WorkflowAgentOutcome } @@ -354,11 +538,12 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( ); const startTask = Effect.fn("WorkflowRun.startAgent")(function* (launch: WorkflowLaunch) { const key = keyOf(launch); - const agent = findAgent(spec, launch); - if (agent === undefined) { + const found = findAgent(spec, state, launch); + if (found === undefined) { return yield* update(key, { outcome: { status: "failed", result: "Not in the spec." } }); } - const task = renderTask(spec, state, agent.task); + const { agent } = found; + const task = renderTask(spec, state, agent.task, found.input); const started = yield* port .start({ key, stage: launch.stage, round: launch.round, agent, task }) .pipe(Effect.result); @@ -378,9 +563,8 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( ); } for (const launch of state.launches) { - if (launch.outcome !== null) continue; - if (launch.taskId === null) yield* startTask(launch); - else yield* watch(keyOf(launch), launch.taskId); + if (launch.outcome === null && launch.taskId !== null) + yield* watch(keyOf(launch), launch.taskId); } const apply = (event: WorkflowEvent) => { @@ -423,6 +607,12 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( yield* startTask(launch); break; } + case "start": + yield* startTask(step.launch); + break; + case "record": + yield* save({ ...state, launches: [...state.launches, step.launch] }); + break; case "advance": state = step.state; break; @@ -445,24 +635,34 @@ export const initialSnapshot = (spec: WorkflowSpec, now: number): WorkflowSnapsh }); export function workflowResult(spec: WorkflowSpec, state: WorkflowSnapshot): WorkflowResult { + const agentResult = (id: string, launch: WorkflowLaunch | undefined): AgentResult => { + if (launch === undefined) return { id, status: "skipped", taskId: null, result: null }; + const { outcome } = launch; + return { + id, + status: outcome?.status ?? "running", + taskId: launch.taskId, + result: outcome?.result ?? null, + ...(outcome?.structuredResult === undefined + ? {} + : { structuredResult: outcome.structuredResult }), + }; + }; const agents = (stage: AgentStage, round: number): StageResult => ({ id: stage.id, - agents: stage.agents.map((agent): AgentResult => { - const launch = findLaunch(state, stage.id, round, agent.id); - if (launch === undefined) { - return { id: agent.id, status: "skipped", taskId: null, result: null }; - } - const { outcome } = launch; - return { - id: agent.id, - status: outcome?.status ?? "running", - taskId: launch.taskId, - result: outcome?.result ?? null, - ...(outcome?.structuredResult === undefined - ? {} - : { structuredResult: outcome.structuredResult }), - }; - }), + agents: [ + ...stage.agents.map((agent) => + agentResult(agent.id, findLaunch(state, stage.id, round, agent.id)), + ), + ...state.launches + .filter( + (l) => + l.stage === stage.id && + l.round === round && + !stage.agents.some((agent) => agent.id === l.agent), + ) + .map((l) => agentResult(l.agent, l)), + ], }); return { name: spec.name, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index f81931ee2055..f16522f8390b 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -868,7 +868,7 @@ export const OrchestrationV2WorkflowRunState = Schema.Struct({ exits: Schema.Array( Schema.Struct({ stage: Schema.String, - reason: Schema.Literals(["accepted", "exhausted"]), + reason: Schema.Literals(["accepted", "exhausted", "dry"]), round: NonNegativeInt, }), ),