Skip to content

[Feature]: Headless dispatch (--headless) — spawn CLI agents as subprocesses instead of creating terminals #9951

Open

Description

@Disorrder

Problem

The coordinator dispatches tasks by creating interactive terminals and pasting preambles into them via bracketed paste (sendTerminalAgentPrompt). This requires:

  1. A recognized TUI agent running in the terminal (agent detection via title/process/explicit status)
  2. The agent to support bracketed paste input
  3. The terminal to stay alive between tasks

This creates unnecessary coupling: the coordinator depends on terminal infrastructure, agent detection, and TUI compatibility — none of which are needed for the actual task execution.

Real-world failure

Running orchestration run with agents like qwen-code (which IS in TUI_AGENT_CONFIG) fails because:

  • terminal create --command "qwen" → agent not recognized by getTerminalAgentStatus() (title detection misses "Qwen", process detection sees node not qwen)
  • dispatch --inject → "no recognized agent detected"
  • Coordinator pastes preamble into bare shell → zsh: parse error near ')'

The root problem: the coordinator assumes every worker is an interactive TUI agent in a visible terminal. But most CLI agents (qwen, codex, claude, aider) support a one-shot prompt mode (-p "prompt") that runs a task and exits — no terminal, no TUI, no paste needed.

Proposed solution: process-based dispatch (--headless)

Add an alternative dispatch strategy: spawn a CLI process with the preamble as a prompt argument, instead of creating a terminal and pasting into it.

Current:  coordinator → createTerminal() → paste preamble → agent TUI → worker_done
Proposed: coordinator → spawn("qwen", ["-p", preamble]) → worker_done

CLI interface

orca orchestration run \
  --spec "..." \
  --agent qwen-code \
  --headless \
  --max-concurrent 4 \
  --worktree active

--headless switches dispatch from terminal+paste to process spawn. Without it, current behavior is preserved (backward compatible).

The --agent flag resolves the agent's launchCmd from TUI_AGENT_CONFIG (e.g., qwen-code → qwen) and the prompt flag (e.g., -p).

How it works

  1. Coordinator generates the preamble (same buildDispatchPreamble() as today)

  2. Instead of createTerminal() + sendTerminalAgentPrompt(), spawn a child process:

    const child = spawn(agentCommand, [promptFlag, preamble], {
      cwd: worktreePath,
      env: { ...process.env, ORCA_TERMINAL_HANDLE: syntheticHandle },
      stdio: ["ignore", "pipe", "pipe"],  // capture stdout/stderr for logging
    });
  3. The agent process runs the task, calls orca orchestration send --type worker_done (same CLI commands as today — the process is alive during execution)

  4. The process exits → coordinator detects exit via child.on("exit") or worker_done message

  5. For the next task, spawn a new process

What still works (no changes needed)

  • worker_done: the agent calls orca orchestration send --type worker_done ... — works from any process with orca on PATH
  • heartbeat: orca orchestration send --type heartbeat ... — works, process is alive during execution
  • escalation: orca orchestration send --type escalation ... — works
  • Preamble: same buildDispatchPreamble() output, passed as -p argument instead of paste

Trade-offs and downsides

1. No interactive question flow (key downside)

In terminal mode, the user can see the agent's question in the terminal and respond immediately. In headless mode, there is no visible terminal — the user does not see the question in real time.

The ask mechanism still works technically: the agent runs orca orchestration ask --question "..." --timeout-ms 600000, which sends a decision_gate message and blocks the process. The coordinator receives the gate and marks the task as blocked. But the user must discover and resolve it asynchronously:

# User checks for blocked tasks periodically:
orca orchestration gate-list --status pending

# User resolves the gate:
orca orchestration gate-resolve --id <gate_id> --resolution "Use approach A"

# The agent's `ask` command unblocks and continues

Proposed mitigation: when a headless worker hits a decision gate, the coordinator should:

  • Log the question prominently (with task ID, question text, and options)
  • Optionally emit a system notification (macOS osascript, desktop notification)
  • The task stays blocked with the gate pending until the user resolves it
  • If the ask times out (default 10 min), the agent should send worker_done with a failure summary describing the unresolved question, so the task can be retried after the user provides guidance

