Agentic Architectures

Catalogue / Multi-agent Coordination

Shared Task List

Agents claim the next unblocked task from one list and work at once

Shape
shared-state
Model calls
1 plan + 1 agent run per claim (tasks + retries) + 1 synthesis
Latency
medium
Complexity
high

Also known as Agent teams, Self-claiming agents, DeLM

1

How do several agents work at once without a coordinator in every step?

The work is written as a list of tasks with their dependencies. Each agent, in its own context, claims the next task that nothing blocks, does it, records the result and claims another. A claim is exclusive, so no task is done twice. Nobody hands out the work and nobody grants turns.

You may need it if

  • A coordinator assigns every subtask and reads every result, and the team moves at its pace.
  • Agents take turns on shared work while most of them wait.
  • The work splits into pieces that touch different files or topics.
  • Two parallel agents picked the same piece because nothing recorded who had taken what.
2

When does a self-service task list go wrong?

Use it when

  • The goal can be cut into tasks that touch separate files, modules or topics.
  • Few tasks wait on others, so several are open to claim at any moment.
  • Each task has a result that can be stated in a few lines and checked on its own.
  • Throughput matters more than having one mind review every step before it starts.

Avoid it when

  • The steps must happen in a fixed order, or most tasks wait on another one. Only one agent can work at a time and the rest idle.
    Use Plan–Execute–Verify instead
  • The problem is hard and cuts across everything. With no owner, agents pick the small safe tasks and the hard part is left. Someone must decide and review.
    Use Supervisor & Specialists instead
  • The tasks cannot be listed up front, because what to do next depends on what was just found.
    Use Blackboard instead
  • The work is one input cut into uniform parts under one instruction. A split and a merge do it with no list, no claims and no dependencies.
    Use Map-Reduce instead
  • Several tasks must edit the same files. A claim protects the task, not the file, and agents overwrite each other.

What it costs

Model calls
1 plan + 1 agent run per claim (tasks + retries) + 1 synthesis
Latency
medium
Complexity
high
3

How does a task move from the list to a finished result?

A lead writes the tasks and their dependencies on a shared list, then steps back. Teammates claim unblocked tasks under a lock, work at the same time and record results, which unblocks other tasks. Code checks the list after each task. When nothing is left, the lead writes the result.

tasks remainall done orbudget spentGoal: The goal to reach, or a plan whose steps are already written.GoalLead: Cuts the goal into tasks, states what each must produce and which tasks it waits for. Assigns nothing.LeadTeammates: Each in its own context. Claims the next unblocked task, does it, records the result, then claims another.TeammatesTask list: Every task with its state, owner, dependencies and result. A claim is exclusive and expires.Task listAll tasks done?: Plain code. After each task, reads the list, releases expired claims and checks the claim budget.All tasksdone?Lead's synthesis: The lead again, once the team has stopped. Writes the result from the recorded task results.Lead'ssynthesisResult: The combined result, with the state of every task and who did it.Result
  1. Step 1 of 6

    The lead writes the list

    The goal is a CSV export for a reporting app. The lead writes six tasks. T1 fixes the export format. T2 the endpoint, T3 the button and T4 the user guide wait for T1. T5, the end-to-end test, waits for T2 and T3. T6 audits personal data columns and waits for nothing.

  2. Step 2 of 6

    Teammates claim, nobody assigns

    Three teammates start, each in a fresh context. Ada claims T1 and Bo claims T6. The lock makes each claim exclusive. Cy finds four tasks pending and all of them blocked, so it waits.

  3. Step 3 of 6

    A result unblocks other tasks

    Ada records the format on T1 and marks it completed. T2, T3 and T4 become claimable at once. Ada, Bo and Cy take one each and work at the same time, reading T1's result from the list.

  4. Step 4 of 6

    Code checks the list after each task

    Each time a task ends, plain code reads the list. Tasks remain, so the teammates keep claiming. Some products also let teammates message each other directly. The list alone is enough for the pattern.

  5. Step 5 of 6

    A stalled claim expires

    Bo stalls on T3. After ten minutes the claim expires and T3 returns to pending. Cy, which has finished T4, claims it. Without the expiry, T5 would wait for ever behind a task nobody is doing.

  6. Step 6 of 6

    The lead writes the result

    T5 passes and nothing is left. The lead comes back, reads the six recorded results and writes what was built, where it is and who did what. A task that failed twice would be listed as unfinished.

