When a Single Conversation Can't Hold a Large Task: Let Agents Turn Orchestration into Code

    When AI agents face tasks far larger than one conversation can coordinate—such as migrating a large codebase—having the agent write its orchestration logic as an executable script offers a way forward. This article explains the four levels of agent collaboration, why turn-by-turn coordination breaks down at scale, how code-based workflow orchestration works, and where it does and doesn't apply.

    When a Single Conversation Can’t Hold a Large Task: Let Agents Turn Orchestration into Code

    A Real Engineering Challenge

    Consider this class of task: migrating an entire large runtime project to another systems programming language, involving hundreds of thousands of lines of code and thousands of source files, with the requirement that the existing test suite passes almost entirely. These tasks share a defining trait—their scale far exceeds what a single agent can coordinate within one conversation.

    Similar scenarios are common in enterprise development:

    • Codebase-wide defect investigation: cross-referencing call chains, logging instrumentation, and historical changes across an entire microservice codebase;
    • Large-scale refactoring or migration touching hundreds of files: every change may affect other modules, requiring batched processing and continuous verification;
    • Technical proposals requiring repeated multi-angle scrutiny: a design must survive “stress tests” across performance, security, cost, and maintainability before sign-off.

    The bottleneck in these tasks is not whether the agent is “smart enough,” but the coordination structure itself. A recent idea worth attention is this: instead of having the agent act as the scheduler turn by turn, let it write the entire orchestration logic as an executable script and hand it to a separate runtime. This article calls this paradigm “code-based workflow orchestration” and examines its principles, boundaries, and engineering practice.

    Four Levels of Agent Collaboration

    To understand the value of code-based orchestration, it helps to map the collaboration levels common in current agentic coding tools. They roughly form a pyramid:

    Level 1: Single-session serial execution. One agent instance does everything from start to finish; all reasoning, tool calls, and intermediate results live in the same context window. This is the simplest and most reliable mode, suited to small, well-bounded tasks.

    Level 2: Subagent spawning. A main agent spawns subagents to handle subtasks such as searching files, reading code, and running commands; the subagents report conclusions back. This master-worker structure lets the main agent focus on decisions while outsourcing information gathering.

    Level 3: Parallel multi-instance teams. Multiple independent agent instances work in parallel like a team, communicating and exchanging state—suited to large tasks that naturally decompose into independent subproblems.

    Level 4: Code-based workflow orchestration. The focus of this article—the agent no longer schedules turn by turn. Instead, it writes the orchestration logic as a script in advance, with loops, branching, concurrency control, and result aggregation all fixed in code, then hands it to a runtime to execute.

    The Shared Bottleneck of the First Three Levels

    The first three levels seem progressive, but they share a structural bottleneck: the orchestrator is always the agent itself.

    This means two things:

    First, context window overflow risk. Every subagent result must enter the main agent’s context window before the agent can decide the next step. When coordinating dozens or hundreds of parallel subtasks, the flood of intermediate results quickly exhausts context capacity. Even with summarization and compression, information loss and error accumulation remain problems.

    Second, attention dilution. An agent’s reasoning quality correlates strongly with the density of relevant information in its context. When the context is filled with process artifacts—logs, file fragments, intermediate output—the agent’s “attention” to the overall goal gets diluted, and decision quality degrades: missed branches, duplicated work, even drifting away from the original objective.

    In other words, turn-by-turn scheduling keeps the entire state of orchestration inside the agent’s context. Once a task crosses a certain scale threshold, this mode simply stops working in engineering terms.

    The Core Idea: Move the Plan into Code

    The key shift of code-based workflow orchestration can be summarized in one sentence: move the orchestration plan out of the agent’s context and into executable code.

    The flow looks like this:

    1. The agent analyzes the task goal and decomposes it into a directed execution plan: which steps can run in parallel, which must be serial, and how to retry or fall back on failure;
    2. It writes this plan as a script (usually in a general-purpose scripting language), explicitly declaring loops, conditional branches, concurrency scheduling, and result aggregation;
    3. The script is handed to an independent runtime, which can drive multiple agent instances or subtasks concurrently;
    4. Intermediate results live in script state variables or external storage and no longer flow back into the main agent’s context;
    5. The main agent only inspects aggregated results at key checkpoints, handling final judgment and correction.

    A representative pseudocode structure:

    1. // Pseudocode: typical structure of code-based orchestration
    2. const modules = await scanModules("./src"); // Scan modules to migrate
    3. const results = await parallel(modules, async (m) => {
    4. const migrated = await agent.run(`Migrate module ${m.name}`);
    5. const test = await runTests(m.testSuite); // Verify immediately
    6. if (!test.passed) {
    7. return await agent.run(`Fix ${m.name}: ${test.failures}`);
    8. }
    9. return migrated;
    10. }, { concurrency: 8 }); // Limit concurrency
    11. const summary = aggregate(results); // Aggregate results
    12. await agent.run(`Run a final consistency check based on this summary: ${summary}`);

    As shown, scheduling state—which modules are done, which failed, how many retries— is maintained entirely by the script, while the main agent’s context holds only highly condensed summaries. This is precisely why the approach can support tasks at the “hundreds of thousands of lines” scale.

    Engineering Benefits

    1. A fundamentally higher scale ceiling. The context window is no longer a hard constraint on coordination. Intermediate results live in code state, so the number of orchestratable subtasks is limited only by compute and cost.

    2. Determinism and auditability. The orchestration logic is explicit code, not implicit turn-by-turn decisions. Teams can review scripts, manage them in version control, and reproduce runs—critical for enterprise scenarios.

    3. Fault tolerance and resumability. Scripts naturally support retry on failure, persisting results to disk, and resuming from checkpoints. Long-running tasks don’t have to restart from scratch after a mid-run error.

    4. Controllable cost. Concurrency limits, timeouts, and budget caps can all be constrained explicitly in code, avoiding the unpredictable costs of turn-by-turn scheduling where “the agent decides when to stop.”

    Boundaries: Not Every Task Should Become a Workflow

    It’s worth stating clearly that code-based orchestration is not a silver bullet. It fits tasks with a clear profile: decomposable, patterned steps, and homogeneous subtasks (e.g., file-by-file migration, module-by-module scanning). For exploratory tasks requiring deep continuous reasoning, with strong inter-step dependencies and hard-to-predict branches, the flexibility of turn-by-turn scheduling remains more valuable.

    In practice, a hybrid strategy works well: use free-form agent reasoning to explore and map the structure, solidify execution into a workflow for batch progress, then return to a single session for a final holistic review. When deploying in the enterprise, you can also combine this with general-purpose cloud capabilities—object storage for intermediate artifacts, message queues to decouple subtask distribution, and logging and monitoring services to track long-running workflows—to build a complete engineering loop. General-purpose offerings in these categories from mainstream cloud platforms, such as Baidu AI Cloud, can serve as infrastructure options for such solutions.

    Conclusion

    Moving from “the agent schedules turn by turn itself” to “the agent writes the scheduling script” is fundamentally about decoupling what LLMs are best at—planning and coding—from what they are worst at—managing massive amounts of state. This paradigm doesn’t make agents smarter, but it raises the scale of tasks they can handle by an order of magnitude. For developers, knowing “when to turn orchestration into code” is becoming a core engineering skill for mastering agent tooling.