Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions apps/server/src/mcp/WorkflowRuns.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
}
}),
);

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
34 changes: 25 additions & 9 deletions apps/server/src/mcp/WorkflowRuns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import {
agentStages,
blamedLaunch,
decodeWorkflowSpec,
initialSnapshot,
phaseAgents,
Expand Down Expand Up @@ -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) => ({
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -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* (
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading
Loading