Agentic Architectures

Catalogue / Multi-agent Coordination

Magentic Orchestration

A manager keeps two ledgers and replans when the team stalls

Shape
orchestrator
Model calls
2 + 2 × rounds + 1 per replan (capped, often 15 to 45)
Latency
high
Complexity
high

Also known as Magentic-One, Task-ledger orchestration

1

What if nobody knows the path to the answer when the work starts?

A manager writes a task ledger: known facts, facts to find, guesses and a plan. Each round it fills a progress ledger: is the task done, is the team looping, who acts next. One specialist acts and reports. After several rounds without progress, the manager rewrites the task ledger and replans.

You may need it if

  • A supervisor keeps assigning subtasks that fail the same way, and nothing tells it to change approach.
  • The split of work cannot be decided up front, because each finding changes what to do next.
  • After twenty steps nobody can say which facts are established and which are still guesses.
2

When are two ledgers more than the task deserves?

Use it when

  • The task is open-ended. The plan has to be built, tried against reality and revised.
  • Specialists act on the world (browse, read files, run code) and their results are uncertain.
  • You can afford one manager call per round on top of each specialist's work.

Avoid it when

  • The steps are known before the work starts. A plan written once and executed in order needs no ledger per round.
    Use Planning instead
  • The division of work is clear from the task. A supervisor that splits once and merges needs no record of progress.
    Use Supervisor & Specialists instead
  • One specialist should take over the conversation and answer the user itself. Here the manager stays in charge of every turn.
    Use Handoff instead
  • The request is simple or urgent. Every round pays a manager call before any specialist acts.
    Use ReAct instead

What it costs

Model calls
2 + 2 × rounds + 1 per replan (capped, often 15 to 45)
Latency
high
Complexity
high
3

How do the two ledgers steer the team round after round?

Two nested loops. Outer: the manager writes the task ledger with facts, guesses and a plan. Inner: each round it fills the progress ledger, then one specialist acts and reports. Too many rounds without progress send the run back to the outer loop. At the end the manager writes the answer from the transcript.

satisfied,or roundlimitnot satisfiednext agent,instructionreports backstalled:rewrite theledgerno replans leftTask: An open-ended request, with any files it refers to. The team of specialists is already configured.TaskManager: Writes and rewrites the task ledger. Each round, fills the progress ledger: done, looping, progressing, who acts next, with what instruction.ManagerTask ledger: Facts given or verified, facts to look up, facts to derive, educated guesses, and the current plan in plain language.Task ledgerProgress ledger: The manager's five answers for the current round, and the count of rounds without progress.ProgressledgerDone, or out of rounds?: Plain code. Reads the first answer of the progress ledger and the number of rounds used.Done, or outof rounds?Stalled?: Plain code. Counts consecutive rounds that show a loop or no progress, and trips when the count passes 2.Stalled?Specialists: Tool-using agents, such as a web browser, a file reader and a coder. One acts per round on the manager's instruction, then reports.SpecialistsFinal report: The manager again. Reads the whole transcript and the task ledger, then writes the answer or, at a limit, its best guess.Final reportResult: The answer or a best guess marked as such, with the last task ledger and the list of rounds.Result
  1. Step 1 of 7

    The manager writes the task ledger

    The task: by how much has the monthly pass in the attached 2023 fare sheet changed compared with today's price? The manager lists what is given, what to look up (today's price), what to derive (the percentage) and a guess: the operator's website shows the price. Then it writes a short plan.

  2. Step 2 of 7

    A round starts with the progress ledger

    The manager rereads the ledger and the transcript and answers five questions. Request satisfied? No. Looping? No. Progress? Yes. Who acts next? The file reader. With what instruction? Extract the monthly pass price from the attached sheet.

  3. Step 3 of 7

    One specialist acts

    Plain code reads the ledger: not done, rounds left, not stalled. The file reader receives the instruction, opens the sheet and reports 62 euros. Its report joins the transcript and the next round begins.

  4. Step 4 of 7

    The team stops making progress

    The web agent is sent to the operator's site and meets a login wall. Sent twice more by other routes, it reports the same wall. For three rounds in a row the manager answers no progress or looping. The count passes 2 and the gate trips.

  5. Step 5 of 7

    The manager rewrites the task ledger

    The run returns to the outer loop. The manager notes what it learned: the site hides its prices. It replaces the guess with a new one: the regional authority publishes the fares. It writes a new plan, the count goes back to zero and the specialists start from a clean context.

  6. Step 6 of 7

    The request is satisfied

    The web agent finds 68 euros in the authority's fare table and the coder computes the change. In the next progress ledger the manager answers yes to the first question. It then reads the whole transcript and writes the answer, an increase of 9.7 percent, with both sources.

  7. Step 7 of 7

    Or a limit ends the run

    After 20 rounds, or when the team stalls again with both replans used, the loops stop. The manager still writes a report. It gives its best guess, says that it is a guess, and lists what was established and what was not. There is no separate failure exit.

