fix(sdk,kernel): run authored agents in parallel under --local-agent

Merged
KH
2mo ago
+951-66

Problem

An authored (TypeScript) flow could not run agents in parallel. Three separate defects stood in the way:

  1. The second agent parked. flows run --local-agent attached one agent worker and one LLM worker, each with capacity: 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-agent path, so the same limit applied there.
  2. f.agent({ cwd }) was refused. The SDK threaded cwd into the step spec (#357/#358), but the kernel StepSpec had no such field: invalid_spec: unknown field "cwd". Without cwd, every agent shares the process directory, and worker-cli.ts runs 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.
  3. Long parallel runs crashed at the end. The authored completion gate was super-linear. aggregatesFor re-walked promise ancestry pairwise, and settledFrom/inFlightFrom scanned 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 ended crashed with lease_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) on flows run and flows 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.
  • ab065fcb — kernel cwd
    • Agent steps take an optional absolute cwd, which is passed to the worker the same way model is.
    • A relative path is refused (RelativeStepCwd). llm steps still refuse the field.
    • Specs without cwd serialize and hash exactly as before; the hash is pinned in a test.
    • f.agent resolves a relative cwd against the flow before sending it.
  • 3985c270 — near-linear completion gate
    • New promise-ancestry.ts works 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 dependenciesOf cache is now keyed by graph version; before, it could return a walk from before the graph grew.

Evidence

Gate cost (synthetic task-graph flow, real daemon), time from body return to run completion:

stepsbeforeafter
42185 ms20 ms
1625 740 ms40 ms
322not measured97 ms
162 × 2s steps4 468 ms92 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.ts
    • tests/authored-parallel-agents.test.ts, run against a real daemon: 3 agents at capacity 2 all complete without parking; two agents in different cwds 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.rs covers cwd.
  • Kernel: ops/cargo.sh test, 262 passed.
  • SDK: npm test with RELAYFLOWD_BIN pointed at this kernel: 2626 passed, 17 skipped, 1 flaky timing test that changes between runs (authored-root fake 30ms lease / Slack 5s timeout / cli-watch). Those pass when run on their own and don't touch the gate.
  • authored-node-runtime.test.ts needs bun 1.4.0; it fails to load on this machine (1.3.14), same as on main.

Not in this PR

  • A budget header 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 causesOf accessor 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-agent gets 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 without done(), 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 by flows check on declarative flows), so agents in different directories actually overlap; specs without cwd hash 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 cwd are documented in docs/SURFACE.md and 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

  • claude session 7371f69d · opened via gh pr create · last active 2026-09-22