This is fundamentally different from terminal mode where the interaction is synchronous and visual. Headless mode trades interactivity for autonomy — suitable for well-specified tasks that don't need mid-execution decisions.

2. No real-time visibility

Terminal mode lets the user watch the agent work in real time. Headless mode has no visible output.

Mitigation: redirect stdout/stderr to log files (e.g., .qwen/worker-logs/<task_id>.log). The user can tail -f if they want to watch a specific worker.

3. Debugging after failure

In terminal mode, the terminal buffer retains the agent's output for post-mortem inspection. In headless mode, the process is gone.

Mitigation: same log files as above. The coordinator should preserve logs for failed tasks and include the log path in the failure summary.

4. Why TUI/terminal mode is still useful

Terminal mode remains the better choice when:

  • Tasks require interactive decision-making (frequent ask calls)
  • The user wants to observe and steer the agent in real time
  • Debugging agent behavior requires inspecting the live terminal
  • The agent does not support a one-shot -p mode

Headless mode is optimized for autonomous, well-specified tasks where the agent can work independently and report results via worker_done.

Summary table

Terminal + paste Headless (process spawn)
Agent detection Required Not needed
Bracketed paste Required Not needed
Terminal lifecycle Must manage Process exits naturally
Agent compatibility Only recognized TUI agents Any CLI with -p flag
Interactive questions Synchronous, visual Asynchronous via gates
Real-time visibility Terminal window Log files
Memory N processes stay resident N processes, exit after task
Cold start Once per terminal Per task (~2-3s)
Best for Interactive, exploratory tasks Autonomous, well-specified tasks

Implementation sketch

In coordinator.ts, dispatchReadyTasks():

if (this.opts.headless) {
  const preamble = buildDispatchPreamble({ taskId, dispatchId, taskSpec, ... });
  const agentConfig = TUI_AGENT_CONFIG[this.opts.agent];
  const logPath = path.join(worktreePath, ".qwen/worker-logs", `${taskId}.log`);
  const logStream = fs.createWriteStream(logPath);
  const child = spawn(agentConfig.launchCmd, [agentConfig.promptFlag ?? "-p", preamble], {
    cwd: worktreePath,
    stdio: ["ignore", "pipe", "pipe"],
  });
  child.stdout?.pipe(logStream);
  child.stderr?.pipe(logStream);
  this.state.activeProcesses.set(task.id, { pid: child.pid, child, logPath });
  child.on("exit", (code) => {
    if (code !== 0 && !this.state.completedTasks.includes(task.id)) {
      this.opts.onLog(`Worker ${task.id} exited with code ${code}. Log: ${logPath}`);
    }
  });
} else {
  // Terminal-based: existing paste logic (unchanged)
}

Related