What each part does
Task
An open-ended request, with any files it refers to. The team of specialists is already configured.
Manager
Writes and rewrites the task ledger. Each round, fills the progress ledger: done, looping, progressing, who acts next, with what instruction.
Task ledger
Facts given or verified, facts to look up, facts to derive, educated guesses, and the current plan in plain language.
Progress ledger
The manager's five answers for the current round, and the count of rounds without progress.
Done, or out of rounds?
Plain code. Reads the first answer of the progress ledger and the number of rounds used.
Stalled?
Plain code. Counts consecutive rounds that show a loop or no progress, and trips when the count passes 2.
Specialists
Tool-using agents, such as a web browser, a file reader and a coder. One acts per round on the manager's instruction, then reports.
Final report
The manager again. Reads the whole transcript and the task ledger, then writes the answer or, at a limit, its best guess.
Result
The answer or a best guess marked as such, with the last task ledger and the list of rounds.
  • Done, or out of rounds? → Final report: satisfied, or round limit
  • Done, or out of rounds? → Stalled?: not satisfied
  • Stalled? → Specialists: next agent, instruction
  • Specialists → Manager: reports back
  • Stalled? → Manager: stalled: rewrite the ledger
  • Stalled? → Final report: no replans left

Where it connects

Entry
task
TaskQuestion

An open-ended request with any files it refers to. No plan is expected, since the manager builds it. The team and a description of each member are already configured.

Exit
result
AnswerOutcome

When: The manager marks the request satisfied, or the round limit or the replan limit is reached.

The final answer or, at a limit, a best guess marked as such. Then the last task ledger and the list of rounds with the agent, the instruction and its report.

Working memory for one run
task-ledger
Plan

Facts given or verified, facts to look up, facts to derive, educated guesses and the plan. The manager rewrites all of it at each replan.

Working memory for one run
progress-ledger
Verdict

One record per round: request satisfied, looping, progressing, next agent, instruction, each with a reason. Plus the count of stalled rounds.

4

What do I ask my assistant to set up?

The agents to launch

Manager

You lead a team and do none of its work. First write the task ledger: facts given, facts to look up, facts to derive, educated guesses, then a short plan naming team members. Each round, say whether the request is satisfied, whether the team is looping, whether progress is being made, who acts next and with what instruction. When told the team is stalled, say what went wrong and rewrite the ledger.

Sees: The task, a description of each specialist, the task ledger and the transcript of instructions and reports. Not the specialists' tools.

Specialist, one per capability, often three to five

You hold one capability, such as browsing the web, reading files or writing and running code. Carry out the one instruction you receive with your own tools. Report what you did, what you found and what failed. Do not plan the rest of the task.

Sees: The transcript since the last replan and its instruction for this round. Its own tools only. Not the ledgers.

A prompt you can paste

Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.

