Agentic AITypeScriptverifiedVerified

Plan-and-Execute Pattern in TypeScript

Separate high-level planning from step-by-step execution: one LLM call produces a structured plan, then individual executor calls carry out each step, with replanning triggered by unexpected results.

How to Implement the Plan-and-Execute Pattern in TypeScript

1Step 1: Define the Step, Plan, and executor types

interface Step {
  id: string;
  description: string;
  status: "pending" | "running" | "done" | "failed";
  result?: string;
}

interface Plan {
  goal: string;
  steps: Step[];
}

type Planner = (goal: string) => Promise<Step[]>;
type Executor = (step: Step) => Promise<string>;

2Step 2: Implement the plan-and-execute loop

async function planAndExecute(
  goal: string,
  planner: Planner,
  executor: Executor
): Promise<Plan> {
  // Phase 1: Plan
  const rawSteps = await planner(goal);
  const plan: Plan = { goal, steps: rawSteps };

  // Phase 2: Execute each step sequentially
  for (const step of plan.steps) {
    step.status = "running";
    try {
      step.result = await executor(step);
      step.status = "done";
    } catch (e) {
      step.result = String(e);
      step.status = "failed";
      break; // halt on first failure
    }
  }

  return plan;
}

3Step 3: Run the pipeline with a sample goal

// Usage
const plan = await planAndExecute(
  "Write and publish a blog post",
  async (goal) => [
    { id: "1", description: "Research the topic", status: "pending" },
    { id: "2", description: "Draft the outline", status: "pending" },
    { id: "3", description: "Write the post", status: "pending" },
    { id: "4", description: "Review and publish", status: "pending" },
  ],
  async (step) => {
    console.log(`Executing: ${step.description}`);
    return `Completed: ${step.description}`;
  }
);

console.log(plan.steps.map(s => `[${s.status}] ${s.description}`));

Plan-and-Execute Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Plan-and-Execute Pattern in the Real World

A building contractor (Planner) reviews the architectural blueprints and produces a phased construction schedule: foundation, framing, electrical, finishing. Individual trade crews (Executors) carry out each phase. If an inspection fails (unexpected result), the contractor revises the remaining schedule rather than demolishing the entire building and starting over.