> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Dynamic Workflow

> Break the context limits of single-agent execution with Code-as-Orchestrator.

MyRM Agent's Dynamic Workflow engine is the third-generation orchestration layer, designed to solve large-scale, cross-domain complex tasks (e.g., full-repo bug scanning, large-scale code migration, multi-angle deep research) by "dispatching hundreds of sub-agents with a single sentence."

## Core Advantages

### 1. Orchestration Flexibility: Code-as-Orchestrator

We pioneered the **Code-as-Orchestrator** pattern. The LLM dynamically generates a Python orchestration script based on the task and executes it in the PTC (Programmatic Tool Calling) secure sandbox. The LLM can freely use `for` loops, `if` conditional branches, and concurrent thread pools, offering flexibility far beyond static DAG (Directed Acyclic Graph) workflows.

### 2. Fault Tolerance & Persistence: 4-Layer Durable Execution

When executing large tasks that take hours, traditional workflows crash if the network disconnects or the computer sleeps. MyRM Agent provides **4-layer persistence** that competitors cannot match: (1) `WorkflowEventStore` — SQLite durable execution cache that replays completed sub-agent results instead of re-executing them; (2) `SubagentCheckpointStorage` — full execution state snapshots (messages, tool outputs, variables, progress) with file-level locking, enabling true **breakpoint resume** after force-stop or crash; (3) Chat DB `progressSteps` — every tool execution step persisted as message metadata for post-hoc review; (4) `event_log/` — structured JSONL audit trail for compliance and debugging. Even if the network disconnects or the server restarts, the workflow can instantly recover from the breakpoint, automatically skipping completed sub-tasks and resuming interrupted sub-agents exactly where they left off.

### 3. Cost Control & Visibility: No More Hidden Bills

Dozens of sub-agents concurrently burning tokens in the background can easily generate "hidden bills." We provide **5 layers of hard budget constraints** (Token/USD/Time/Descendants/Concurrency), and offer a **Subagent Dashboard real-time topology tree** and **Live Token odometer** on the frontend. You can clearly see the progress, time spent, and cost of every concurrent sub-task. An event-driven **Staleness Probe** automatically detects when a sub-agent stops making progress — a red alert appears in the Dashboard, IM notification is pushed, and the desktop notification fires, all with zero overhead (piggybacks on existing token usage events, with a 4x tolerance multiplier during active tool calls to avoid false positives on slow but working tools). Every sub-agent streams **Real-time Proof of Work** through four parallel channels: `SUBAGENT_LOG` (live tool execution stream), `FILE_DIFF` (full diff content with one-click revert), `SUBAGENT_PROGRESS` (token/cost/ETA counters), and `ARTIFACT_CONTENT` (generated artifacts pushed instantly) — so you always know exactly what each sub-agent is doing, what it changed, and how much it costs, as it happens. The Dashboard also features **Advanced Visualization**: a **Header Summary** showing total agents, active count, failures, cumulative cost, and model distribution at a glance; **Sort & Filter** controls (sort by spawn order, cost, duration, or status; filter to running, failed, or leaf nodes); **Subtree Aggregate Badges** on every branch node showing descendant count, accumulated cost, and token usage; and a collapsible **Mini Gantt Timeline** rendering each sub-agent's execution span as a color-coded CSS bar — all GUI-native with zero backend changes and zero prompt token impact.

### 4. Heterogeneous Model Ensemble: Intelligent Routing

Within the same workflow, the system automatically dispatches simple "data collection" sub-tasks to cheap and extremely fast models (like DeepSeek V3), while assigning core "logical summarization" tasks to the strongest reasoning models (like Opus/GPT-4o). While ensuring output quality, it helps you reduce running costs by 10x to 60x.

### 5. Closed-Loop Verification: Physical Sandbox Evidence

When a sub-agent says "code modification complete," the system forces a "read-only verifier" to be spawned, truly running `npm test` or compilation commands in the sandbox. Only when real physical execution success evidence is obtained is the task considered truly complete. We reject LLM hallucinations and deliver absolutely reliable results.

### 6. Background Task Auto-Wake: "Done? Report Back!"

When you dispatch a long-running background sub-agent (e.g., a full-repo refactoring task), the main Agent doesn't just sit idle — it automatically wakes up and continues when the background task completes. The **AsyncWakeupHandler** protocol bridges the Harness framework and the Server layer: upon sub-agent completion, the result is injected into chat history, and a headless Agent run is automatically triggered with 3 retries, exponential backoff, and daily budget protection. Combined with the **Kanban Dispatcher** (heartbeat monitoring, zombie detection, scheduled wakeup) and **6 idle maintenance tasks** (memory consolidation, cognitive derivation, context compaction, etc.), MyRM Agent achieves true "fire-and-forget" autonomous operation. If the server restarts, **OfflineDurableTask** automatically resumes interrupted tasks from the database checkpoint. When a background task finishes while you're away, the **Offline Guardian** precisely distinguishes success from failure — dual-insurance detection (SSE error chunk matching + semantic error flag) ensures you see "Task Completed" or "Task Failed" with a click-to-chat link, never a misleading generic notification.