Activity

  1. changed the title [-][Feature]: Process-based dispatch — spawn CLI agents as subprocesses instead of creating terminals[/-] [+][Feature]: Headless dispatch (--headless) — spawn CLI agents as subprocesses instead of creating terminals[/+] on Jul 22, 2026
  2. Disorrder commented on Jul 22, 2026

    @Disorrder
    Author

    I can propose a PR later

  3. added
    enhancement
    on Jul 27, 2026
  4. pablontiv commented on Aug 3, 2026

    @pablontiv

    Overlapping outcome, different mechanism. Filed #12360: orchestration worker-start has no per-dispatch way to set the launched agent's permission flags, so a worker inherits the global settings.agentDefaultArgs and stops at an interactive approval prompt whenever that global is empty.

    A --headless one-shot subprocess sidesteps that failure entirely, since there is no TUI to prompt in. Recorded it in #12360 as the closest alternative solution rather than a competing one.

    Disposition: complementary, neither blocks the other. Headless dispatch does not help a dispatch that wants a real supervised terminal, and a per-dispatch permission surface does not reduce the case for headless dispatch.

  5. vladsafedev commented on Aug 6, 2026

    @vladsafedev

    I've built this dispatch mechanism as a standalone CLI (playmaker) that runs claude/codex/antigravity/opencode as detached one-shot processes and tracks them. I've been using it daily for my own work, and a few details are directly relevant to the design sketched here. Can turn this into a PR.

    Behavior below verified against claude 2.1.201, codex 0.144.1, and agy 1.1.10.

    1. Spawn in stream mode, not plain -p to get the session id in a second.
      The proposal spawns [promptFlag, preamble] and waits for exit. Slightly better: most agents have a streaming one-shot mode that emits the session id as an early event, which the coordinator needs for tracking and resume:
    • claude -p --output-format stream-json --verbose → first JSONL event carries session_id (note: --verbose is mandatory with stream-json, otherwise claude errors out)
    • codex exec --json → emits a thread.started event with the thread id in ~1s (also: --output-last-message <file> gives you the final assistant message cleanly, no stdout scraping)
    • Antigravity (agy -p) is the hard case: plain-text stdout, no JSON envelope, and the conversation id never hits stdout at all — it's recoverable a few seconds in from the debug log (--log-file, the Created conversation <uuid> line). The design should tolerate ids arriving late or via side channels.
    1. Resume replaces "keep the terminal alive between tasks".
      The issue notes the terminal must stay alive between tasks. Headless removes that constraint entirely: for the next task, resume the same session in a new process — claude -p --resume <session_id> / codex exec resume <thread_id> / agy --conversation <uuid> -p. Codex re-emits thread.started with the same id on resume, and an unknown id fails fast with a no rollout found error rather than silently starting a new thread. Coordinator keeps conversational continuity with zero live processes between tasks.

    2. Permission flags are load-bearing in headless, not a nicety (ties into [Feature]: orchestration worker-start needs a per-dispatch agent permission surface #12360).
      With no keyboard attached, a default-mode claude doesn't fail loudly — it completes "successfully" (exit 0, result subtype success) having changed nothing, with a final message asking for permission. So --headless needs per-dispatch permission args to be usable at all:

    • claude: --permission-mode acceptEdits (+ optional --allowedTools A,B — comma-separated, the variadic form swallows the prompt) or --dangerously-skip-permissions
    • codex: codex exec never prompts — it's non-interactive by design; gating happens in its sandbox instead (-s / config; the stock default is read-only, so set workspace-write for edit tasks unless your config already does)
    • A sensible default that's served me well: agent free inside the worktree cwd, refused outside it (acceptEdits)
    1. Exit code ≠ outcome; the result event is richer anyway.
      claude's final result event carries total_cost_usd, duration_ms, and usage — free telemetry for the dispatch UI. Worth parsing instead of relying on exit + worker_done alone.

    2. Transcripts exist on disk even without a terminal.
      Every agent writes native session files (claude: ~/.claude/projects/<cwd-with-slashes-as-dashes>/<session-id>.jsonl; codex: rollout-*-<thread_id>.jsonl under ~/.codex/sessions/YYYY/MM/DD/; agy: transcript_full.jsonl under ~/.gemini/antigravity-cli/brain/<conversation-id>/). A headless thread in the sidebar can render the live transcript from these instead of showing nothing where the terminal would be.

    playmaker's per-agent adapters (src/playmaker/agents/) are a working reference for all of the above — spawn args, stream parsing, session-file discovery, resume — one file per agent, MIT.

    I'm glad to open a PR implementing --headless along these lines if the approach looks right to maintainers.

  6. 0xAlbertChen commented on Nov 30, 2026

    @0xAlbertChen

    Strong +1. Headless dispatch is extremely important for scaling Orca beyond interactive development workflows.

    For unattended orchestration, creating a terminal, detecting the agent, injecting a prompt, and inspecting terminal output introduces unnecessary complexity and failure points.

    We are targeting a multi-host fleet with up to 100 concurrent agent seats.

    Where providers officially support non-interactive execution, Orca should offer a process-based or structured-protocol dispatch mode with:

    • Explicit process and dispatch identities.
    • Structured startup confirmation.
    • Machine-readable execution status.
    • Reliable stdout/stderr capture.
    • Completion receipts and exit classifications.
    • Session recovery where supported.
    • Automatic resource cleanup.
    • Per-dispatch account, model, effort, and permission settings.

    Interactive terminals should remain available for human-operated agents, but automated workers should not require visible terminals.

    This would improve reliability, reduce resource consumption, and make Orca much more suitable as a headless execution platform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementorchestration

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions