# Dynamic Workflows

> Dynamic Workflows let CodeBuddy write a JavaScript orchestration script that the runtime executes in the background to coordinate dozens or even hundreds of subagents on a task. The script itself is readable, editable, and rerunnable, making it suitable for codebase audits, large migrations, and research tasks that require cross-validation.

<Note>
Dynamic Workflows are currently a research preview and require CodeBuddy Code v2.105.0 or later. They are enabled by default; to turn them off, toggle "Dynamic workflows" in `/config`.
</Note>

A Dynamic Workflow is a JavaScript script that CodeBuddy writes on the spot for your task. The runtime executes it in the background while your session stays responsive. The script contains one or more [`agent()`](#script-api) calls; each call dispatches an independent subagent to work. After the script receives intermediate results, it can branch, run work in parallel, or dispatch the next batch of subagents.

Use a Workflow when a task is too large to fit in a single session, or when you want the orchestration logic recorded as a rerunnable script. Typical scenarios include:

- Whole-monorepo audits of API contracts, authentication, or instrumentation
- Batch triage and ownership assignment for a group of issues
- Research that needs cross-validation across multiple repositories or sources
- A plan worth drafting from several independent angles first, then comparing them to pick the best option

This page covers:

- [When to Use a Workflow](#when-to-use-a-workflow) (tradeoffs with subagents / Skills / Agent Teams)
- [Running a Built-in Workflow](#running-a-built-in-workflow): `/deep-research`
- [Asking CodeBuddy to Write a Workflow](#asking-codebuddy-to-write-a-workflow), and saving it for reuse
- [How Workflows Run](#how-workflows-run) and [Run Management](#run-management)

## When to Use a Workflow

[Subagents](sub-agents.md), [Skills](skills.md), [Agent Teams](agent-teams.md), and Workflows can all run multi-step tasks. The difference is “who holds the plan”:

|                       | Subagents                       | Skills                    | Agent Teams                       | Workflows                       |
| :-------------------- | :------------------------------ | :------------------------ | :-------------------------------- | :------------------------------ |
| Essence               | Workers dispatched by CodeBuddy | Instructions CodeBuddy follows | A leader supervising a group of peer sessions | A script executed by the runtime |
| Who decides what happens next | CodeBuddy, deciding each round | CodeBuddy, following the prompt | Leader agent, deciding each round | The script |
| Where intermediate results live | CodeBuddy’s context window | CodeBuddy’s context window | Shared task list | Script variables |
| What is reusable      | Worker definitions              | The instructions themselves | The team definition               | The orchestration process itself |
| Scale                 | A small number of delegations per round | Same as subagents | A few peers running long tasks     | Dozens to hundreds of agents in a single run |
| Interruption          | Start another round             | Start another round        | Teammates keep running             | Can resume within the same session |

Workflow moves the “plan” into code. With subagents / Skills / Agent Teams, CodeBuddy is the orchestrator: every round, it decides whom to dispatch and what to do next, and all results go into the context window. With Workflow, loops, branches, and intermediate results are managed by the script itself, leaving only the **final answer** in CodeBuddy’s context.

Turning the plan into code has another benefit: the script can apply a **repeatable quality pattern**, not just dispatch more agents. For example, you can have several agents adversarially review each other’s findings before reporting, or draft plans from multiple angles at the same time and compare them before choosing the best one. The credibility of a single result can be much higher than a “one-pass” answer.

## Running a Built-in Workflow

The fastest way to experience Workflow is to run `/deep-research`, CodeBuddy Code’s built-in “multi-source cross-validation research” workflow. In the session, you will see agents progress through phases in the background. When it finishes, you receive only a synthesized report instead of a long sequence of round-by-round conversations.

### Steps

1. **Start the Workflow**

   Run `/deep-research` with a research question. It searches, fetches, and cross-validates sources from multiple angles in parallel, then synthesizes a cited report.

   ```text
   /deep-research Compare how mainstream frontend monorepo tools (Turborepo / Nx / Lerna) have evolved over the past year in remote caching and task graphs
   ```

2. **Approve the Run**

   CodeBuddy Code asks whether to allow this Workflow to run. Choose **Yes** to continue. The exact prompt depends on your [permission mode](iam.md#permission-system). See [Pre-Run Plan Approval](#pre-run-plan-approval).

3. **Watch Progress**

   The run starts in the background. Use `/workflows` to open the Workflows view, select this run with the arrow keys, and press Enter to enter the progress page:

   ```text
   /workflows
   ```

   The progress page shows “phases”. Each phase displays the agent count, total tokens, and elapsed time. Drill into any phase to view each agent’s prompt and output. See [Watching a Run](#watching-a-run) for the full shortcut list.

   You can also see a one-line progress summary directly in the task panel below the input box. Press the ↓ arrow key to move focus to the task panel, then press Enter to expand it.

4. **Read the Report**

   When the run finishes, the report is automatically returned to the session. Every major claim includes cited sources, and claims that fail cross-validation are removed.

To apply Workflow to your own task, first [ask CodeBuddy to write one](#asking-codebuddy-to-write-a-workflow). When a run produces satisfying results, you can [save it as a command](#saving-a-workflow-for-reuse).

### Built-in Workflow

CodeBuddy Code includes the following Workflow:

| Command                       | Purpose                                                                                                                                                                                                        |
| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/deep-research <question>`   | Searches, fetches, and cross-validates sources from multiple angles in parallel, votes on each claim, removes parts that fail validation, and outputs a cited report. Requires the [WebSearch tool](tools-reference.md#websearch-tool-behavior) to be available. |

[Workflows you save yourself](#saving-a-workflow-for-reuse) are registered as commands in the same way and appear together with built-in Workflows in `/` autocomplete.

### Watching a Run

Workflow runs in the background and the session stays responsive. At any time, `/workflows` can list active / completed runs. Select one to enter the progress view.

```text
/workflows
```

The progress view is organized by phase. Each phase shows the agent count, total tokens, and elapsed time. The bottom status bar lists all shortcuts:

| Key           | Action                                                                                           |
| :------------ | :----------------------------------------------------------------------------------------------- |
| `↑` / `↓`     | Select a phase or agent                                                                          |
| `Enter` or `→` | Drill into the selected phase, then drill into an agent to read its prompt, recent tool calls, and final result |
| `Esc`         | Go back one level                                                                                |
| `j` / `k`     | Scroll when agent details overflow                                                               |
| `p`           | Pause or resume the run                                                                          |
| `x`           | Abort the selected agent; abort the entire Workflow when focus is on the run                      |
| `r`           | Restart the selected running agent                                                               |
| `s`           | [Save](#saving-a-workflow-for-reuse) the current run’s script as a command                        |

## Asking CodeBuddy to Write a Workflow

There are two ways to ask CodeBuddy to write a Workflow for your task:

- [Ask for a Workflow in your prompt](#asking-for-a-workflow-in-your-prompt): use natural language or the keyword `ultracode`, and CodeBuddy will write one for this task.
- [Let CodeBuddy decide (ultracode mode)](#ultracode-mode-let-codebuddy-decide): `/effort ultracode` sets the effort level to ultracode, and CodeBuddy will first plan every substantial task in the session as a Workflow.

You can also run an existing Workflow command directly, such as the built-in `/deep-research` or one you have [saved](#saving-a-workflow-for-reuse).

### Asking for a Workflow in Your Prompt

If you do not want to change the whole session’s effort level and only want one task to use Workflow, add the keyword `ultracode` to your prompt. Natural language such as “run this with a workflow” or “use a workflow” has the same effect: CodeBuddy treats direct requests as an equivalent explicit opt-in.

```text
ultracode: scan every domain under packages/ to find which Facade / CloudRepo methods lack unit tests, and rank them by risk
```

CodeBuddy Code highlights the keyword in your input. After CodeBuddy receives this prompt, it writes a Workflow script for the task instead of working round by round. If you do not want to trigger Workflow, press `Option+W` on macOS or `Alt+W` on Windows / Linux to remove the highlight for this prompt; or place the cursor after the keyword and press Backspace to delete it. To disable keyword triggering entirely, turn off “Ultracode keyword trigger” in `/config`.

If the result meets your needs, you can [save it as a command](#saving-a-workflow-for-reuse) afterward.

If you already have an orchestrator built in another way (a folder of subagent prompts or a Skill that dispatches tasks), you can ask CodeBuddy to inspect it and write an equivalent Workflow.

### Ultracode Mode: Let CodeBuddy Decide

Ultracode is a combined CodeBuddy Code configuration: it raises [reasoning effort](models.md#adjusting-reasoning-effort) to `xhigh` and adds automatic Workflow orchestration. After it is enabled, CodeBuddy proactively decides which tasks are worth running as Workflows; you do not need to remind it every time.

```text
/effort ultracode
```

After entering ultracode, a request may be split into multiple consecutive Workflows: one run to inspect the current code, another run to implement changes, and another run to verify them. **Every** task in the session follows this pattern. Each request consumes significantly more tokens than lower effort levels and also takes longer.

ultracode only applies to the current session and automatically resets in a new session. Use `/effort high` to return to daily work. It is only available on models that support `xhigh` [reasoning effort](models.md#adjusting-reasoning-effort); unsupported models do not show this option in the `/effort` menu.

### Pre-Run Plan Approval

In the CLI, each launch prompts for confirmation before running:

- **Yes**: start the run
- **Yes, and don't ask again this session**: start the run and stop asking about Workflow tools for the rest of the current session (session-scoped only; new sessions ask again)
- **No**: cancel (you can also press `Esc`)

Whether this prompt appears depends on your [permission mode](permission-modes.md):

| Permission mode                            | When it asks                                                                                                                   |
| :----------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
| Default, Accept edits, Auto                | Every time, unless you have selected **Yes, and don't ask again this session** during the current session. The prompt is skipped entirely when ultracode is enabled |
| Bypass permissions, `codebuddy -p`, Agent SDK | Never asks; the run starts directly                                                                                         |

Permission mode only affects this **pre-launch** prompt. Subagents dispatched by Workflow always run in `acceptEdits` mode and inherit your [tool allowlist](settings.md#permission-settings), regardless of the current mode of your session. File edits are auto-approved.

Shell commands, Web Fetch, and MCP tool calls that are not on the allowlist may still ask during the run. To avoid interruptions during long tasks, add the commands agents will need to the allowlist before starting.

`codebuddy -p` and Agent SDK do not have human-interaction entry points. Tool calls follow your configured permission rules, without interactive confirmation.

### Saving a Workflow for Reuse

When a Workflow is something you will run repeatedly (for example, a review process you run on every branch), save its script as a command.

In `/workflows`, select the run you want to keep, press `s`, and press `Tab` in the save dialog to switch between two save locations:

- Project `.codebuddy/workflows/`: distributed with the repository and visible to everyone on the team
- User directory `~/.codebuddy/workflows/`: available in all projects and visible only to you

Press Enter to save. After that, invoke it in any session with `/<name>`.

If a project-level Workflow and a user-level Workflow have the same name, the **project-level** Workflow takes precedence.

### Passing Arguments to a Saved Workflow

Saved Workflows receive input through `args`. In the script, this is a global variable named `args`. This lets you pass research questions, target path lists, configuration objects, and more without editing the script each time.

The following prompt triggers a saved Workflow and passes an issue list as arguments:

```text
> Use /review-branch to run an architecture review on each of the last 20 commits on feat/skills-center
```

CodeBuddy passes the list as structured data, so the script can directly use array / object methods on `args` without parsing it manually. If the caller does not pass `args`, then `args` is `undefined` in the script.

## How Workflows Run

The runtime executes the script in an isolated environment that is completely separate from your session. Intermediate results remain in script variables and do not enter CodeBuddy’s context.

Each run writes the script to a file under the session directory (`~/.codebuddy/projects/<session>/`). CodeBuddy receives that path when the run starts, so you can ask it “where is the script”. Open it to read CodeBuddy’s orchestration logic, diff it against the previous run, or edit it and ask CodeBuddy to restart with the edited version.

The runtime continuously records each agent’s result. This is the foundation for [resuming](#resuming-a-run-after-pause) a run within the same session.

### Behavior and Limits

The runtime enforces the following constraints:

| Constraint                                                           | Reason                                                                                                                    |
| :------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
| No user input is accepted while running                              | The only thing that can pause a run is an agent permission prompt. If you need sign-off between phases, split each phase into an independent Workflow |
| The Workflow itself has no direct filesystem / Shell access          | File reads/writes and command execution are always done by agents; the script only coordinates agents                     |
| At most 16 concurrent agents at a time (fewer on machines with fewer CPU cores) | Limits local resource usage                                                                                              |
| At most 1000 agents in a single run                                  | Prevents runaway loops in scripts                                                                                         |

### Deterministic Sandbox

The runtime enforces determinism to avoid different results when the same script runs twice (also a prerequisite for [resume cache hits](#resuming-a-run-after-pause)). The sandbox rejects the following nondeterminism / arbitrary code generation APIs (compile-time scanning + runtime interception):

- Time-related APIs: `Date.now()`, `new Date()`, `performance.now()`
- Random numbers: `Math.random()`
- Arbitrary code generation: dynamic string evaluation and dynamic Function construction (`codeGeneration.strings` is disabled in the sandbox)
- Node globals: `require` / `process` / `__dirname` / `Buffer` are not visible inside the sandbox

When you need timestamps or random numbers, use `agent()` to have a subagent fetch real information (search, read files, call APIs), and “package” the nondeterminism into the agent’s result.

### Script API

The script is a self-contained JavaScript module and can use the following global functions:

| Global                        | Purpose                                                                                                                               |
| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| `agent(prompt, options?)`     | Dispatches a subagent to execute `prompt` and returns its result. `options` can specify `tools` / `maxTurns` / `schema` (structured output) / `model`, and more |
| `parallel(items, options?)`   | Fans out over `items` in parallel. Equivalent to `Promise.all`, but constrained by the 16-agent concurrency limit                     |
| `pipeline(items, options?)`   | Runs sequentially, passing the previous segment’s result to the next segment; when any segment fails, the remaining segments return `null` |
| `phase(name, body)`           | Marks an orchestration block as a phase. The progress view aggregates display by phase. `body` can be a sync or async function        |
| `log(...)`                    | Writes a timestamped log entry, which appears in the progress view’s Run log                                                          |
| `args`                        | Arguments passed by the caller (see [Passing Arguments to a Saved Workflow](#passing-arguments-to-a-saved-workflow))                  |
| `workflow(name, args?)`       | Calls a **saved** Workflow as a nested Workflow (only exposed to the parent; child Workflows do not expose this hook again, and deep nesting is forbidden) |

## Run Management

After a run starts, manage it from the `/workflows` view. You can also expand the progress row in the task panel below the input box.

### Resuming a Run After Pause

If you paused a run, you can resume it: completed agents return cached results directly, and the remaining work continues. Select the paused run in `/workflows` and press `p` to resume; you can also ask CodeBuddy to restart the run with the same script.

Resume is limited to **the same CodeBuddy Code session**. If you exit CodeBuddy Code while a Workflow is still running, the next session starts from the beginning.

### Cost

Workflow dispatches many agents, so the token cost of a single run can be much higher than doing the same task conversationally. These costs count toward your plan limits.

To estimate cost before starting a large task, run it on a small slice first: one directory instead of the entire repo, or one specific question instead of a broad topic. Each agent’s token usage is visible in real time in the `/workflows` view, and you can press `x` to abort a run at any time without losing completed results. The runtime’s [agent limits](#behavior-and-limits) also cap the maximum cost of a single run to prevent runaway scripts.

By default, each agent uses the current session model, unless the script explicitly routes a phase to another model. You can control cost in several ways:

- Run `/model` before large tasks to check the current model. If you usually switch to a cheaper model, remember to switch back or intentionally keep it
- When describing the task, proactively tell CodeBuddy: “use a cheaper model for phases that do not need the strongest model”

### Disabling Workflow

Workflow is available in the CLI, desktop app, IDE extension, `codebuddy -p` headless mode, and [Agent SDK](sdk.md). The way to disable it is the same across all forms.

Disable it only for yourself:

- Turn off “Dynamic workflows” in `/config`. This persists to settings
- Set `"disableWorkflows": true` in `~/.codebuddy/settings.json`. This persists
- Set the environment variable `CODEBUDDY_DISABLE_WORKFLOWS=1`. It is read at startup and takes effect wherever it is set

Disable it for the whole organization: set `"disableWorkflows": true` in [managed settings](settings.md#enterprise-managed-policy-settings).

After disabling, built-in Workflow commands are unavailable, the keyword `ultracode` no longer triggers Workflow, and the `/effort` menu no longer shows the ultracode option.

## Related Resources

- [Subagents](sub-agents.md): the underlying “worker” primitive orchestrated by Workflow
- [Agent Teams](agent-teams.md): another multi-agent collaboration model, where a leader agent manages the plan
- [Skills system](skills.md): turn “instructions” into reusable Skills
- [Reasoning effort adjustment (including ultracode)](models.md#adjusting-reasoning-effort)
- [Hooks system](hooks-guide.md): attach hooks to tool calls and session events
