diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index 44f12e289d45..b283815f5209 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -1005,6 +1005,33 @@ it.layer(layerTest)("t3_workflow_run", (it) => { assert.equal((yield* ended(other.threadId, stopped.subagentId))?.status, "cancelled"); const cancelled = yield* largestUpdate(other.threadId, stopped.subagentId); assert.isAtMost(cancelled.largest, 2048); + + // A judge naming a huge template fails the run with the longest error, in each encoding. + for (const char of ["X", '"', "界"]) { + const failing = yield* seedParent(`bytes-error-${char.codePointAt(0)}`); + const failed = yield* runs.run(failing.scope, wide); + yield* failing.endTurn; + settled.clear(); + const settleFailing = (count: number, text: string) => + Effect.gen(function* () { + const children = yield* childrenOf( + failing.threadId, + failed.subagentId, + settled.size + count, + ); + for (const child of children.filter((c) => !settled.has(c.id))) { + settled.add(child.id); + yield* settleChild(child, text); + } + }); + yield* settleFailing(20, "Part done."); + yield* settleFailing(1, "Revised."); + const judged = { ok: false, addAgents: [{ template: char.repeat(1_000) }] }; + yield* settleFailing(1, `\`\`\`json\n${JSON.stringify(judged)}\n\`\`\``); + assert.equal((yield* ended(failing.threadId, failed.subagentId))?.status, "failed"); + const errored = yield* largestUpdate(failing.threadId, failed.subagentId); + assert.isAtMost(errored.largest, 2048, `template of ${char}`); + } }), ); @@ -1201,6 +1228,85 @@ it.layer(layerTest)("t3_workflow_run", (it) => { }), ); + it.effect("says why a judge's invalid growth failed the run: result, status, wake and row", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const runs = yield* workflowRunsIn(yield* Effect.scope); + const parent = yield* seedParent("growth-error"); + const { subagentId } = yield* runs.run(parent.scope, { + name: "grow", + 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: { rewriter: { task: "Rewrite {{draft}}." } }, + }, + }, + ], + }); + yield* parent.endTurn; + const [poet] = yield* childrenOf(parent.threadId, subagentId, 1); + yield* settleChild(poet!, "Draft. ".repeat(3_000)); + const critic = (yield* childrenOf(parent.threadId, subagentId, 2)).find( + (child) => child.id !== poet!.id, + )!; + const judged = { ok: false, addAgents: [{ template: "rewiter", task: "Fix line 1." }] }; + yield* settleChild(critic, `\`\`\`json\n${JSON.stringify(judged)}\n\`\`\``); + + const error = 'round 1 critic: addAgents[0]: unknown template "rewiter"'; + const row = yield* ended(parent.threadId, subagentId); + assert.equal(row?.status, "failed"); + assert.equal(JSON.parse(row?.result ?? "{}").error, error); + assert.equal((yield* runs.status(parent.scope, subagentId)).error, error); + assert.deepInclude( + row?.workflow?.agents.find((agent) => agent.label === "critic"), + { state: "failed", result: error }, + ); + // Delivered as the continuation service would; the long draft keeps the result out of it. + yield* wakes(parent.threadId); + const offered = (yield* SubscriptionRef.get(yield* Offers)).find( + (offer) => offer.threadId === parent.threadId, + )!.delegatedCompletion!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:growth-error:wake"), + threadId: parent.threadId, + messageId: offered.messageId, + text: "Delegated task completed.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + delegatedCompletion: { + parentRunId: offered.parentRunId, + generation: offered.generation, + taskIds: [subagentId], + }, + }); + const wake = (yield* orchestrator.getThreadProjection(parent.threadId)).messages.find( + (message) => message.id === offered.messageId, + ); + assert.notInclude(wake?.text ?? "", row?.result ?? ""); + assert.include(wake?.text ?? "", error); + }), + ); + it.effect("resumes after a restart without relaunching a child and still wakes once", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -1253,6 +1359,11 @@ it.layer(layerTest)("t3_workflow_run", (it) => { assert.equal(row?.status, "failed"); const woken = JSON.parse(row?.result ?? "{}"); assert.equal(woken.stages[1].agents[0].status, "invalid_output"); + assert.match(woken.error, /^round 1 j: invalid_output: ./); + assert.deepInclude( + row?.workflow?.agents.find((agent) => agent.label === "j"), + { state: "failed", result: woken.error }, + ); assert.deepEqual(yield* runs.status(live.scope, subagentId), woken); // The runner records the judge's outcome, and the server stops before it ends the run. diff --git a/apps/server/src/mcp/WorkflowRuns.ts b/apps/server/src/mcp/WorkflowRuns.ts index ea4c8157df32..b3d935198c9a 100644 --- a/apps/server/src/mcp/WorkflowRuns.ts +++ b/apps/server/src/mcp/WorkflowRuns.ts @@ -34,6 +34,7 @@ import { import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { agentStages, + blamedLaunch, decodeWorkflowSpec, initialSnapshot, phaseAgents, @@ -169,7 +170,9 @@ function toRow( readonly workflow: OrchestrationV2SubagentWorkflow; readonly workflowRun: OrchestrationV2WorkflowRunState; } { - const { launches, ...state } = snapshot; + // The error is kept once, on the row it blames, to fit the last update's wire budget. + const { launches, error, ...state } = snapshot; + const blamed = blamedLaunch(spec, snapshot); const phases = workflowPhases(spec, snapshot); const agents = phases.flatMap(({ stage, round }, phaseIndex) => phaseAgents(spec, snapshot, stage, round).map((agent) => ({ @@ -202,13 +205,17 @@ function toRow( ...base, ...target, ...(child === undefined ? {} : { childThreadId: child.threadId }), - state: live - ? launch.taskId === null - ? "queued" - : "running" - : launch.outcome?.status === "completed" - ? "completed" - : "failed", + ...(launch === blamed && error ? { result: error } : {}), + state: + launch === blamed + ? "failed" + : live + ? launch.taskId === null + ? "queued" + : "running" + : launch.outcome?.status === "completed" + ? "completed" + : "failed", ...(queuedAt === undefined ? {} : { queuedAt }), ...(startedAt === undefined ? {} : { startedAt }), ...(completedAt === undefined ? {} : { completedAt }), @@ -327,7 +334,16 @@ const make = Effect.gen(function* () { }), ); const { version: _version, ...state } = run.workflowRun; - return { ...state, launches } satisfies WorkflowSnapshot; + const error = + state.status === "running" + ? undefined + : run.agents.find(({ agent }) => agent.state === "failed" && agent.result !== undefined) + ?.agent.result; + return { + ...state, + ...(error === undefined ? {} : { error }), + launches, + } satisfies WorkflowSnapshot; }); const drive = Effect.fn("WorkflowRuns.drive")(function* ( diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 93bd155d034c..67fafb4ce17e 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -136,7 +136,7 @@ const WorkflowStage = Schema.Struct({ const WorkflowRunTool = Tool.make("t3_workflow_run", { description: - "Run stages in order; returns at once, wakes you when done. Stage: `{id,agents:[{id,task,target?,role?,isolation?,resultSchema?}]}` (parallel) or `{id,repeat:{stages,judge,until:{path,equals},max,onExhausted?,dry?,templates?:{name:{task}}}}`. Its judge may return `addAgents:[{key,template,input,stage?}]`, `rerun:[stage]`; `dry:N` ends after N rounds of neither. {{stage}}, {{stage.agent}}, {{feedback}}, {{input.x}} insert results.", + "Run stages in order; returns now, wakes you when done. Stage: `{id,agents:[{id,task,target?,role?,isolation?,resultSchema?}]}` (parallel) or `{id,repeat:{stages,judge,until:{path,equals},max,onExhausted?,dry?,templates?:{name:{task}}}}`. Its judge may return `addAgents:[{template,task?,input?,key?,stage?}]`, `rerun:[stage]`; `dry:N` ends after N rounds of neither. {{stage}},{{stage.agent}},{{feedback}},{{input.x}} insert output.", parameters: Schema.Struct({ name: TrimmedNonEmptyString, stages: Schema.Array(WorkflowStage), diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 34054f1ec123..54c8c3e97e33 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -424,6 +424,7 @@ it.effect("never launches or records a round beyond max", () => "review.judge#2", ]); expect(fake.persisted.every(({ snapshot }) => snapshot.round <= 2)).toBe(true); + expect(result.error).toBe("loop: not accepted in 2 rounds"); expect(result.stages[1]).toMatchObject({ id: "loop", exit: null }); expect(result.stages[2]).toMatchObject({ agents: [{ id: "editor", status: "skipped" }] }); }), @@ -466,7 +467,9 @@ it.effect("a child whose JSON failed its resultSchema fails the run", () => const worker = makeFake({ reply: (start) => ({ outcome: start.agent.id === "a" ? invalid : ok(start.key) }), }); - expect((yield* runWorkflow(worker.port, innerLoop(3))).status).toBe("failed"); + const failedWorker = yield* runWorkflow(worker.port, innerLoop(3)); + expect(failedWorker.status).toBe("failed"); + expect(failedWorker.error).toBe("round 1 a: invalid_output: $.verdict: required"); expect(worker.created).not.toContain("revise.writer#1"); const judge = makeFake({ @@ -806,31 +809,51 @@ it.effect("exits after K consecutive dry votes, never on an invalid or missing j 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"] }, - ]) { + for (const [bad, error] of [ + [{ addAgents: [{ key: "x", template: "nope" }] }, 'addAgents[0]: unknown template "nope"'], + [ + { addAgents: [{ key: "x", template: "rewrite", stage: "polish" }] }, + 'addAgents[0]: unknown stage "polish"', + ], + [{ addAgents: [rewrite("ok", "x"), 3] }, "addAgents[1]: not an object"], + [{ addAgents: [{ key: "a b", template: "rewrite" }] }, "addAgents[0]: bad key"], + [{ addAgents: [{ template: "rewrite", task: 3 }] }, "addAgents[0]: task must be text"], + [{ rerun: ["polish"] }, 'rerun: unknown stage "polish"'], + ] as const) { const invalid = makeFake({ reply: judging([bad]) }); - expect((yield* runWorkflow(invalid.port, grow(3, { dry: 1 }))).status).toBe("failed"); + const result = yield* runWorkflow(invalid.port, grow(3, { dry: 1 })); + expect({ bad, status: result.status, error: result.error }).toEqual({ + bad, + status: "failed", + error: `round 1 critic: ${error}`, + }); 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"); + const unjudged = yield* runWorkflow(missing.port, grow(3, { dry: 1 })); + expect(unjudged.status).toBe("failed"); + expect(unjudged.error).toBe("round 1 critic: no structured result"); 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" }, - ]) { + for (const [bad, error] of [ + [{ verdict: "accept", rerun: ["polish"] }, 'rerun: unknown stage "polish"'], + [ + { verdict: "accept", addAgents: [{ key: "x", template: "nope" }] }, + 'addAgents[0]: unknown template "nope"', + ], + [{ verdict: "accept", addAgents: "bad" }, "addAgents must be a list"], + ] as const) { 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({ bad, status: result.status, error: result.error }).toEqual({ + bad, + status: "failed", + error: `round 1 critic: ${error}`, + }); expect(result.stages[0]).toMatchObject({ exit: null }); expect(fake.created).not.toContain("polish.editor#1"); } @@ -841,7 +864,11 @@ it.effect("an accepting judge whose growth is invalid fails the run instead of p }), }); const result = yield* runWorkflow(fake.port, grow(3, { dry: 1 })); - expect({ raw, status: result.status }).toEqual({ raw, status: "failed" }); + expect({ raw, status: result.status, error: result.error }).toEqual({ + raw, + status: "failed", + error: "round 1 critic: result is not an object", + }); } }), ); @@ -891,6 +918,154 @@ it.effect("deduplicates grown keys across the whole run, not just the current re }), ); +/** The judge result a live Haiku run returned verbatim: no key, a task instead of input. */ +const LIVE_JUDGE = { + best: "...", + best_score: 6, + addAgents: [{ template: "rewriter", task: "Rewrite only line 1 ..." }], + rerun: ["draft"], + done: false, + fix: "...", +}; +const haikuLoop = { + name: "haiku-growing-loop", + stages: [ + { + id: "loop", + repeat: { + stages: [ + { id: "draft", agents: [{ id: "poet", task: "Write. Notes: {{feedback}}" }] }, + { + id: "judge", + agents: [{ id: "judge", task: "Judge {{draft}}.", resultSchema: { type: "object" } }], + }, + ], + judge: "judge", + until: { path: "done", equals: true }, + max: 3, + templates: { rewriter: { task: "Rewrite {{draft.poet}} to fix {{input.fix}}." } }, + }, + }, + ], +}; +const liveJudging = + (first: unknown) => + (start: WorkflowAgentStart): Reply => ({ + outcome: + start.agent.id === "judge" + ? ok("judged", start.round === 1 ? first : { done: true }) + : ok(start.key), + }); + +it.effect("grows from the shapes a judge naturally writes: no key, a task instead of input", () => + Effect.gen(function* () { + const live = makeFake({ reply: liveJudging(LIVE_JUDGE) }); + const result = yield* runWorkflow(live.port, haikuLoop); + + expect(result.status).toBe("completed"); + expect(live.startCalls).toEqual([ + "draft.poet#1", + "judge.judge#1", + "draft.poet#2", + "draft.rewriter-1-0#2", + "judge.judge#2", + ]); + expect(live.rendered.get("draft.rewriter-1-0#2")).toBe("Rewrite only line 1 ..."); + + // A task resolves references; without one, the template's task takes the input. + const mixed = makeFake({ + reply: liveJudging({ + addAgents: [ + { template: "rewriter", task: "Fix {{draft.poet}} line 2." }, + { template: "rewriter", input: { fix: "meter" } }, + ], + rerun: ["judge"], + }), + }); + expect((yield* runWorkflow(mixed.port, haikuLoop)).status).toBe("completed"); + expect(mixed.rendered.get("draft.rewriter-1-0#2")).toBe("Fix draft.poet#1 line 2."); + expect(mixed.rendered.get("draft.rewriter-1-1#2")).toBe("Rewrite draft.poet#1 to fix meter."); + + yield* crashSweep(haikuLoop, liveJudging(LIVE_JUDGE), (fake, swept) => { + expect(swept.status).toBe("completed"); + expect(fake.violations).toEqual([]); + expect(fake.created.filter((key) => key === "draft.rewriter-1-0#2")).toHaveLength(1); + expect(new Set(fake.created).size).toBe(fake.created.length); + }); + }), +); + +it.effect( + "bounds a judge's task: it sees only what the judge saw, and never renders oversized", + () => + Effect.gen(function* () { + const seen = { + ...haikuLoop, + stages: [ + { id: "brief", agents: [{ id: "writer", task: "Brief." }] }, + { id: "private", agents: [{ id: "secret", task: "Private." }] }, + { + id: "loop", + repeat: { + ...haikuLoop.stages[0]!.repeat, + stages: [ + haikuLoop.stages[0]!.repeat.stages[0]!, + { + id: "judge", + agents: [ + { id: "judge", task: "Judge {{draft}} for {{brief}}.", resultSchema: {} }, + ], + }, + ], + }, + }, + ], + }; + const task = "{{brief.writer}} {{private.secret}} {{draft.poet}} {{input.x}}"; + const scoped = makeFake({ + reply: liveJudging({ + addAgents: [{ template: "rewriter", task, input: { x: "in" } }], + rerun: ["judge"], + }), + }); + expect((yield* runWorkflow(scoped.port, seen)).status).toBe("completed"); + expect(scoped.rendered.get("draft.rewriter-1-0#2")).toBe( + "brief.writer#1 {{private.secret}} draft.poet#1 in", + ); + + // 1,024 references to a 64 KiB result would render 64 MiB. + const huge = makeFake({ + reply: (start) => + start.agent.id === "poet" + ? { outcome: ok("X".repeat(65_536)) } + : liveJudging({ + addAgents: [{ template: "rewriter", task: "{{draft.poet}}".repeat(1_024) }], + })(start), + }); + const result = yield* runWorkflow(huge.port, haikuLoop); + expect(result.status).toBe("failed"); + expect(result.error).toBe( + "round 2 rewriter-1-0: failed: Its task renders to more than 120000 bytes.", + ); + expect(huge.startCalls).not.toContain("draft.rewriter-1-0#2"); + + // A task with no references, measured in bytes: 40,001 three-byte characters. + for (const literal of ["X".repeat(120_001), "界".repeat(40_001)]) { + const plain = makeFake({ + reply: liveJudging({ + addAgents: [{ template: "rewriter", task: literal }], + rerun: ["judge"], + }), + }); + const plainResult = yield* runWorkflow(plain.port, haikuLoop); + expect(plainResult.error).toBe( + "round 2 rewriter-1-0: failed: Its task renders to more than 120000 bytes.", + ); + expect(plain.startCalls).not.toContain("draft.rewriter-1-0#2"); + } + }), +); + it.effect("waits for grown agents before starting the next stage or judge", () => Effect.gen(function* () { const fake = makeFake({ diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index b010633d1caa..003a36b2941e 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -55,21 +55,7 @@ const RepeatStage = Schema.Struct({ }); 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); +const isWorkflowId = Schema.is(WorkflowId); export const WorkflowSpec = Schema.Struct({ name: TrimmedNonEmptyString, @@ -106,6 +92,7 @@ export const WorkflowSnapshot = Schema.Struct({ phase: Schema.Int, deadline: Schema.Number, stop: Schema.Boolean, + error: Schema.optional(Schema.String), launches: Schema.Array(WorkflowLaunch), exits: Schema.Array( Schema.Struct({ @@ -259,22 +246,62 @@ 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 isRecord = (value: unknown): value is Readonly> => + typeof value === "object" && value !== null && !Array.isArray(value); + +interface Growth { + readonly adds: ReadonlyArray<{ + readonly key: string; + readonly template: string; + readonly stage: string; + readonly task: string | undefined; + readonly input: Readonly>; + }>; + readonly rerun: ReadonlyArray; +} + +/** + * The judge's requests for the next round, or why they cannot be met. A missing key derives from + * the judge's round and the entry's position, so dedup and resume see the same key every time. + */ +function parseGrowth(stage: RepeatStage, round: number, value: unknown): Growth | string { + if (value === undefined) return "no structured result"; + if (!isRecord(value)) return "result is not an object"; 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 { addAgents = [], rerun = [] } = value; + if (!Array.isArray(addAgents)) return "addAgents must be a list"; + if (!Array.isArray(rerun)) return "rerun must be a list"; + const adds: Array = []; + for (const [index, add] of addAgents.entries()) { + const at = `addAgents[${index}]`; + if (!isRecord(add)) return `${at}: not an object`; + const { template, task, input = {}, stage: target = ids[0] } = add; + if (typeof template !== "string" || !Object.hasOwn(templates, template)) { + return `${at}: unknown template ${JSON.stringify(template ?? null)}`; + } + const key = + add.key ?? `${template.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 48)}-${round}-${index}`; + if (!isWorkflowId(key)) return `${at}: bad key`; + if (typeof target !== "string" || !ids.includes(target)) { + return `${at}: unknown stage ${JSON.stringify(target)}`; + } + if (task !== undefined && (typeof task !== "string" || task.trim() === "")) { + return `${at}: task must be text`; + } + if (!isRecord(input)) return `${at}: input must be an object`; + adds.push({ key, template, stage: target, task, input }); + } + const unknown = rerun.find((id) => typeof id !== "string" || !ids.includes(id)); + if (unknown !== undefined) return `rerun: unknown stage ${JSON.stringify(unknown)}`; + return { adds, rerun }; } +const growthIn = (stage: RepeatStage, state: WorkflowSnapshot, round: number) => { + const growth = parseGrowth(stage, round, judgedIn(state, stage, round)); + return typeof growth === "string" ? null : growth; +}; + const isGrown = (stage: RepeatStage, launch: WorkflowLaunch) => stage.repeat.stages.some( (s) => s.id === launch.stage && !s.agents.some((agent) => agent.id === launch.agent), @@ -283,7 +310,7 @@ const isGrown = (stage: RepeatStage, launch: WorkflowLaunch) => /** 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 ?? []; + const rerun = growthIn(stage, state, round - 1)?.rerun ?? []; return rerun.length === 0 || rerun.includes(phaseId); } @@ -332,7 +359,7 @@ export function phaseAgents( /** 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 growth = growthIn(stage, state, 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)), @@ -354,19 +381,24 @@ function dryStreak( ) { const wasDry = (round: number) => grownFor(spec, stage, state, round + 1).length === 0 && - !growthOf(stage, judgedIn(state, stage, round))?.rerun.length; + !growthIn(stage, state, round)?.rerun.length; let streak = dryNow ? 1 : 0; while (streak > 0 && streak < state.round && wasDry(state.round - streak)) streak += 1; return streak; } +/** delegate_task's prompt cap, in bytes; a task is measured before it is built. */ +const TASK_BYTES = 120_000; + +/** Null when the task would render past TASK_BYTES. `visible` limits the stages it may read. */ function renderTask( spec: WorkflowSpec, state: WorkflowSnapshot, template: string, input?: Readonly>, -): string { - return template.replace(REFERENCE, (match, stageRef: string, agentRef?: string) => { + visible?: ReadonlySet, +): string | null { + const resolve = (match: string, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { const stage = spec.stages[state.cursor]; if (stage === undefined || "agents" in stage) return match; @@ -375,6 +407,7 @@ function renderTask( if (stageRef === "input" && input !== undefined) { return agentRef === undefined ? JSON.stringify(input) : asText(input[agentRef] ?? null); } + if (visible !== undefined && !visible.has(stageRef)) return match; if (!agentStages(spec).some((stage) => stage.id === stageRef)) return match; const latest = new Map(); for (const launch of state.launches) { @@ -384,7 +417,30 @@ function renderTask( } if (agentRef !== undefined) return asText(latest.get(agentRef) ?? null); return JSON.stringify(Object.fromEntries(latest)); - }); + }; + const values = new Map(); + let bytes = Buffer.byteLength(template.replace(REFERENCE, "")); + if (bytes > TASK_BYTES) return null; + for (const [match, stageRef, agentRef] of template.matchAll(REFERENCE)) { + let value = values.get(match); + if (value === undefined) { + const resolved = resolve(match, stageRef!, agentRef); + value = { text: resolved, bytes: Buffer.byteLength(resolved) }; + values.set(match, value); + } + bytes += value.bytes; + if (bytes > TASK_BYTES) return null; + } + return template.replace(REFERENCE, (match) => values.get(match)!.text); +} + +/** A judge-authored task reads only the repeat's stages and those its judge's own task read. */ +function judgeView(stage: RepeatStage): ReadonlySet { + const judge = stage.repeat.stages.at(-1)?.agents.find((a) => a.id === stage.repeat.judge); + return new Set([ + ...stage.repeat.stages.map((s) => s.id), + ...[...(judge?.task.matchAll(REFERENCE) ?? [])].map(([, stageRef]) => stageRef!), + ]); } function accepts(until: RepeatStage["repeat"]["until"], value: unknown): boolean { @@ -397,21 +453,65 @@ function accepts(until: RepeatStage["repeat"]["until"], value: unknown): boolean } type Step = - | { readonly _tag: "finish"; readonly status: typeof WorkflowRunStatus.Type } + | { + readonly _tag: "finish"; + readonly status: typeof WorkflowRunStatus.Type; + readonly error?: string; + } | { 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" }; -const finish = (status: typeof WorkflowRunStatus.Type): Step => ({ _tag: "finish", status }); +const finish = (status: typeof WorkflowRunStatus.Type, error?: string): Step => ({ + _tag: "finish", + status, + ...(error === undefined ? {} : { error }), +}); const advance = (state: WorkflowSnapshot): Step => ({ _tag: "advance", state }); +const jsonBytes = (text: string) => Buffer.byteLength(JSON.stringify(text)) - 2; + +/** The error rides the run's last row update, so it is cut to a budget of JSON-encoded bytes. */ +const ERROR_BYTES = 200; +const clip = (text: string) => { + const flat = text.replace(/\s+/g, " ").trim(); + if (jsonBytes(flat) <= ERROR_BYTES) return flat; + let cut = ""; + let bytes = jsonBytes("…"); + for (const char of flat) { + bytes += jsonBytes(char); + if (bytes > ERROR_BYTES) break; + cut += char; + } + return `${cut}…`; +}; + +/** A launch that ended the run by not completing; the run's own cancels at its end never count. */ +const brokenLaunch = (state: WorkflowSnapshot) => + state.launches.find( + (l) => l.outcome !== null && l.outcome.status !== "completed" && !l.cancelRequested, + ); + +/** The row a failed run's error belongs to: the agent that failed, else the judge that ended it. */ +export function blamedLaunch(spec: WorkflowSpec, state: WorkflowSnapshot) { + if (state.status !== "failed" || state.error === undefined) return undefined; + const broken = brokenLaunch(state); + if (broken !== undefined) return broken; + const stage = spec.stages[state.cursor]; + if (stage === undefined || "agents" in stage) return undefined; + return findLaunch(state, stage.repeat.stages.at(-1)?.id ?? "", state.round, stage.repeat.judge); +} + /** The TLA model's runner actions, as a pure choice over the persisted state. */ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step { if (state.stop) return finish("cancelled"); if (now >= state.deadline) return finish("timed_out"); - if (state.launches.some((l) => l.outcome !== null && l.outcome.status !== "completed")) { - return finish("failed"); + const broken = brokenLaunch(state); + if (broken?.outcome) { + const { status, result } = broken.outcome; + const reason = result?.trim() ? `${status}: ${result}` : status; + return finish("failed", clip(`round ${broken.round} ${broken.agent}: ${reason}`)); } const stage = spec.stages[state.cursor]; if (stage === undefined) return finish("completed"); @@ -460,8 +560,10 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step }); 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"); + const growth = parseGrowth(loop, state.round, value); + if (typeof growth === "string") { + return finish("failed", clip(`round ${state.round} ${repeat.judge}: ${growth}`)); + } 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; @@ -469,12 +571,14 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step return advance(exit("dry")); } if (state.round === repeat.max) { - return repeat.onExhausted === "pass" ? advance(exit("exhausted")) : finish("failed"); + return repeat.onExhausted === "pass" + ? advance(exit("exhausted")) + : finish("failed", `${loop.id}: not accepted in ${state.round} rounds`); } return advance({ ...state, round: state.round + 1, phase: 0 }); } -/** A spec agent, or a grown one built from its template and the input its judge gave it. */ +/** A spec agent, or a grown one built from its template, with the task and 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( @@ -483,12 +587,14 @@ function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: Workflow 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 add = growthIn(stage, state, 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 { + agent: { ...template, id: add.key, task: add.task ?? template.task }, + input: add.input, + visible: add.task === undefined ? undefined : judgeView(stage), + }; } return undefined; } @@ -543,7 +649,11 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( return yield* update(key, { outcome: { status: "failed", result: "Not in the spec." } }); } const { agent } = found; - const task = renderTask(spec, state, agent.task, found.input); + const task = renderTask(spec, state, agent.task, found.input, found.visible); + if (task === null) { + const result = `Its task renders to more than ${TASK_BYTES} bytes.`; + return yield* update(key, { outcome: { status: "failed", result } }); + } const started = yield* port .start({ key, stage: launch.stage, round: launch.round, agent, task }) .pipe(Effect.result); @@ -587,6 +697,7 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( yield* save({ ...state, status: step.status, + ...(step.error === undefined ? {} : { error: step.error }), launches: state.launches.map((l) => l.outcome === null ? { ...l, cancelRequested: true, outcome: CANCELLED } : l, ), @@ -667,6 +778,7 @@ export function workflowResult(spec: WorkflowSpec, state: WorkflowSnapshot): Wor return { name: spec.name, status: state.status, + ...(state.error === undefined ? {} : { error: state.error }), stages: spec.stages.map((stage) => { if ("agents" in stage) return agents(stage, 1); const ids = new Set(stage.repeat.stages.map((s) => s.id)); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b72dfd9f6ea4..72457fb1facd 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -689,7 +689,12 @@ function delegatedCompletionWakeDetail( return detail; } } - return `${label}. Use task_status with taskId ${taskId} to read the result.`; + // A server-run workflow keeps its error on the row it blames. + const error = + task?.workflowRun === undefined + ? undefined + : task.workflow?.agents.find((agent) => agent.state === "failed" && agent.result)?.result; + return `${label}${error ? `: ${error}` : ""}. Use task_status with taskId ${taskId} to read the result.`; }) .join("\n\n"); }