What each part does
Goal
The goal to reach, or a plan whose steps are already written.
Lead
Cuts the goal into tasks, states what each must produce and which tasks it waits for. Assigns nothing.
Teammates
Each in its own context. Claims the next unblocked task, does it, records the result, then claims another.
Task list
Every task with its state, owner, dependencies and result. A claim is exclusive and expires.
All tasks done?
Plain code. After each task, reads the list, releases expired claims and checks the claim budget.
Lead's synthesis
The lead again, once the team has stopped. Writes the result from the recorded task results.
Result
The combined result, with the state of every task and who did it.
  • Lead → Task list: tasks and dependencies
  • Lead → Teammates: starts the team
  • Task list → Teammates: next unblocked task
  • Teammates → Task list: claim, then result
  • Teammates → All tasks done?: task finished
  • All tasks done? → Task list: releases expired claims
  • All tasks done? → Teammates: tasks remain
  • All tasks done? → Lead's synthesis: all done or budget spent

Where it connects

Entry
goal
TaskPlan

A goal that can be cut into separable tasks, or a plan whose steps are written. Given a plan, the lead turns its steps into tasks and adds the dependencies.

Exit
result
AnswerDocument

When: Every task is completed, or nothing can be claimed any more, or the claim budget is spent.

The result written from the completed tasks, then each task with its state, owner and recorded result, and the tasks left unfinished with the reason.

Working memory for one run
task-list
Plan

A list of tasks, each with a state (pending, in progress, completed or failed), an owner, the tasks it waits for and, once completed, a short result.

4

What do I ask my assistant to set up?

The agents to launch

Lead

Cut the goal into 5 to 15 tasks that can each be done alone and that touch separate files or topics. For each, say what to produce, how to tell it is done and which tasks it waits for. Do not assign tasks and do not do them. When the team has stopped, write the result from the recorded task results and list what is unfinished.

Sees: The goal at the start. At the end, the goal and the whole task list with results. Not the teammates' working contexts.

Teammate, three to five, each in its own context

Claim the next task that is pending and not blocked, and do only that task. Use the recorded results of the tasks it waited for. When done, record a short result: what you produced, where it is and what a later task needs to know. Then claim another. If you cannot finish, release the claim and say why.

Sees: The goal, the task list with states and recorded results, and the shared workspace. Not the lead's or other teammates' contexts.

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 "Shared Task List" 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]

# Shared Task List
Agents claim the next unblocked task from one list and work at once.
Input: the task above. It must provide: A goal that can be cut into separable tasks, or a plan whose steps are written. Given a plan, the lead turns its steps into tasks and adds the dependencies. If something essential is missing, ask for it before starting.

Agents to launch:
- Lead: Cut the goal into 5 to 15 tasks that can each be done alone and that touch separate files or topics. For each, say what to produce, how to tell it is done and which tasks it waits for. Do not assign tasks and do not do them. When the team has stopped, write the result from the recorded task results and list what is unfinished.
  Context for this agent: The goal at the start. At the end, the goal and the whole task list with results. Not the teammates' working contexts.
- Teammate (three to five, each in its own context): Claim the next task that is pending and not blocked, and do only that task. Use the recorded results of the tasks it waited for. When done, record a short result: what you produced, where it is and what a later task needs to know. Then claim another. If you cannot finish, release the claim and say why.
  Context for this agent: The goal, the task list with states and recorded results, and the shared workspace. Not the lead's or other teammates' contexts.

Procedure:
1. Launch the lead on the goal and store its tasks in one shared list. Each task has an id, a state, an owner, the ids it waits for and a result field.
2. Check the list with plain code. Dependencies must point to existing tasks, and no two tasks may name the same file as their output.
3. Launch three to five teammates at the same time, each in a fresh context with the goal and access to the list.
4. Make the claim atomic. Under a lock, a teammate takes the first pending task whose dependencies are all completed, and becomes its owner.
5. When a teammate finishes, write the result on the task and mark it completed in code. Do not rely on the teammate remembering to update the list.
6. Release any claim older than 10 minutes back to pending. After 2 failed attempts, mark the task failed and leave its dependants blocked.
7. When the stop rule is met, launch the lead once more on the goal and the list to write the result.

Stop rule: Stop when every task is completed. Stop also when no task can be claimed and none is in progress, or after 40 claims in total. A claim expires after 10 minutes and a task is abandoned after 2 attempts.

