fix(sdk,kernel): run authored agents in parallel under --local-agent
Problem
An authored (TypeScript) flow could not run agents in parallel. Three separate defects stood in the way:
- The second agent parked.
flows run --local-agentattached one agent worker and one LLM worker, each withcapacity: 1(local-agent.ts). A second agent/LLM step that became ready while the first was running found no free worker. The kernel parked it, and the authored executor treated the park as a failure (agent_parked). Cloud runs v2 flows through this same--local-agentpath, so the same limit applied there. f.agent({ cwd })was refused. The SDK threadedcwdinto the step spec (#357/#358), but the kernelStepSpechad no such field:invalid_spec: unknown field "cwd". Withoutcwd, every agent shares the process directory, andworker-cli.tsruns agents that share a directory one at a time (on purpose, so each file change is credited to the right step). So even with more capacity, agents still took turns.- Long parallel runs crashed at the end. The authored completion gate was super-linear.
aggregatesForre-walked promise ancestry pairwise, andsettledFrom/inFlightFromscanned every tracked promise once per operation. On a 20-minute, 114-step run it blocked the event loop for about 180s after the body returned, so lease-renewal timers never fired. The run then endedcrashedwithlease_conflict: attempt has no active worker lease.
Changes
acddf5dc— capacity and queuing- The local agent and LLM workers now default to
DEFAULT_LOCAL_AGENT_CAPACITY = 4. - New flag
--agent-capacity <n>(1–32) onflows runandflows resume. It is refused without--local-agent, with--cloud, or when given twice. - New
worker-slots.ts, a FIFO limiter. The authored executor now waits in-process for a free slot instead of overbooking the worker and parking.
- The local agent and LLM workers now default to
ab065fcb— kernelcwd- Agent steps take an optional absolute
cwd, which is passed to the worker the same waymodelis. - A relative path is refused (
RelativeStepCwd).llmsteps still refuse the field. - Specs without
cwdserialize and hash exactly as before; the hash is pinned in a test. f.agentresolves a relativecwdagainst the flow before sending it.
- Agent steps take an optional absolute
3985c270— near-linear completion gate- New
promise-ancestry.tsworks out which invocations each group member depends on, for all members in one pass. It collapses cycles with Tarjan's algorithm and propagates the answer as bitsets. rootsInFlight()/settledWithRoots()replace the per-operation scans.- The
dependenciesOfcache is now keyed by graph version; before, it could return a walk from before the graph grew.
- New
Evidence
Gate cost (synthetic task-graph flow, real daemon), time from body return to run completion:
| steps | before | after |
|---|---|---|
| 42 | 185 ms | 20 ms |
| 162 | 5 740 ms | 40 ms |
| 322 | not measured | 97 ms |
| 162 × 2s steps | 4 468 ms | 92 ms |
End-to-end with real Claude agents (examples/task-graph, 4-subtask diamond plan, --local-agent, fresh daemon on this kernel):
agent-4 cwd=slugify + 5.2s -> + 42.3s success
agent-6 cwd=truncate + 10.7s -> + 45.7s success ← overlaps slugify for about 32s
agent-14 cwd=index + 51.0s -> + 83.5s success ← starts after both dependencies merged
agent-19 cwd=readme + 89.0s -> + 131.6s success
- Exit 0,
completionReason: success, 137s. - 101 ms between the last step and run completion.
- All four branches merged, with the integrated tests passing.
- Before this PR, the same flow parked on its second agent. An earlier long run on the first two commits alone crashed with the lease conflict above.
Tests
- New test files:
tests/worker-slots.test.tstests/authored-parallel-agents.test.ts, run against a real daemon: 3 agents at capacity 2 all complete without parking; two agents in differentcwds overlap; with the limiter off, the extra agent parks, which pins the original bug.tests/promise-ancestry.test.ts
- The gate-cost regression goes next to the 30 000-await test. It fails on the old code (25 060 ms) and passes now.
- The kernel
spec/tests.rscoverscwd. - Kernel:
ops/cargo.sh test, 262 passed. - SDK:
npm testwithRELAYFLOWD_BINpointed at this kernel: 2626 passed, 17 skipped, 1 flaky timing test that changes between runs (authored-rootfake 30ms lease / Slack 5s timeout /cli-watch). Those pass when run on their own and don't touch the gate. authored-node-runtime.test.tsneeds bun 1.4.0; it fails to load on this machine (1.3.14), same as onmain.
Not in this PR
- A
budgetheader still makes an authored flow run one step at a time (authored-budget.ts"Serialized admission").examples/pr-review-pipeline's "parallel" lenses therefore run in sequence. That needs its own fix. - Lease renewal runs on main-thread timers (
worker-lease.ts). Any synchronous stretch longer than about 20s still loses the lease. Renewing from a worker thread would close that class of problem. - #553 adds a
causesOfaccessor with the same name as the one here; whichever merges second drops its copy. - For Cloud runs, this reaches customers after the runtime is promoted (artifact → bucket → env pins → deploy). No Cloud code change is needed; Cloud's
--local-agentgets 4 slots by default.
🤖 Generated with Claude Code
[!NOTE]
Medium Risk
Changes kernel agent step validation, local worker concurrency, artifact locking, and authored completion gating—execution-critical paths with broad test coverage but non-trivial behavioral surface area.
Overview
Authored TypeScript flows can run multiple f.agent and f.llm calls in parallel under flows run|resume --local-agent, instead of parking overflow steps or stalling at completion.
Concurrency: Local agent and LLM workers default to 4 simultaneous dispatches (each counted separately). --agent-capacity <n> (1–32, requires --local-agent) threads through CLI, durable authored runs, and the Node child. A new WorkerSlots limiter queues extra child admissions in-process before run.start, matching worker capacity so the kernel no longer parks with agent_parked. On body failure or missing done(), slots close and stop so queued work is not admitted after teardown.
Per-agent cwd: The kernel accepts an optional absolute cwd on agent steps (relative paths refused in YAML and at flows check). f.agent resolves a relative cwd against the runner; specs without cwd hash unchanged. Agents in disjoint directories can overlap; overlapping trees (nested dirs or symlink aliases, including not-yet-created paths via canonicalTree) still serialize for artifact attribution.
Completion gate: Promise-dependency work for the authored operation gate is batched (promise-ancestry, rootsInFlight, cached aggregatesByInvocation) so large parallel runs finish in near-linear time instead of blocking the event loop and losing the root lease.
Reviewed by Cursor Bugbot for commit 18a95dbb60a22ac3d6328faa95fab5518ee49ee5. Bugbot is set up for automated code reviews on this repo. Configure here.
Summary by cubic
Fixes authored (TypeScript) flows so f.agent and f.llm calls run in parallel under --local-agent instead of parking the overflow or crashing at completion.
Behavior
- Agent and LLM workers now hold 4 dispatches each;
flows run|resume --agent-capacity <n>(1–32, requires--local-agent) sets it, and calls beyond the limit wait in-process in a FIFO limiter instead of submitting to a busy worker and parking. When the body fails or returns withoutdone(), the limiter refuses the waiting calls so they never run after teardown; a slot freed by a failing holder is handed over on a later macrotask so queued work cannot slip in before the refusal lands. - Agent steps carry an optional absolute
cwd(relative paths refused by the kernel, resolved by the TypeScript surface, and rejected byflows checkon declarative flows), so agents in different directories actually overlap; specs withoutcwdhash exactly as before. Agents in overlapping trees (one contains the other, or a symlink alias — including roots that do not exist yet) still take turns so each file change credits the right step; disjoint trees run side by side. - The flag and
cwdare documented indocs/SURFACE.mdand the CLI usage strings.
Performance
- The completion gate is now near-linear: one batch pass over promise ancestry with bitsets and Tarjan cycle condensation, plus a roots-indexed pass over settled promises, replaces per-operation walks. The gap between body return and run completion dropped from ~4470 ms to ~90 ms on a 162-step run, eliminating the lease-conflict crashes.
Agent Relay sessions
claudesession7371f69d· opened viagh pr create· last active 2026-09-22