Extension API: Running External Processes
Part of the Extension API Guide. The coroutine-correct pattern for launching processes from tools and command handlers without freezing the agent UI.
Running External Processes
Scripts can run external processes (e.g., shell commands, CLI tools) from inside a tool { execute { } } block or a registerCommand handler. How you launch that process matters enormously โ the wrong pattern will freeze the agent UI.
The Rule: Never Block the Coroutine Dispatcher
Tool execute blocks and command handlers run as coroutines. Coroutines are scheduled across a small, shared pool of threads. If your code blocks one of those threads (by calling Thread.join(), process.waitFor(), or stream.readText() directly on the calling coroutine), the entire dispatcher stalls โ the TUI stops rendering, streaming output freezes, and the agent appears to hang.
Use processRunner โ the right tool for the job
The framework injects a ProcessRunner instance directly into every script as processRunner. It is the same singleton used by BashTool, GrepTool, and FindTool. Use it instead of rolling your own process management:
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.withTimeoutOrNull
import us.nineworlds.book.domain.process.ProcessEvent
// All three imports above are available via defaultImports โ no explicit import needed.
suspend fun runCommand(
command: List<String>,
timeoutMs: Long = 30_000L,
): Triple<Int, String, String> {
val result = withTimeoutOrNull(timeoutMs) {
val events = processRunner.run(command).toList()
val stdout = events.filterIsInstance<ProcessEvent.Stdout>().joinToString("\n") { it.text }
val stderr = events.filterIsInstance<ProcessEvent.Stderr>().joinToString("\n") { it.text }
val exitCode = events.filterIsInstance<ProcessEvent.Completed>().firstOrNull()?.exitCode ?: -1
val hasError = events.filterIsInstance<ProcessEvent.Error>().isNotEmpty()
Triple(if (hasError) -2 else exitCode, stdout, stderr)
}
return result ?: Triple(-1, "", "ERROR: timed out after ${timeoutMs / 1000}s")
}
Then call it from your execute block or command handler โ the calling coroutine suspends cleanly while the process runs:
tool {
name = "run_linter"
description = "Runs ktlint on the given file"
val file = string("file", "Path to the Kotlin file")
execute { args ->
val (exitCode, _, stderr) = runCommand(listOf("ktlint", args[file]))
if (exitCode == 0) "No lint errors" else "Lint errors:\n$stderr"
}
}
Anti-pattern โ Raw threads + waitFor on the caller
// DON'T DO THIS โ blocks the coroutine dispatcher thread
fun runTool(command: List<String>): String {
val process = ProcessBuilder(command).start()
var stdout = ""
val reader = Thread { stdout = process.inputStream.bufferedReader().readText() }
reader.start()
process.waitFor() // parks the dispatcher thread
reader.join(5000) // also blocks; silently drops output on timeout
return stdout
}
Why this hangs: process.waitFor() parks the calling thread. When all dispatcher threads are parked, no coroutine can make progress โ including the ones draining process streams. The OS pipe buffer fills, the process stalls trying to write, and everything deadlocks.
Key Points
| Anti-pattern | processRunner.run() |
|
|---|---|---|
How it runs |
|
|
|
Caller’s coroutine thread |
Dedicated |
Timeout |
|
|
UI during execution |
Frozen |
Responsive |
Output streaming |
Requires |
Line-by-line via |
Cancellation |
Manual |
|
Boilerplate |
~60 lines |
~10 lines |
Always pass an explicit path argument to filesystem tools
Some CLI tools (notably rg and grep) treat a missing path argument as "read from stdin" rather than "search the current directory". When launched via ProcessBuilder, there is no TTY attached โ so the process silently blocks forever waiting for input that will never arrive. withTimeoutOrNull will eventually cancel it, but only after burning the full timeout.
Always append an explicit path, defaulting to "." when the user has not provided one:
// BAD โ rg with no path reads stdin and blocks forever
cmd.add(pattern)
// if no path is given, nothing is appended and rg hangs
if (userPath.isNotBlank()) cmd.add(userPath)
// GOOD โ always provide a path; default to current directory
cmd.add(pattern)
cmd.add(if (userPath.isNotBlank()) userPath else ".")
This is the same convention used by the built-in GrepTool and FindTool.
One-off commands at script load time
Script-level (top-level) code runs once at startup, outside any agent turn. Short-lived, small-output commands (e.g., which rg, rg --version) are safe to run with a plain ProcessBuilder + readText() + waitFor() there โ the startup path is not a shared dispatcher thread and the output is tiny. Use processRunner.run() for everything called during agent turns.
Environment: the BOOK_FLEET marker on every child process
Every process Book spawns โ processRunner.run(), built-in tools (BashTool, GrepTool, FindTool), MCP server subprocesses โ observes BOOK_FLEET=1 in its environment (SPEC-01).
The guarantee is precise:
| Rule | Behaviour |
|---|---|
Marker export |
The child environment always contains |
Inheritance |
Everything else in the parent environment is inherited untouched; your tool’s |
Foreign markers |
Book never sets foreign harness markers ( |
Single choke point |
The export lives in one place โ |
Scripts that spawn Book child processes (e.g., fleet orchestration) can detect their own nested-Book invocations by reading BOOK_FLEET from the child environment. The live Herdr pane-restore confirmation for that scenario is a human run-book, not an automated test.