Exit:
- `result`, when: Every task is completed, or nothing can be claimed any more, or the claim budget is spent. Deliver: The result written from the completed tasks, then each task with its state, owner and recorded result, and the tasks left unfinished with the reason.

# Final deliverable
The result written by the lead, then the task list with each task's state, owner and recorded result, the tasks left unfinished and why, and the number of claims used.

The same thing in code

LangGraph, python, package langgraph
import asyncio
from dataclasses import dataclass
from typing import TypedDict

from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel

TEAM = ["ada", "bo", "cy"]
MAX_TASKS, MAX_CLAIMS, MAX_ATTEMPTS = 15, 40, 2
CLAIM_SECONDS = 600  # a claim expires after 10 minutes
LEAD = ("Cut the goal into 5 to 15 tasks that can each be done alone and touch separate files or topics. For "
        "each, say what to produce, how to tell it is done and which task ids it waits for. Assign nothing.")
TEAMMATE = ("Do only the task you claimed. Use the recorded results of the tasks it waited for. Reply with a "
            "short result: what you produced, where it is and what a later task needs to know.")
SYNTHESIS = "Write the result from the recorded task results only, and list every task that is not completed."


class Task(BaseModel):
    id: str
    title: str
    detail: str  # what to produce and how to tell it is done
    blocked_by: list[str]  # ids of the tasks that must be completed first


class Plan(BaseModel):
    tasks: list[Task]


@dataclass
class Entry:
    task: Task
    state: str = "pending"  # pending | in_progress | completed | failed
    owner: str = ""
    result: str = ""
    attempts: int = 0


class TaskList:
    def __init__(self, tasks: list[Task]) -> None:
        self.entries = {t.id: Entry(t) for t in tasks[:MAX_TASKS]}
        self.lock = asyncio.Lock()
        self.claims = 0

    async def claim(self, owner: str) -> Entry | None:
        async with self.lock:  # the claim lock: two teammates never get the same task
            for e in self.entries.values():
                waits = [self.entries[b].state for b in e.task.blocked_by if b in self.entries]
                if e.state == "pending" and all(s == "completed" for s in waits) and self.claims < MAX_CLAIMS:
                    e.state, e.owner, e.attempts = "in_progress", owner, e.attempts + 1
                    self.claims += 1
                    return e
            return None

    def busy(self) -> bool:
        return any(e.state == "in_progress" for e in self.entries.values())

    def listing(self) -> str:
        return "\n".join(f"[{e.task.id}] {e.task.title} | {e.state} | {e.owner} | {e.result}" for e in self.entries.values())


class State(TypedDict):
    goal: str
    tasks: list[Task]
    listing: str
    claims: int
    result: str


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


async def teammate(name: str, goal: str, board: TaskList) -> None:
    while True:
        entry = await board.claim(name)  # it pulls its own work: nobody assigns it
        if entry is None:
            if not board.busy():
                return  # nothing to claim and nothing in progress that could unblock a task
            await asyncio.sleep(1)
            continue
        prompt = f"{TEAMMATE}\n\nGoal: {goal}\n\nTask list:\n{board.listing()}\n\nYour task: [{entry.task.id}] {entry.task.detail}"
        try:
            msg = await asyncio.wait_for(llm.ainvoke(prompt), CLAIM_SECONDS)
            entry.result, entry.state = msg.text, "completed"  # set in code; unblocks its dependants
        except Exception:  # expired or crashed: the task returns to the list, twice at most
            entry.state, entry.owner = ("pending" if entry.attempts < MAX_ATTEMPTS else "failed"), ""


async def lead(state: State) -> dict:
    plan = Plan.model_validate(await llm.with_structured_output(Plan).ainvoke(f"{LEAD}\n\nGoal: {state['goal']}"))
    return {"tasks": plan.tasks}


async def team(state: State) -> dict:
    # the list and its lock live in this node: branch states are copies and could not share them
    board = TaskList(state["tasks"])
    await asyncio.gather(*(teammate(name, state["goal"], board) for name in TEAM))
    return {"listing": board.listing(), "claims": board.claims}


async def synthesis(state: State) -> dict:
    msg = await llm.ainvoke(f"{SYNTHESIS}\n\nGoal: {state['goal']}\n\nTask list:\n{state['listing']}")
    return {"result": msg.text}


g = StateGraph(State)
g.add_node("lead", lead)
g.add_node("team", team)
g.add_node("synthesis", synthesis)
g.add_edge(START, "lead")
g.add_edge("lead", "team")
g.add_edge("team", "synthesis")
g.add_edge("synthesis", END)
app = g.compile()


async def run(goal: str) -> dict:
    s = await app.ainvoke({"goal": goal, "tasks": [], "listing": "", "claims": 0, "result": ""})
    return {"result": s["result"], "task_list": s["listing"], "claims": s["claims"]}

The teammates run inside one node so that they share one list and one lock. Give each teammate real tools and a workspace; here a task is a single model call.

Claude Agent SDK, python, package claude-agent-sdk
import asyncio
from dataclasses import dataclass

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

TEAM = ["ada", "bo", "cy"]
MAX_TASKS, MAX_CLAIMS, MAX_ATTEMPTS = 15, 40, 2
CLAIM_SECONDS = 600  # a claim expires after 10 minutes
LEAD = ("Cut the goal into 5 to 15 tasks that can each be done alone and touch separate files or topics. For "
        "each, say what to produce, how to tell it is done and which task ids it waits for. Assign nothing.")
TEAMMATE = ("Do only the task you claimed. Use the recorded results of the tasks it waited for. Reply with a "
            "short result: what you produced, where it is and what a later task needs to know.")
SYNTHESIS = "Write the result from the recorded task results only, and list every task that is not completed."


class Task(BaseModel):
    id: str
    title: str
    detail: str  # what to produce and how to tell it is done
    blocked_by: list[str]  # ids of the tasks that must be completed first


class Plan(BaseModel):
    tasks: list[Task]


@dataclass
class Entry:
    task: Task
    state: str = "pending"  # pending | in_progress | completed | failed
    owner: str = ""
    result: str = ""
    attempts: int = 0


class TaskList:
    def __init__(self, tasks: list[Task]) -> None:
        self.entries = {t.id: Entry(t) for t in tasks[:MAX_TASKS]}
        self.lock = asyncio.Lock()
        self.claims = 0

    async def claim(self, owner: str) -> Entry | None:
        async with self.lock:  # the claim lock: two teammates never get the same task
            for e in self.entries.values():
                waits = [self.entries[b].state for b in e.task.blocked_by if b in self.entries]
                if e.state == "pending" and all(s == "completed" for s in waits) and self.claims < MAX_CLAIMS:
                    e.state, e.owner, e.attempts = "in_progress", owner, e.attempts + 1
                    self.claims += 1
                    return e
            return None

    def busy(self) -> bool:
        return any(e.state == "in_progress" for e in self.entries.values())

    def listing(self) -> str:
        return "\n".join(f"[{e.task.id}] {e.task.title} | {e.state} | {e.owner} | {e.result}" for e in self.entries.values())


async def session(system: str, prompt: str, schema: type[BaseModel] | None = None) -> ResultMessage:
    # every call is its own session: lead and teammates never share a context
    options = ClaudeAgentOptions(
        system_prompt=system,
        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 teammate(name: str, goal: str, board: TaskList) -> None:
    while True:
        entry = await board.claim(name)  # it pulls its own work: nobody assigns it
        if entry is None:
            if not board.busy():
                return  # nothing to claim and nothing in progress that could unblock a task
            await asyncio.sleep(1)
            continue
        prompt = f"Goal: {goal}\n\nTask list:\n{board.listing()}\n\nYour task: [{entry.task.id}] {entry.task.detail}"
        try:
            done = await asyncio.wait_for(session(TEAMMATE, prompt), CLAIM_SECONDS)
            entry.result, entry.state = done.result or "", "completed"  # set in code; unblocks its dependants
        except Exception:  # expired or crashed: the task returns to the list, twice at most
            entry.state, entry.owner = ("pending" if entry.attempts < MAX_ATTEMPTS else "failed"), ""


async def run(goal: str) -> dict:
    plan = Plan.model_validate((await session(LEAD, f"Goal: {goal}", Plan)).structured_output)
    board = TaskList(plan.tasks)  # the lead steps back: from here the list coordinates
    await asyncio.gather(*(teammate(name, goal, board) for name in TEAM))
    final = await session(SYNTHESIS, f"Goal: {goal}\n\nTask list:\n{board.listing()}")
    return {"result": final.result or "", "task_list": board.listing(), "claims": board.claims}

Each teammate is a loop of separate sessions around an in-process list. Claude Code's own agent teams keep the list on disk with file locks, and need an interactive session.

OpenAI Agents SDK, python, package openai-agents
import asyncio
from dataclasses import dataclass

from agents import Agent, Runner
from pydantic import BaseModel

TEAM = ["ada", "bo", "cy"]
MAX_TASKS, MAX_CLAIMS, MAX_ATTEMPTS = 15, 40, 2
CLAIM_SECONDS = 600  # a claim expires after 10 minutes


class Task(BaseModel):
    id: str
    title: str
    detail: str  # what to produce and how to tell it is done
    blocked_by: list[str]  # ids of the tasks that must be completed first


class Plan(BaseModel):
    tasks: list[Task]


@dataclass
class Entry:
    task: Task
    state: str = "pending"  # pending | in_progress | completed | failed
    owner: str = ""
    result: str = ""
    attempts: int = 0


class TaskList:
    def __init__(self, tasks: list[Task]) -> None:
        self.entries = {t.id: Entry(t) for t in tasks[:MAX_TASKS]}
        self.lock = asyncio.Lock()
        self.claims = 0

    async def claim(self, owner: str) -> Entry | None:
        async with self.lock:  # the claim lock: two teammates never get the same task
            for e in self.entries.values():
                waits = [self.entries[b].state for b in e.task.blocked_by if b in self.entries]
                if e.state == "pending" and all(s == "completed" for s in waits) and self.claims < MAX_CLAIMS:
                    e.state, e.owner, e.attempts = "in_progress", owner, e.attempts + 1
                    self.claims += 1
                    return e
            return None

    def busy(self) -> bool:
        return any(e.state == "in_progress" for e in self.entries.values())

    def listing(self) -> str:
        return "\n".join(f"[{e.task.id}] {e.task.title} | {e.state} | {e.owner} | {e.result}" for e in self.entries.values())


lead = Agent(name="Lead", output_type=Plan,
             instructions="Cut the goal into 5 to 15 tasks that can each be done alone and touch separate files or "
                          "topics. For each, say what to produce, how to tell it is done and which task ids it "
                          "waits for. Assign nothing.")
worker = Agent(name="Teammate",  # add the tools the tasks need
               instructions="Do only the task you claimed. Use the recorded results of the tasks it waited for. "
                            "Reply with a short result: what you produced, where it is and what a later task "
                            "needs to know.")
synthesizer = Agent(name="Lead (synthesis)",
                    instructions="Write the result from the recorded task results only, and list every task "
                                 "that is not completed.")


async def teammate(name: str, goal: str, board: TaskList) -> None:
    while True:
        entry = await board.claim(name)  # it pulls its own work: nobody assigns it
        if entry is None:
            if not board.busy():
                return  # nothing to claim and nothing in progress that could unblock a task
            await asyncio.sleep(1)
            continue
        prompt = f"Goal: {goal}\n\nTask list:\n{board.listing()}\n\nYour task: [{entry.task.id}] {entry.task.detail}"
        try:
            done = await asyncio.wait_for(Runner.run(worker, prompt), CLAIM_SECONDS)  # a fresh run per task
            entry.result, entry.state = done.final_output_as(str), "completed"  # set in code; unblocks dependants
        except Exception:  # expired or crashed: the task returns to the list, twice at most
            entry.state, entry.owner = ("pending" if entry.attempts < MAX_ATTEMPTS else "failed"), ""


async def run(goal: str) -> dict:
    plan = (await Runner.run(lead, f"Goal: {goal}")).final_output_as(Plan)
    board = TaskList(plan.tasks)  # the lead steps back: from here the list coordinates
    await asyncio.gather(*(teammate(name, goal, board) for name in TEAM))
    final = await Runner.run(synthesizer, f"Goal: {goal}\n\nTask list:\n{board.listing()}")
    return {"result": final.final_output_as(str), "task_list": board.listing(), "claims": board.claims}

No handoffs and no agents-as-tools: three loops share one list, and plain code makes the claim atomic. Give the teammate agent the tools its tasks need.

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

const TEAM = ['ada', 'bo', 'cy'];
const MAX_TASKS = 15;
const MAX_CLAIMS = 40;
const MAX_ATTEMPTS = 2;
const CLAIM_MS = 600_000; // a claim expires after 10 minutes
const model = anthropic('claude-sonnet-5-5');

const taskSchema = z.object({
  id: z.string(),
  title: z.string(),
  detail: z.string().describe('what to produce and how to tell it is done'),
  blockedBy: z.array(z.string()).describe('ids of the tasks that must be completed first'),
});
type Task = z.infer<typeof taskSchema>;
type Entry = {
  task: Task;
  state: 'pending' | 'in_progress' | 'completed' | 'failed';
  owner: string;
  result: string;
  attempts: number;
};

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

async function withExpiry<T>(job: Promise<T>, ms: number): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const expired = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error('claim expired')), ms);
  });
  try {
    return await Promise.race([job, expired]);
  } finally {
    clearTimeout(timer);
  }
}

export async function run(goal: string) {
  const { output: plan } = await generateText({
    model,
    instructions:
      'Cut the goal into 5 to 15 tasks that can each be done alone and touch separate files or topics. For ' +
      'each, say what to produce, how to tell it is done and which task ids it waits for. Assign nothing.',
    prompt: `Goal: ${goal}`,
    output: Output.object({ schema: z.object({ tasks: z.array(taskSchema) }) }),
  });

  // the shared list: the lead steps back, from here the list coordinates
  const entries = new Map<string, Entry>();
  for (const task of plan.tasks.slice(0, MAX_TASKS)) {
    entries.set(task.id, { task, state: 'pending', owner: '', result: '', attempts: 0 });
  }
  let claims = 0;
  const listing = () =>
    [...entries.values()].map((e) => `[${e.task.id}] ${e.task.title} | ${e.state} | ${e.owner} | ${e.result}`).join('\n');
  const busy = () => [...entries.values()].some((e) => e.state === 'in_progress');

  // synchronous, so two teammates in this process can never get the same task
  const claim = (owner: string): Entry | null => {
    if (claims >= MAX_CLAIMS) return null;
    for (const e of entries.values()) {
      const unblocked = e.task.blockedBy.every((id) => !entries.has(id) || entries.get(id)?.state === 'completed');
      if (e.state === 'pending' && unblocked) {
        e.state = 'in_progress';
        e.owner = owner;
        e.attempts += 1;
        claims += 1;
        return e;
      }
    }
    return null;
  };

  const teammate = async (name: string) => {
    for (;;) {
      const entry = claim(name); // it pulls its own work: nobody assigns it
      if (!entry) {
        if (!busy()) return; // nothing to claim and nothing in progress that could unblock a task
        await sleep(1000);
        continue;
      }
      try {
        const { text } = await withExpiry(
          generateText({
            model,
            instructions:
              'Do only the task you claimed. Use the recorded results of the tasks it waited for. Reply with a ' +
              'short result: what you produced, where it is and what a later task needs to know.',
            prompt: `Goal: ${goal}\n\nTask list:\n${listing()}\n\nYour task: [${entry.task.id}] ${entry.task.detail}`,
          }),
          CLAIM_MS,
        );
        entry.result = text;
        entry.state = 'completed'; // set in code; unblocks the tasks that wait for it
      } catch { // expired or crashed: the task returns to the list, twice at most
        entry.state = entry.attempts < MAX_ATTEMPTS ? 'pending' : 'failed';
        entry.owner = '';
      }
    }
  };
  await Promise.all(TEAM.map((name) => teammate(name)));

  const { text: result } = await generateText({
    model,
    instructions: 'Write the result from the recorded task results only, and list every task that is not completed.',
    prompt: `Goal: ${goal}\n\nTask list:\n${listing()}`,
  });
  return { result, taskList: listing(), claims };
}

The claim is one synchronous function, which is atomic in a single process. Across processes, use a file lock or a database row lock, and give teammates real tools.

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 claim with no expiry turns one stuck agent into a blocked team. Give every claim a time limit and return the task to the list.
  • Two tasks that write to the same file will overwrite each other, each under a valid claim. Cut tasks by file or module.
  • Agents sometimes finish the work and forget to mark the task completed, which blocks its dependants. Update the state in code.
  • With no owner, agents drift to small safe tasks. Have the lead write the hard part as a task of its own, with a clear test for done.
  • Tasks that are too small cost more in claiming than in work. Tasks that are too large run long with no checkpoint.

Chain it

Its result can feed

It can take the result of

Directly

Source