diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 484de4e6b1ff..2884eee6fa11 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -487,6 +487,26 @@ it.effect("rejects a string workflow stage by naming the stage shape before the }).pipe(Effect.provide(layerRecordingTools(calls))); }); +it.effect( + "passes unknown workflow keys to the service, which rejects them, never strips them", + () => { + const calls: Array = []; + return Effect.gen(function* () { + const agents = [{ id: "a", task: "Draft." }]; + const input = { + name: "review", + stages: [ + { id: "draft", agents, dependsOn: [] }, + { id: "loop", repeat: { stages: [{ id: "fix", agents }], judge: "a", max: 2 } }, + ], + timeout: 60_000, + }; + yield* callTool("t3_workflow_run", input).pipe(Effect.ignore); + expect(calls).toEqual([input]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, +); + it("advertises workflow stages as objects that need an id", () => { const schema = advertisedJsonSchema(OrchestratorToolkit.tools.t3_workflow_run) as { properties: { stages: { items?: { type?: string; required?: Array } } }; diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index b283815f5209..ae842cb6753e 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -1269,7 +1269,9 @@ it.layer(layerTest)("t3_workflow_run", (it) => { 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"'; + // The critic was delegated with its templates in its resultSchema, so its reply fails there. + const error = + 'round 1 critic: invalid_output: $.addAgents[0].template: not one of ["rewriter"]'; const row = yield* ended(parent.threadId, subagentId); assert.equal(row?.status, "failed"); assert.equal(JSON.parse(row?.result ?? "{}").error, error); diff --git a/apps/server/src/mcp/advertisedJsonSchema.test.ts b/apps/server/src/mcp/advertisedJsonSchema.test.ts index 09a90556a9dd..d9168f4fcb90 100644 --- a/apps/server/src/mcp/advertisedJsonSchema.test.ts +++ b/apps/server/src/mcp/advertisedJsonSchema.test.ts @@ -43,3 +43,17 @@ it("drops JSON noise, merges tagged unions, and keeps null where it is required" required: ["beforeRunId", "every"], }); }); + +it("advertises a struct that keeps unknown keys as the plain struct", () => { + const tool = Tool.make("example", { + parameters: Schema.StructWithRest(Schema.Struct({ id: Schema.String }), [ + Schema.Record(Schema.String, Schema.Unknown), + ]), + }); + + expect(advertisedJsonSchema(tool)).toEqual({ + type: "object", + properties: { id: { type: "string" } }, + required: ["id"], + }); +}); diff --git a/apps/server/src/mcp/advertisedJsonSchema.ts b/apps/server/src/mcp/advertisedJsonSchema.ts index 10001307f2d6..fe463b517b55 100644 --- a/apps/server/src/mcp/advertisedJsonSchema.ts +++ b/apps/server/src/mcp/advertisedJsonSchema.ts @@ -67,13 +67,15 @@ const mergeTaggedObjects = (branches: ReadonlyArray): JsonObject | undefin return { type: "object", properties, required: [tag, ...requiredByAll] }; }; +const isEmptyObject = (value: Json) => Predicate.isObject(value) && Object.keys(value).length === 0; + const compact = (schema: Json, optional: boolean): Json => { if (Array.isArray(schema)) return schema.map((item) => compact(item, false)); if (!Predicate.isObject(schema)) return schema; const required = new Set(Array.isArray(schema.required) ? schema.required : []); let result: JsonObject = {}; for (const [key, value] of Object.entries(schema)) { - if (key === "additionalProperties" && value === true) continue; + if (key === "additionalProperties" && (value === true || isEmptyObject(value))) continue; if (SAFE_INTEGER_BOUNDS[key] === value) continue; result[key] = key === "properties" && Predicate.isObject(value) @@ -85,6 +87,17 @@ const compact = (schema: Json, optional: boolean): Json => { ) : compact(value, false); } + // A `Schema.StructWithRest` rest compacts to an `allOf` branch that only restates the type. + if (Array.isArray(result.allOf)) { + const type = result.type; + const branches = result.allOf.filter( + (branch) => + !Predicate.isObject(branch) || + !Object.entries(branch).every(([key, value]) => key === "type" && value === type), + ); + const { allOf: _allOf, ...rest } = result; + result = branches.length === 0 ? rest : { ...rest, allOf: branches }; + } if (Array.isArray(result.anyOf)) { const branches = result.anyOf .flatMap((branch) => (isBareAnyOf(branch) ? branch.anyOf : [branch])) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 67fafb4ce17e..d64ab517a342 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -127,21 +127,40 @@ const TaskCancelTool = Tool.make("task_cancel", { const workflowDependencies = [...dependencies, WorkflowRuns.WorkflowRuns]; -// Stages advertise only their outline to keep the tool list small; the service decodes the full spec. -const WorkflowStage = Schema.Struct({ - id: Schema.String, - agents: Schema.optional(Schema.Array(Schema.Unknown)), - repeat: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), -}).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" }); +// The description types the spec; the schema is an outline the service decodes in full. Unknown keys +// pass through so the service rejects them: stripping them would run a spec the model did not write. +const withRest = >(struct: S) => + Schema.StructWithRest(struct, [Schema.Record(Schema.String, Schema.Unknown)]); +// Codex sends the items of an array with no item type as JSON strings, so agents are typed objects. +const agents = Schema.optional(Schema.Array(Schema.Record(Schema.String, Schema.Unknown))); +const WorkflowStage = withRest( + Schema.Struct({ + id: Schema.String, + agents, + repeat: Schema.optional( + withRest( + Schema.Struct({ + stages: Schema.optional(Schema.Array(withRest(Schema.Struct({ agents })))), + }), + ), + ), + }), +).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" }); const WorkflowRunTool = Tool.make("t3_workflow_run", { - description: - "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), - timeoutMs: Schema.optional(Schema.Int), - }), + description: `Run agents in stages; returns now, wakes you when done. +type Spec={name:string;stages:Stage[]} +type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents parallel +type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit model/options; options must match model*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} +type Loop={stages:{id:string;agents:Agent[]/*may be empty*/}[];judge?:string/*agent id in LAST stage; defaults to its sole agent*/;until:{path:string/*judge result field, e.g. 'ok'*/;equals:string|number|boolean|null};max:number/*1-10 rounds*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} +Tasks: {{stageId}} or {{stageId.agentId}} insert earlier results. After a loop use inner stage ids, never its id. Loops rerun stages in order; forward/self references and {{feedback}} read last round (null in round 1). The judge's result must have until's field; its schema is generated if omitted. With templates, judge may return addAgents:{template:string;task?:string;input?:object/*{{input.x}}*/;stage?:string}[] for next round and rerun:stageId[]. dry:N ends after N rounds with neither. Only loop judges add agents; put round 1 inside the loop.`, + parameters: withRest( + Schema.Struct({ + name: TrimmedNonEmptyString, + stages: Schema.Array(WorkflowStage), + timeoutMs: Schema.optional(Schema.Int), + }), + ), success: Schema.Struct({ subagentId: NodeId, next: Schema.Literal(ORCHESTRATOR_MCP_RUNNING_TASK_NEXT), diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 54c8c3e97e33..8ac08cce4940 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -8,6 +8,7 @@ import * as Fiber from "effect/Fiber"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; +import { validateJson } from "./resultSchema.ts"; import { decodeWorkflowSpec, initialSnapshot, @@ -683,6 +684,355 @@ it.effect("rejects bad references and judges before any start", () => }), ); +it.effect("rejects what it would otherwise drop or leave unresolved, before any start", () => + Effect.gen(function* () { + const one = (task: string) => ({ id: "x", task }); + const bad: Array<[unknown, string]> = [ + [ + { name: "both", stages: [{ id: "loop", agents: [one("x")], repeat: repeat(2) }] }, + "has both agents and repeat", + ], + [{ name: "key", stages: [{ id: "a", agents: [{ ...one("x"), model: "haiku" }] }] }, "model"], + [{ name: "top-key", stages: [{ id: "a", agents: [one("x")] }], timeout: 9 }, "timeout"], + [{ name: "stage-key", stages: [{ id: "a", agents: [one("x")], after: "b" }] }, "after"], + [ + { + name: "repeat-key", + stages: [draft, { id: "loop", repeat: { ...repeat(2), rounds: 3 } }], + }, + "rounds", + ], + [ + { name: "wrapper", stages: [draft, { id: "b", agents: [one("{{stage.draft}}")] }] }, + "{{stage.draft}}", + ], + [ + { name: "deep", stages: [draft, { id: "b", agents: [one("{{draft.a.result}}")] }] }, + "{{draft.a.result}}", + ], + [ + { + name: "until", + stages: [ + draft, + { + id: "loop", + repeat: { ...repeat(2), until: { path: "review.judge.verdict", equals: "accept" } }, + }, + ], + }, + "until.path", + ], + ]; + + for (const [input, message] of bad) { + const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); + const error = yield* runWorkflow(fake.port, input).pipe(Effect.flip); + expect(error.code).toBe("invalid_request"); + expect(error.message).toContain(message); + expect(fake.startCalls).toEqual([]); + } + }), +); + +it.effect( + "defaults a loop's judge to its last stage's only agent, and grows into empty stages", + () => + Effect.gen(function* () { + const fake = makeFake({ + reply: judging([{ addAgents: [{ key: "rw-1", template: "rewrite", stage: "fix" }] }, {}]), + }); + const { judge: _judge, ...loop } = grow(3).stages[0]!.repeat as Record; + const [draftStage, , critique] = grow(3).stages[0]!.repeat!.stages; + + const result = yield* runWorkflow(fake.port, { + name: "defaults", + stages: [ + { + id: "loop", + repeat: { + ...loop, + stages: [draftStage, { id: "fix", agents: [] }, critique], + max: 2, + onExhausted: "pass", + }, + }, + ], + }); + + expect(result.status).toBe("completed"); + expect(fake.startCalls).toEqual([ + "draft.poet#1", + "critique.critic#1", + "draft.poet#2", + "fix.rw-1#2", + "critique.critic#2", + ]); + }), +); + +it.effect("lets a loop stage read its own loop's later stages as last round's results", () => + Effect.gen(function* () { + const fake = makeFake({ reply: verdicts(["reject", "accept"]) }); + const loop = repeat(2); + const [, review] = loop.stages; + + const spec = { + name: "back-reference", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [ + { + id: "revise", + agents: [ + { + id: "writer", + task: "Fix {{revise.writer}} per {{review.judge}} in {{revise}}.", + }, + { id: "peer", task: "Peer {{revise.writer}}, stage {{revise}}, {{review}}." }, + ], + }, + review, + ], + }, + }, + ], + }; + + const result = yield* runWorkflow(fake.port, spec); + + expect(result.status).toBe("completed"); + expect(fake.rendered.get("revise.writer#1")).toBe("Fix null per null in null."); + expect(fake.rendered.get("revise.peer#1")).toBe("Peer null, stage null, null."); + const lastRound = '{"writer":"revise.writer#1","peer":"revise.peer#1"}'; + expect(fake.rendered.get("revise.writer#2")).toBe( + `Fix revise.writer#1 per {"verdict":"reject"} in ${lastRound}.`, + ); + expect(fake.rendered.get("revise.peer#2")).toBe( + `Peer revise.writer#1, stage ${lastRound}, {"judge":{"verdict":"reject"}}.`, + ); + + // Resumed in round 2 after the writer finished there: the peer still reads round 1 only. + const decoded = yield* decodeWorkflowSpec(spec); + const done = (stage: string, round: number, agent: string, outcome: WorkflowAgentOutcome) => ({ + stage, + round, + agent, + taskId: `task:${launchKey(stage, round, agent)}`, + cancelRequested: false, + outcome, + }); + const resumed = makeFake({ reply: verdicts(["reject", "accept"]) }); + yield* resumeWorkflow(resumed.port, decoded, { + ...initialSnapshot(decoded, yield* Clock.currentTimeMillis), + cursor: 1, + round: 2, + launches: [ + done("draft", 1, "a", ok("A")), + done("draft", 1, "b", ok("B")), + done("revise", 1, "writer", ok("writer-1")), + done("revise", 1, "peer", ok("peer-1")), + done("review", 1, "judge", ok("verdict", { verdict: "reject" })), + done("revise", 2, "writer", ok("writer-2")), + ], + }); + expect(resumed.rendered.get("revise.peer#2")).toBe( + 'Peer writer-1, stage {"writer":"writer-1","peer":"peer-1"}, {"judge":{"verdict":"reject"}}.', + ); + }), +); + +it.effect("gives a judge the result schema its until and templates need", () => + Effect.gen(function* () { + const schemas = new Map(); + const fake = makeFake({ + reply: verdicts(["accept"]), + onStart: (start) => Effect.sync(() => schemas.set(start.key, start.agent.resultSchema)), + }); + const loop = repeat(2); + const [revise, review] = loop.stages; + const bare = { + ...review, + agents: [{ id: "judge", task: "Judge {{revise.writer}}." }], + }; + + const result = yield* runWorkflow(fake.port, { + name: "bare-judge", + stages: [ + draft, + { + id: "loop", + repeat: { ...loop, stages: [revise, bare], templates: { fix: { task: "Fix." } } }, + }, + ], + }); + + expect(result.status).toBe("completed"); + expect(schemas.get("review.judge#1")).toEqual({ + type: "object", + properties: { + verdict: { type: "string" }, + feedback: { type: "string" }, + addAgents: { + type: "array", + items: { + type: "object", + properties: { + template: { enum: ["fix"] }, + task: { type: "string" }, + input: { type: "object" }, + key: { type: "string" }, + stage: { enum: ["revise", "review"] }, + }, + required: ["template"], + }, + }, + rerun: { type: "array", items: { enum: ["revise", "review"] } }, + }, + required: ["verdict"], + }); + expect(schemas.get("revise.writer#1")).toBeUndefined(); + + // A parent's own judge schema wins: its fields and constraints stay; only absent ones are added. + const own = { + type: "object", + properties: { verdict: { type: "string" }, addAgents: { type: "array" } }, + required: ["verdict", "addAgents"], + }; + const parented = makeFake({ + reply: verdicts(["accept"]), + onStart: (start) => Effect.sync(() => schemas.set(start.key, start.agent.resultSchema)), + }); + yield* runWorkflow(parented.port, { + name: "parent-judge", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [revise, { ...review, agents: [{ ...bare.agents[0]!, resultSchema: own }] }], + templates: { fix: { task: "Fix." } }, + }, + }, + ], + }); + expect(schemas.get("review.judge#1")).toEqual({ + ...own, + properties: { + ...own.properties, + rerun: { type: "array", items: { enum: ["revise", "review"] } }, + }, + }); + }), +); + +it.effect("a generated judge schema keeps until's field when it is named feedback", () => + Effect.gen(function* () { + for (const [path, accepting] of [ + ["feedback", { feedback: true }], + ["feedback.ok", { feedback: { ok: true } }], + ] as const) { + // The judge's reply passes through the real result validator, as a delegated task's does. + const fake = makeFake({ + reply: (start) => { + const value = start.agent.id === "judge" ? accepting : start.key; + const mismatch = + start.agent.resultSchema === undefined + ? null + : validateJson(start.agent.resultSchema, value); + return { + outcome: + mismatch === null + ? ok(start.key, start.agent.id === "judge" ? value : undefined) + : { status: "invalid_output", result: mismatch }, + }; + }, + }); + const loop = repeat(2); + const [revise, review] = loop.stages; + const result = yield* runWorkflow(fake.port, { + name: "feedback-until", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [revise, { ...review, agents: [{ id: "judge", task: "Judge." }] }], + until: { path, equals: true }, + }, + }, + ], + }); + expect({ path, status: result.status }).toEqual({ path, status: "completed" }); + } + }), +); + +it.effect("checks until.path only against what a judge schema actually rules out", () => + Effect.gen(function* () { + const withJudgeSchema = (resultSchema: Record) => { + const loop = repeat(2); + const [revise, review] = loop.stages; + return { + name: "until-path", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [ + revise, + { ...review, agents: [{ id: "judge", task: "Judge.", resultSchema }] }, + ], + until: { path: "ok", equals: true }, + }, + }, + ], + }; + }; + // Open schemas allow undeclared fields, and a closed one still allows what a pattern matches. + const open = { type: "object", properties: { reason: { type: "string" } }, required: ["ok"] }; + const closed = { ...open, required: [], additionalProperties: false }; + const allowed = [ + open, + { + type: "object", + properties: { reason: { type: "string" } }, + patternProperties: { "^ok$": { type: "boolean" } }, + additionalProperties: false, + required: ["ok"], + }, + { ...closed, patternProperties: { "(": {} } }, + ]; + for (const schema of allowed) { + const accepting = makeFake({ + reply: (start) => ({ + outcome: + start.agent.id === "judge" + ? ok("judged", { ok: true, reason: "accepted" }) + : ok(start.key), + }), + }); + const { status } = yield* runWorkflow(accepting.port, withJudgeSchema(schema)); + expect({ schema, status }).toEqual({ schema, status: "completed" }); + } + + for (const schema of [closed, { ...closed, patternProperties: { "^no$": {} } }]) { + const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); + const error = yield* runWorkflow(fake.port, withJudgeSchema(schema)).pipe(Effect.flip); + expect(error.message).toContain('until.path "ok"'); + expect(fake.startCalls).toEqual([]); + } + }), +); + /** Draft, probe, then a critic who judges and may grow the next round from two templates. */ const grow = (max: number, extra: Record = {}) => ({ name: "grow", diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 003a36b2941e..4a4e74f9e91b 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -8,6 +8,7 @@ import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; const DEFAULT_TIMEOUT_MS = 60 * 60 * 1_000; @@ -25,14 +26,16 @@ export const WorkflowAgent = Schema.Struct({ export type WorkflowAgent = typeof WorkflowAgent.Type; const AgentStage = Schema.Struct({ id: WorkflowId, agents: Schema.NonEmptyArray(WorkflowAgent) }); -type AgentStage = typeof AgentStage.Type; +// A loop's stage may start empty: the judge grows agents into it. +const LoopStage = Schema.Struct({ id: WorkflowId, agents: Schema.Array(WorkflowAgent) }); +type AgentStage = typeof LoopStage.Type; const RoundCount = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })); const RepeatStage = Schema.Struct({ id: WorkflowId, repeat: Schema.Struct({ - stages: Schema.NonEmptyArray(AgentStage), + stages: Schema.NonEmptyArray(LoopStage), judge: WorkflowId, until: Schema.Struct({ path: TrimmedNonEmptyString, @@ -152,12 +155,61 @@ export const launchKey = (stage: string, round: number, agent: string) => `${stage}.${agent}#${round}`; const REFERENCE = /\{\{\s*([A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_-]+))?\s*\}\}/g; +const EXACT_REFERENCE = new RegExp(`^${REFERENCE.source}$`); +const BRACES = /\{\{([^{}]*)\}\}/g; const CANCELLED: WorkflowAgentOutcome = { status: "cancelled", result: null }; const invalid = (message: string) => new OrchestratorMcpFailure({ code: "invalid_request", message }); -// Braces that name no stage stay literal, so a task can still show `{{x}}` syntax. +/** + * Why `until.path` cannot be in the judge's result, or null. Open schemas allow undeclared fields, so + * a path is ruled out only by a closed object whose properties and patterns all miss it, or by + * starting with one of the loop's own ids + * (a `stage.agent.field` guess) that the schema does not declare. + */ +function untilError(stage: RepeatStage, judge: WorkflowAgent): string | null { + const { path } = stage.repeat.until; + const loopIds = new Set([ + stage.id, + ...stage.repeat.stages.flatMap((s) => [s.id, ...s.agents.map((a) => a.id)]), + ]); + let schema: unknown = judge.resultSchema ?? {}; + for (const [depth, segment] of path.split(".").entries()) { + if (!isRecord(schema)) return null; + const properties = isRecord(schema.properties) ? schema.properties : {}; + if (Object.hasOwn(properties, segment)) { + schema = properties[segment]; + continue; + } + const patterns = isRecord(schema.patternProperties) ? schema.patternProperties : {}; + let matched: unknown; + for (const [pattern, sub] of Object.entries(patterns)) { + let regex: RegExp; + try { + regex = new RegExp(pattern, "u"); + } catch { + return null; // A pattern this engine cannot compile may allow the field; never reject on it. + } + if (regex.test(segment)) matched ??= sub; + } + if (matched !== undefined) { + schema = matched; + continue; + } + const where = `Repeat "${stage.id}": until.path "${path}"`; + if (schema.additionalProperties === false) { + return `${where} is not a field judge "${judge.id}"'s resultSchema allows.`; + } + if (depth === 0 && loopIds.has(segment)) { + return `${where} names a stage or agent; it is a field of judge "${judge.id}"'s own result, such as "ok".`; + } + return null; + } + return null; +} + +// Braces that name nothing in the spec stay literal, so a task can still show `{{x}}` syntax. function referenceError(spec: WorkflowSpec): string | null { const ids = new Set(); const repeats = new Set(); @@ -182,9 +234,8 @@ function referenceError(spec: WorkflowSpec): string | null { if (judge === undefined) { return `Repeat "${stage.id}": judge "${stage.repeat.judge}" must be an agent of its last stage.`; } - if (judge.resultSchema === undefined) { - return `Repeat "${stage.id}": judge "${judge.id}" needs a resultSchema for until.`; - } + const until = untilError(stage, judge); + if (until !== null) return until; } 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. @@ -197,22 +248,33 @@ function referenceError(spec: WorkflowSpec): string | null { } } const index = new Map(order.map(({ stage }, i) => [stage.id, i])); + const named = new Set([...ids, ...order.flatMap(({ stage }) => stage.agents.map((a) => a.id))]); for (const [position, { stage, repeat }] of order.entries()) { const agentIds = new Set(); for (const agent of stage.agents) { if (agentIds.has(agent.id)) return `Duplicate agent id "${stage.id}.${agent.id}".`; agentIds.add(agent.id); - for (const [text, stageRef, agentRef] of agent.task.matchAll(REFERENCE)) { + for (const [text, inner = ""] of agent.task.matchAll(BRACES)) { const where = `"${stage.id}.${agent.id}" uses ${text}`; + const [, stageRef, agentRef] = EXACT_REFERENCE.exec(text) ?? []; if (stageRef === "feedback") { - if (repeat === null || agentRef !== undefined) return `${where} outside a repeat.`; + if (repeat === null) return `${where} outside a repeat.`; + if (agentRef !== undefined) return `${where}; use {{feedback}}, the judge's last result.`; + continue; + } + if (stageRef === "input") continue; + const target = stageRef === undefined ? undefined : index.get(stageRef); + if (stageRef === undefined || target === undefined) { + // Braces that mention a spec id yet resolve to nothing would reach the agent verbatim. + if (inner.split(".").some((part) => named.has(part.trim()))) { + return `${where}, which is not a reference: use {{stage}} or {{stage.agent}}.`; + } continue; } - if (stageRef === undefined) continue; if (repeats.has(stageRef)) return `${where}; name one of the repeat's stages instead.`; - const target = index.get(stageRef); - if (target === undefined) continue; - if (target >= position) return `${where}, which has not run yet.`; + // In a loop, a stage that has not run this round reads last round's results (none in round 1). + const sameLoop = repeat !== null && order[target]?.repeat === repeat; + if (target >= position && !sameLoop) return `${where}, which has not run yet.`; const known = order[target]?.stage.agents.some((a) => a.id === agentRef) ?? false; if (agentRef !== undefined && !known) return `${where}, which names no agent there.`; } @@ -221,10 +283,49 @@ function referenceError(spec: WorkflowSpec): string | null { return null; } -const decodeSpec = Schema.decodeUnknownEffect(WorkflowSpec); +// An unknown key is a guess at a field that does not exist; ignoring it would run another spec. +const STRICT = { onExcessProperty: "error" } as const; +const decodeSpec = Schema.decodeUnknownEffect(WorkflowSpec, STRICT); +type StageDecoder = (stage: unknown) => Result.Result; +const stageDecoders: Record<"agents" | "repeat", StageDecoder> = { + agents: Schema.decodeUnknownResult(AgentStage, STRICT), + repeat: Schema.decodeUnknownResult(RepeatStage, STRICT), +}; + +/** The first stage that is not exactly one variant, judged by its own variant, not the union. */ +function stageError(input: unknown): string | null { + const stages = isRecord(input) && Array.isArray(input.stages) ? input.stages : []; + for (const [index, stage] of stages.entries()) { + if (!isRecord(stage)) continue; + const label = `Stage "${String(stage.id)}" (stages[${index}])`; + if ("agents" in stage && "repeat" in stage) { + return `${label} has both agents and repeat. Give it one: put a loop's agents in repeat.stages.`; + } + const decoded = stageDecoders["repeat" in stage ? "repeat" : "agents"](stage); + if (Result.isFailure(decoded)) return `${label}: ${decoded.failure.message}`; + } + return null; +} + +/** A loop that names no judge takes its last stage's only agent. */ +function withDefaultJudges(input: unknown): unknown { + if (!isRecord(input) || !Array.isArray(input.stages)) return input; + const stages = input.stages.map((stage: unknown) => { + if (!isRecord(stage) || !isRecord(stage.repeat) || "judge" in stage.repeat) return stage; + const last: unknown = Array.isArray(stage.repeat.stages) ? stage.repeat.stages.at(-1) : null; + const agents: unknown = isRecord(last) ? last.agents : null; + const [only] = Array.isArray(agents) && agents.length === 1 ? agents : []; + if (!isRecord(only) || typeof only.id !== "string") return stage; + return { ...stage, repeat: { ...stage.repeat, judge: only.id } }; + }); + return { ...input, stages }; +} /** Decodes a spec and rejects unknown or forward references before anything starts. */ -export const decodeWorkflowSpec = Effect.fn("WorkflowRun.decodeSpec")(function* (input: unknown) { +export const decodeWorkflowSpec = Effect.fn("WorkflowRun.decodeSpec")(function* (raw: unknown) { + const input = withDefaultJudges(raw); + const shape = stageError(input); + if (shape !== null) return yield* invalid(shape); const spec = yield* decodeSpec(input).pipe(Effect.mapError((error) => invalid(error.message))); const error = referenceError(spec); if (error !== null) return yield* invalid(error); @@ -390,14 +491,20 @@ function dryStreak( /** 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. */ +/** + * Null when the task would render past TASK_BYTES. `from` is the rendering agent's stage; `visible` + * limits the stages it may read. + */ function renderTask( spec: WorkflowSpec, state: WorkflowSnapshot, template: string, + from: string, input?: Readonly>, visible?: ReadonlySet, ): string | null { + const loop = spec.stages[state.cursor]; + const order = loop === undefined || "agents" in loop ? [] : loop.repeat.stages.map((s) => s.id); const resolve = (match: string, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { const stage = spec.stages[state.cursor]; @@ -409,14 +516,22 @@ function renderTask( } if (visible !== undefined && !visible.has(stageRef)) return match; if (!agentStages(spec).some((stage) => stage.id === stageRef)) return match; + const completed = state.launches.filter( + (l) => l.stage === stageRef && l.outcome?.status === "completed", + ); + // A same-loop stage that has not run yet this round reads only the last round it ran in, so a + // sibling finishing first, or a resume, never changes what this task sees. + const ahead = order.includes(from) && order.indexOf(stageRef) >= order.indexOf(from); + const before = completed.filter((l) => l.round < state.round).map((l) => l.round); + const round = ahead ? Math.max(0, ...before) : undefined; const latest = new Map(); - for (const launch of state.launches) { - if (launch.stage === stageRef && launch.outcome?.status === "completed") { - latest.set(launch.agent, valueOf(launch.outcome)); + for (const launch of completed) { + if (round === undefined || launch.round === round) { + latest.set(launch.agent, valueOf(launch.outcome!)); } } if (agentRef !== undefined) return asText(latest.get(agentRef) ?? null); - return JSON.stringify(Object.fromEntries(latest)); + return latest.size === 0 && ahead ? "null" : JSON.stringify(Object.fromEntries(latest)); }; const values = new Map(); let bytes = Buffer.byteLength(template.replace(REFERENCE, "")); @@ -578,6 +693,52 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step return advance({ ...state, round: state.round + 1, phase: 0 }); } +/** + * What the judge is asked to return: the parent's schema, else one with the field `until` reads, plus + * the growth contract its templates need. The judge sees it in its task, so it never guesses one. + */ +function judgeSchema(stage: RepeatStage, judge: WorkflowAgent): WorkflowAgent["resultSchema"] { + const { stages, templates = {}, until } = stage.repeat; + const [field = "", ...rest] = until.path.split("."); + const leaf = { type: until.equals === null ? "null" : typeof until.equals }; + const nest = (schema: object, key: string) => ({ + type: "object", + properties: { [key]: schema }, + required: [key], + }); + const base = judge.resultSchema ?? { + type: "object", + // until's field comes last, so a path through `feedback` keeps its type. + properties: { feedback: { type: "string" }, [field]: rest.reduceRight(nest, leaf) }, + required: [field], + }; + const names = Object.keys(templates); + if (names.length === 0) return base; + const ids = stages.map((s) => s.id); + const properties = isRecord(base.properties) ? base.properties : {}; + return { + ...base, + properties: { + addAgents: { + type: "array", + items: { + type: "object", + properties: { + template: { enum: names }, + task: { type: "string" }, + input: { type: "object" }, + key: { type: "string" }, + stage: { enum: ids }, + }, + required: ["template"], + }, + }, + rerun: { type: "array", items: { enum: ids } }, + ...properties, + }, + }; +} + /** 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) { @@ -586,6 +747,13 @@ function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: Workflow ); if (phase === undefined) continue; const agent = phase.agents.find((a) => a.id === launch.agent); + if ( + !("agents" in stage) && + stage.repeat.stages.at(-1) === phase && + agent?.id === stage.repeat.judge + ) { + return { agent: { ...agent, resultSchema: judgeSchema(stage, agent) } }; + } if (agent !== undefined || "agents" in stage) return agent && { agent }; const add = growthIn(stage, state, launch.round - 1)?.adds.find((a) => a.key === launch.agent); const template = add && stage.repeat.templates?.[add.template]; @@ -649,7 +817,7 @@ 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, found.visible); + const task = renderTask(spec, state, agent.task, launch.stage, 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 } }); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 1d99b2763b8b..eae23d4e43d5 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 47106 + "mcpToolListJsonBytes": 48093 } diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index c5b005af9e55..244afc7e996e 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -148,23 +148,11 @@ it.effect("passes the staged-loop workflow case only for a real repeat stage", ( ]; const decodes = (stages: unknown) => Effect.exit(decodeWorkflowSpec({ name: "notes", stages })).pipe(Effect.map(Exit.isSuccess)); - const loop = real[1] as { repeat: { stages: Array<{ agents: Array }> } }; - const noSchema = [ - real[0], - { - ...loop, - repeat: { - ...loop.repeat, - stages: [ - loop.repeat.stages[0], - { id: "judge", agents: [agent("opus", "claude-opus-5-5")] }, - ], - }, - }, - ]; - expect([yield* decodes(real), yield* decodes(noSchema)]).toEqual([true, false]); + const loop = real[1] as { repeat: object }; + const judgeObject = [real[0], { ...loop, repeat: { ...loop.repeat, judge: { id: "opus" } } }]; + expect([yield* decodes(real), yield* decodes(judgeObject)]).toEqual([true, false]); expect(failed(staged.expect, run(real))).toEqual([]); - // The mock fails a spec the real decoder rejects, such as a judge without a resultSchema. + // The mock fails a spec the real decoder rejects, such as a judge given as an object. expect(failed(staged.expect, run(real, true))).not.toEqual([]); const named = [{ id: "repeat", agents: drafts.map((model, i) => agent(`d${i}`, model)) }]; expect(failed(staged.expect, run(named))).not.toEqual([]);