Framework-agnostic prompt
You are the orchestrator of a multi-agent workflow that follows the "Magentic Orchestration" architecture.
Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it.

# Task
[Describe your task here]

# Magentic Orchestration
A manager keeps two ledgers and replans when the team stalls.
Input: the task above. It must provide: An open-ended request with any files it refers to. No plan is expected, since the manager builds it. The team and a description of each member are already configured. If something essential is missing, ask for it before starting.

Agents to launch:
- Manager: You lead a team and do none of its work. First write the task ledger: facts given, facts to look up, facts to derive, educated guesses, then a short plan naming team members. Each round, say whether the request is satisfied, whether the team is looping, whether progress is being made, who acts next and with what instruction. When told the team is stalled, say what went wrong and rewrite the ledger.
  Context for this agent: The task, a description of each specialist, the task ledger and the transcript of instructions and reports. Not the specialists' tools.
- Specialist (one per capability, often three to five): You hold one capability, such as browsing the web, reading files or writing and running code. Carry out the one instruction you receive with your own tools. Report what you did, what you found and what failed. Do not plan the rest of the task.
  Context for this agent: The transcript since the last replan and its instruction for this round. Its own tools only. Not the ledgers.

Procedure:
1. Describe each specialist in one or two lines, with what it can do and with which tools. The manager chooses from these descriptions.
2. Launch the manager on the task to write the task ledger. It lists facts, lookups, derivations and guesses, then the plan. If a person should approve the plan, show it to them here.
3. Each round, ask the manager for the progress ledger as a fixed record. It holds the five answers, with a short reason next to each.
4. If the request is satisfied, go to the final report. Otherwise update the stall count. Add one when the round shows a loop or no progress, and reset it when progress is made.
5. While the count is at 2 or less, send the instruction to the named specialist and append its report to the transcript.
6. When the count passes 2, ask the manager what went wrong and have it rewrite the task ledger and the plan. Clear the specialists' contexts, reset the count and resume the rounds. Allow 2 replans.
7. At the end, launch the manager on the full transcript and the task ledger to write the final answer.

Stop rule: Stop when the manager marks the request satisfied. Stop also after 20 rounds, or when the team stalls again after 2 replans. In both cases the manager still reports its best guess and says that it is one.

Exit:
- `result`, when: The manager marks the request satisfied, or the round limit or the replan limit is reached. Deliver: The final answer or, at a limit, a best guess marked as such. Then the last task ledger and the list of rounds with the agent, the instruction and its report.

# Final deliverable
The answer, or a best guess marked as such. Then the final task ledger, the number of rounds and replans, and the list of rounds with the agent, the instruction and one line of result.

The same thing in code

LangGraph, python, package langgraph
from typing import Literal, TypedDict

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel

MAX_ROUNDS, MAX_STALLS, MAX_REPLANS = 20, 2, 2
TEAM = {  # one description per specialist; in a real system each one has its own tools
    "web": "Browses the web: searches, opens pages and reads them.",
    "files": "Reads local files and attachments.",
    "coder": "Writes and runs code for calculations and data processing.",
}
MANAGER = "You lead this team and do none of its work:\n" + "\n".join(f"- {n}: {d}" for n, d in TEAM.items())
LEDGER = ("Write the task ledger: facts given or verified, facts to look up, facts to derive, educated "
          "guesses, then a short plan that names team members.")
REPLAN = ("The team is stalled. Say what went wrong and what was learned. Then rewrite the whole task ledger, "
          "with revised guesses and a new plan.")
REPORT = ("Write the final answer from the rounds and the ledger. If the request is not satisfied, give your "
          "best guess and say that it is a guess.")


class Progress(BaseModel):  # the progress ledger: a fixed record that plain code can read
    satisfied: bool
    looping: bool
    progressing: bool
    reason: str  # the new fact this round produced, or why there is none
    next_agent: Literal["web", "files", "coder"]
    instruction: str