### 7. Optional Path Guard: Graceful Degradation for Non-Critical Steps

In complex DAG plans, not every step is equally important. MyRM Agent supports **`allow_failure` declarative fault tolerance** at the individual step level — mark any step as non-critical, and if it fails (even after 3 automatic retries), it gracefully degrades to `skipped` status instead of `failed`. Downstream steps that depend on it continue executing normally, and the overall task can still succeed.

**Real-world example:** In a multi-source research task, one search engine API is rate-limited and fails. Instead of aborting the entire research, MyRM skips that source, continues with the remaining sources, and delivers a complete report. Competing frameworks would abort the entire DAG on any single step failure.

This capability is unique to MyRM — no competing framework (Claude Code, CrewAI, Dify, OpenHands, Hermes) supports DAG node-level `allow_failure` declarations. The result: **30%+ higher task success rates** in multi-step workflows compared to all-or-nothing competitors.

### 8. One-Click Workflow Toggle: Smarter Than Ultra Mode

OpenAI's GPT-5.6 Sol introduced "Ultra Mode" — a one-click toggle that runs 4 agents in parallel, trading higher token costs for faster results. MyRM's **WorkflowModeToggle** provides equivalent one-click activation, but with significant advantages:

|                         | OpenAI Ultra                  | MyRM Workflow Mode                                                                 |
| ----------------------- | ----------------------------- | ---------------------------------------------------------------------------------- |
| **Orchestration**       | Fixed 4 parallel agents       | LLM dynamically decides parallelism and strategy                                   |
| **Persistence**         | None                          | 4-layer persistence (SQLite + Checkpoint + Chat DB + JSONL) with breakpoint resume |
| **Cost safety**         | None (3-5x cost, no controls) | Budget fuse-breaker + auto-reset after send                                        |
| **Progress visibility** | Black box                     | 4 SSE event types + categorized progress bars                                      |
| **Result synthesis**    | Simple merge                  | 4-level confidence classification (✅/⚠️/❌/💥)                                      |
| **Orchestration modes** | 1 (fixed parallel)            | 4 primitives (delegate/batch/swarm/workflow)                                       |

The toggle automatically resets after sending to prevent accidental high-cost follow-up messages — a safety mechanism OpenAI Ultra lacks.

### 9. Planning Guardrails: Focused Execution, Not Runaway Planning

When LLMs plan multi-step tasks, two failure modes are common: **over-planning** (generating 50+ trivial plan items, wasting tokens) and **multi-focus drift** (marking 3-5 tasks as "in progress" simultaneously, completing none).

MyRM's `todo_write` tool enforces hard guardrails at the code level:

* **MAX\_TODOS = 20**: Prevents planning explosion. When exceeded, a clear error guides the LLM to merge or simplify.
* **Single in\_progress enforcement**: Only one task may be actively worked on at a time. If the LLM violates this, the system **intelligently corrects** (reverts older in\_progress items to pending, keeps the latest) and provides a feedback note explaining the correction.
* **Correction over rejection**: Unlike hard rejections that disrupt flow, intelligent correction keeps the workflow moving while teaching the LLM to self-correct in subsequent turns.

This is a code-enforced constraint, not a prompt-level suggestion — behavior is consistent regardless of which LLM model or provider is used.

### 10. Single Agent Gatekeeping: Simple by Default, Powerful on Demand

MyRM defaults to a focused single-agent experience — `suggestWorkflowMode` is **off by default**. The system silently handles most tasks with one agent, delivering fast, predictable responses with zero orchestration overhead. Users never see workflow suggestions unless they explicitly opt in.

For power users who want proactive multi-agent suggestions, a single toggle in **Settings → Preferences → Advanced** enables the detection engine:

* **Zero LLM cost**: Detection uses pure regex-based scoring on the query structure (numbered lists, parallel keywords, multi-goal markers).
* **Non-blocking**: The suggestion appears as an inline card in the chat stream; the current response is never interrupted.
* **User control**: Accept (enables workflow for next message), dismiss (hides card), or turn the toggle back off.
* **Conservative by design**: Only triggers when the ComplexityRouter classifies the task as `reasoning` tier AND the decomposability score meets a strict threshold (≥4/7).
* **Backward compatible**: Existing users who previously had `suggestWorkflowMode: true` saved in their settings keep their preference — no silent behavior change on upgrade.

**Why single-agent first?** As Bret Taylor (Sierra CEO, former Salesforce CEO) articulated: the best multi-agent systems present as a single agent to the user. Multi-agent orchestration is an implementation detail, not a product surface. MyRM is the only platform that has full multi-agent DAG orchestration capability **and** deliberately suppresses it by default — ensuring new users get the simplest, fastest experience while experts retain full control.

No competing product — including Claude Code, OpenClaw, Hermes, DeerFlow, CoPaw, or Lobe-Chat — offers configurable workflow mode suggestion. They either always show it (adding noise) or never offer it (missing opportunities).