class State(TypedDict):
    task: str
    ledger: str  # the task ledger
    transcript: list[str]  # cleared at each replan
    log: list[str]  # every round, kept for the final report
    progress: Progress | None
    rounds: int
    stalls: int
    replans: int
    answer: str
    status: str


model = init_chat_model("anthropic:claude-sonnet-5-5")


async def ask(system: str, prompt: str) -> str:
    return (await model.ainvoke([SystemMessage(system), HumanMessage(prompt)])).text


def view(state: State) -> str:
    return f"Task: {state['task']}\n\nTask ledger:\n{state['ledger']}\n\nTranscript:\n" + "\n".join(state["transcript"])


async def write_ledger(state: State) -> dict:  # outer loop
    if not state["ledger"]:
        return {"ledger": await ask(MANAGER, f"Task: {state['task']}\n\n{LEDGER}")}
    ledger = await ask(MANAGER, f"{view(state)}\n\n{REPLAN}")
    return {"ledger": ledger, "transcript": [], "stalls": 0, "replans": state["replans"] + 1}


async def progress_ledger(state: State) -> dict:  # inner loop: once per round
    raw = await model.with_structured_output(Progress).ainvoke(
        [SystemMessage(MANAGER), HumanMessage(view(state) + "\n\nFill the progress ledger.")])
    p = Progress.model_validate(raw)
    stalls = 0 if p.progressing and not p.looping else state["stalls"] + 1
    return {"progress": p, "stalls": stalls}


def route(state: State) -> str:
    p = state["progress"]
    if (p and p.satisfied) or state["rounds"] >= MAX_ROUNDS:
        return "report"
    if state["stalls"] > MAX_STALLS:  # stalled: replan, or stop when both replans are used
        return "write_ledger" if state["replans"] < MAX_REPLANS else "report"
    return "specialist"


async def specialist(state: State) -> dict:
    p = state["progress"]
    assert p is not None
    brief = (f"You are the {p.next_agent} agent. {TEAM[p.next_agent]} Carry out the one instruction you "
             "receive. Report what you did, what you found and what failed.")
    reply = await ask(brief, "\n".join(state["transcript"] + [f"Instruction: {p.instruction}"]))
    line = f"[{p.next_agent}] {p.instruction} -> {reply}"
    return {"transcript": state["transcript"] + [line], "log": state["log"] + [line], "rounds": state["rounds"] + 1}


async def report(state: State) -> dict:
    p = state["progress"]
    rounds = "\n".join(state["log"])
    answer = await ask(MANAGER, f"Task: {state['task']}\n\nTask ledger:\n{state['ledger']}\n\nAll rounds:\n{rounds}\n\n{REPORT}")
    return {"answer": answer, "status": "answered" if p and p.satisfied else "best guess"}


builder = StateGraph(State)
builder.add_node("write_ledger", write_ledger)
builder.add_node("progress_ledger", progress_ledger)
builder.add_node("specialist", specialist)
builder.add_node("report", report)
builder.add_edge(START, "write_ledger")
builder.add_edge("write_ledger", "progress_ledger")
builder.add_conditional_edges("progress_ledger", route, ["report", "write_ledger", "specialist"])
builder.add_edge("specialist", "progress_ledger")
builder.add_edge("report", END)
graph = builder.compile()


async def run(task: str) -> dict:
    start: State = {"task": task, "ledger": "", "transcript": [], "log": [], "progress": None,
             "rounds": 0, "stalls": 0, "replans": 0, "answer": "", "status": ""}
    s = await graph.ainvoke(start, {"recursion_limit": 3 * MAX_ROUNDS + 20})
    return {"answer": s["answer"], "status": s["status"], "ledger": s["ledger"], "rounds": s["log"], "replans": s["replans"]}

Specialists rely on instructions alone here: give each one its real tools. Status says whether the answer is a best guess written at a limit.

Claude Agent SDK, python, package claude-agent-sdk
from typing import Literal

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel

MAX_ROUNDS, MAX_STALLS, MAX_REPLANS = 20, 2, 2
TEAM = {  # description and tools of each specialist
    "web": ("Browses the web: searches, opens pages and reads them.", ["WebSearch", "WebFetch"]),
    "files": ("Reads local files and attachments.", ["Read", "Glob", "Grep"]),
    "coder": ("Writes and runs code for calculations and data processing.", ["Write", "Bash"]),
}
MANAGER = "You lead this team and do none of its work:\n" + "\n".join(f"- {n}: {d}" for n, (d, _) in TEAM.items())
LEDGER = ("Write the task ledger: facts given or verified, facts to look up, facts to derive, educated "
          "guesses, then a short plan that names team members.")
REPLAN = ("The team is stalled. Say what went wrong and what was learned. Then rewrite the whole task ledger, "
          "with revised guesses and a new plan.")
REPORT = ("Write the final answer from the rounds and the ledger. If the request is not satisfied, give your "
          "best guess and say that it is a guess.")


class Progress(BaseModel):  # the progress ledger: a fixed record that plain code can read
    satisfied: bool
    looping: bool
    progressing: bool
    reason: str  # the new fact this round produced, or why there is none
    next_agent: Literal["web", "files", "coder"]
    instruction: str


async def session(system: str, prompt: str, tools: list[str], schema: type[BaseModel] | None = None) -> ResultMessage:
    # one fresh session per call: the manager has no tools, a specialist has only its own
    options = ClaudeAgentOptions(
        system_prompt=system,
        allowed_tools=tools,
        output_format={"type": "json_schema", "schema": schema.model_json_schema()} if schema else None,
    )
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage):
            return msg
    raise RuntimeError("no result")


async def run(task: str) -> dict:
    ledger = (await session(MANAGER, f"Task: {task}\n\n{LEDGER}", [])).result or ""
    transcript: list[str] = []  # cleared at each replan
    log: list[str] = []  # every round, kept for the final report
    stalls, replans, satisfied = 0, 0, False
    while len(log) < MAX_ROUNDS:  # stop rule: 20 rounds
        view = f"Task: {task}\n\nTask ledger:\n{ledger}\n\nTranscript:\n" + "\n".join(transcript)
        raw = await session(MANAGER, view + "\n\nFill the progress ledger.", [], Progress)
        p = Progress.model_validate(raw.structured_output)
        if p.satisfied:
            satisfied = True
            break
        stalls = 0 if p.progressing and not p.looping else stalls + 1
        if stalls > MAX_STALLS:  # stalled: back to the outer loop
            if replans == MAX_REPLANS:
                break
            ledger = (await session(MANAGER, f"{view}\n\n{REPLAN}", [])).result or ledger
            transcript, stalls, replans = [], 0, replans + 1
            continue
        description, tools = TEAM[p.next_agent]
        brief = (f"You are the {p.next_agent} agent. {description} Carry out the one instruction you "
                 "receive. Report what you did, what you found and what failed.")
        reply = await session(brief, "\n".join(transcript + [f"Instruction: {p.instruction}"]), tools)
        line = f"[{p.next_agent}] {p.instruction} -> {reply.result or ''}"
        transcript.append(line)
        log.append(line)
    rounds = "\n".join(log)
    final = await session(MANAGER, f"Task: {task}\n\nTask ledger:\n{ledger}\n\nAll rounds:\n{rounds}\n\n{REPORT}", [])
    return {"answer": final.result, "status": "answered" if satisfied else "best guess",
            "ledger": ledger, "rounds": log, "replans": replans}

Each specialist is its own session with its own tools. Run the coder in a sandboxed working directory. Status says whether the answer is a best guess.

OpenAI Agents SDK, python, package openai-agents
from typing import Literal

from agents import Agent, Runner
from pydantic import BaseModel

MAX_ROUNDS, MAX_STALLS, MAX_REPLANS = 20, 2, 2
TEAM = {  # one description per specialist
    "web": "Browses the web: searches, opens pages and reads them.",
    "files": "Reads local files and attachments.",
    "coder": "Writes and runs code for calculations and data processing.",
}
MANAGER = "You lead this team and do none of its work:\n" + "\n".join(f"- {n}: {d}" for n, d in TEAM.items())
LEDGER = ("Write the task ledger: facts given or verified, facts to look up, facts to derive, educated "
          "guesses, then a short plan that names team members.")
REPLAN = ("The team is stalled. Say what went wrong and what was learned. Then rewrite the whole task ledger, "
          "with revised guesses and a new plan.")
REPORT = ("Write the final answer from the rounds and the ledger. If the request is not satisfied, give your "
          "best guess and say that it is a guess.")


class Progress(BaseModel):  # the progress ledger: a fixed record that plain code can read
    satisfied: bool
    looping: bool
    progressing: bool
    reason: str  # the new fact this round produced, or why there is none
    next_agent: Literal["web", "files", "coder"]
    instruction: str


manager = Agent(name="Manager", instructions=MANAGER)
tracker = manager.clone(output_type=Progress)  # the same manager, filling the progress ledger
specialists = {
    name: Agent(
        name=name,
        instructions=f"You are the {name} agent. {description} Carry out the one instruction you receive. "
                     "Report what you did, what you found and what failed.",
        tools=[],  # plug in this specialist's own tools
    )
    for name, description in TEAM.items()
}


async def run(task: str) -> dict:
    ledger = (await Runner.run(manager, f"Task: {task}\n\n{LEDGER}")).final_output_as(str)
    transcript: list[str] = []  # cleared at each replan
    log: list[str] = []  # every round, kept for the final report
    stalls, replans, satisfied = 0, 0, False
    while len(log) < MAX_ROUNDS:  # stop rule: 20 rounds
        view = f"Task: {task}\n\nTask ledger:\n{ledger}\n\nTranscript:\n" + "\n".join(transcript)
        p = (await Runner.run(tracker, view + "\n\nFill the progress ledger.")).final_output_as(Progress)
        if p.satisfied:
            satisfied = True
            break
        stalls = 0 if p.progressing and not p.looping else stalls + 1
        if stalls > MAX_STALLS:  # stalled: back to the outer loop
            if replans == MAX_REPLANS:
                break
            ledger = (await Runner.run(manager, f"{view}\n\n{REPLAN}")).final_output_as(str)
            transcript, stalls, replans = [], 0, replans + 1
            continue
        # one specialist acts per round, on the manager's instruction
        prompt = "\n".join(transcript + [f"Instruction: {p.instruction}"])
        reply = (await Runner.run(specialists[p.next_agent], prompt)).final_output_as(str)
        line = f"[{p.next_agent}] {p.instruction} -> {reply}"
        transcript.append(line)
        log.append(line)
    rounds = "\n".join(log)
    final = await Runner.run(manager, f"Task: {task}\n\nTask ledger:\n{ledger}\n\nAll rounds:\n{rounds}\n\n{REPORT}")
    return {"answer": final.final_output_as(str), "status": "answered" if satisfied else "best guess",
            "ledger": ledger, "rounds": log, "replans": replans}

The manager never hands control over: plain code calls the specialist it names. Give each specialist its real tools. Status flags a best guess.

Vercel AI SDK, typescript, package ai
import { anthropic } from '@ai-sdk/anthropic';
import { Output, ToolLoopAgent } from 'ai';
import { z } from 'zod';

const MAX_ROUNDS = 20;
const MAX_STALLS = 2;
const MAX_REPLANS = 2;
const model = anthropic('claude-sonnet-5-5');
const TEAM = { // one description per specialist
  web: 'Browses the web: searches, opens pages and reads them.',
  files: 'Reads local files and attachments.',
  coder: 'Writes and runs code for calculations and data processing.',
};
type Member = keyof typeof TEAM;
const MANAGER =
  'You lead this team and do none of its work:\n' +
  Object.entries(TEAM).map(([name, description]) => `- ${name}: ${description}`).join('\n');
const LEDGER =
  'Write the task ledger: facts given or verified, facts to look up, facts to derive, educated ' +
  'guesses, then a short plan that names team members.';
const REPLAN =
  'The team is stalled. Say what went wrong and what was learned. Then rewrite the whole task ledger, ' +
  'with revised guesses and a new plan.';
const REPORT =
  'Write the final answer from the rounds and the ledger. If the request is not satisfied, give your ' +
  'best guess and say that it is a guess.';

// the progress ledger: a fixed record that plain code can read
const progressSchema = z.object({
  satisfied: z.boolean(),
  looping: z.boolean(),
  progressing: z.boolean(),
  reason: z.string().describe('the new fact this round produced, or why there is none'),
  nextAgent: z.enum(['web', 'files', 'coder']),
  instruction: z.string(),
});

const manager = new ToolLoopAgent({ model, instructions: MANAGER });
const tracker = new ToolLoopAgent({ model, instructions: MANAGER, output: Output.object({ schema: progressSchema }) });
const specialist = (name: Member) =>
  new ToolLoopAgent({
    model,
    instructions:
      `You are the ${name} agent. ${TEAM[name]} Carry out the one instruction you receive. ` +
      'Report what you did, what you found and what failed.',
    tools: {}, // plug in this specialist's own tools
  });

export async function run(task: string) {
  let ledger = (await manager.generate({ prompt: `Task: ${task}\n\n${LEDGER}` })).text;
  let transcript: string[] = []; // cleared at each replan
  const log: string[] = []; // every round, kept for the final report
  let stalls = 0;
  let replans = 0;
  let satisfied = false;
  while (log.length < MAX_ROUNDS) { // stop rule: 20 rounds
    const view = `Task: ${task}\n\nTask ledger:\n${ledger}\n\nTranscript:\n${transcript.join('\n')}`;
    const { output: p } = await tracker.generate({ prompt: `${view}\n\nFill the progress ledger.` });
    if (p.satisfied) {
      satisfied = true;
      break;
    }
    stalls = p.progressing && !p.looping ? 0 : stalls + 1;
    if (stalls > MAX_STALLS) { // stalled: back to the outer loop
      if (replans === MAX_REPLANS) break;
      ledger = (await manager.generate({ prompt: `${view}\n\n${REPLAN}` })).text;
      transcript = [];
      stalls = 0;
      replans++;
      continue;
    }
    // one specialist acts per round, on the manager's instruction
    const { text } = await specialist(p.nextAgent).generate({
      prompt: [...transcript, `Instruction: ${p.instruction}`].join('\n'),
    });
    const line = `[${p.nextAgent}] ${p.instruction} -> ${text}`;
    transcript.push(line);
    log.push(line);
  }
  const { text: answer } = await manager.generate({
    prompt: `Task: ${task}\n\nTask ledger:\n${ledger}\n\nAll rounds:\n${log.join('\n')}\n\n${REPORT}`,
  });
  return { answer, status: satisfied ? 'answered' : 'best guess', ledger, rounds: log, replans };
}

Plain code calls the specialist the manager names. Give each specialist its real tools. Status says whether the answer is a best guess written at a limit.

Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.

What goes wrong

  • A progress ledger written as free text cannot drive code. Ask for a fixed record with five fields and a reason next to each answer.
  • A manager that always answers that progress is being made never trips the counter. Make it name the new fact the round produced.
  • Replanning without rewriting the facts and guesses gives the same plan in other words. A stall usually comes from a wrong guess.
  • Without a cap on rounds and replans, a task that cannot be solved runs until the budget is gone.
  • At a limit the best guess looks like an answer. Mark it clearly, so that a later stage does not treat it as established.

Chain it

Its result can feed

Source