Skip to content

fix(agents): run sessions_spawn children in one-shot agent --local - #207243

Closed
obviyus wants to merge 11 commits into
mainfrom
core/local-spawn-runtime
Closed

obviyus wants to merge 11 commits into
mainfrom
core/local-spawn-runtime

Conversation

@obviyus

@obviyus obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

In a one-shot openclaw agent --local run, sessions_spawn never works, on any runtime. The tool returns {"status":"error","error":"published reply runtime missing for main"}, so a user who asks for a subagent gets a blocker.

There are three causes, one after another:

  1. Admission. Agent-turn admission reads its dispatch facts only from the Gateway's configured publication (loadPublishedGatewayReplyDispatchRuntime). That publication does not exist outside a Gateway, so the loader returns nothing and admission throws (agent-run-admission-phase.ts).
  2. Lifecycle reads. The child's completion wait (agent.wait) went to the websocket Gateway client, because bindGatewayLifecycleRequest treated local contexts as unhosted. It failed with "requires credentials".
  3. Lifetime. Subagent completion and the announcement back to the parent run as detached root work. The one-shot process closed its databases as soon as the parent turn returned. Completion then failed with Database maintenance resource admission is closed.

Solution

One owner per step; no second implementation.

  • Dispatch facts. The request context supplies them (loadReplyDispatchRuntime). A Gateway keeps its configured publication. The local context loads the target agent's run generation under the same lease contract, through one shared projection (projectReplyDispatchRuntime).

  • Lifecycle reads. The local context uses the Gateway's own createGatewayInstanceRuntime with the shared method registry. agent.wait, chat.history and agent turns therefore run in-process through the same server-method owner. The runtime and registry load on the first turn or lifecycle read, so a one-shot run that never dispatches another turn loads no extra modules. The hand-written local facade and its internal-facade.runtime.ts barrel are deleted.

  • Global registration. The process-global lifecycle registration moved from the runtime factory to the Gateway kernel. An embedded host never replaces a live Gateway's registration; gateway.boot runs a local command inside the Gateway process. Test fixtures that stand in for a listening Gateway register the same way.

  • Lifetime.

    • Local agent turns are admitted as root work.
    • Both one-shot database owners wait for root work to go idle before they close the databases (waitForLocalBackgroundWork → waitForGatewayRootWorkIdle): runWithLocalStateOwner, and agent exec's temporary state before its cleanup. The wait is event-driven: release notifications, no timer.
    • Long-lived subscriptions never count, using the existing isActiveRootWork rule. Every root-work kind a one-shot can reach is finite.
    • While it waits, the CLI prints Waiting for N background tasks to finish. Press Ctrl-C to stop. Ctrl-C stops the wait.
  • Hosting Gateway. If a Gateway already hosts the process (BOOT.md runs a local command inside it), the local context defers to it: the Gateway's publication, execution tracking and lifecycle runtime. Only a true one-shot process supplies its own.

User impact

  • One-shot agent --local users on the embedded and Codex runtimes: sessions_spawn now runs the child, and the parent gets a continuation turn with the child's result.
  • One-shot commands that start no detached work exit as before, with no wait.
  • Gateway users: dispatch facts, execution tracking and the global lifecycle registration are unchanged. For BOOT.md turns, lifecycle reads (agent.wait) now use the hosting Gateway's runtime in-process instead of a websocket call back to the same Gateway.
  • Other one-shot commands can also be interrupted while they wait: templates add through the CLI signal gate, agent exec --state-dir through its own signal bridge.

Accepted edge cases

  • Failure retries on timers. If a subagent completion fails and retries on a timer (subagent-registry-run-wait.ts:126-145, subagent-registry-completion-runtime.ts:212-224), no root is held during the delay, so the one-shot process can close before the retry runs. The run stays persisted as pending, and registry recovery delivers it on the next Gateway start (initSubagentRegistry, server-startup-bootstrap.ts); a later --local run does not restore it. The normal path has no gap: the child's lifecycle-end handler takes its root before the child turn's root releases.
  • Results after the first turn. In --json mode the first turn's result prints before the wait. The continuation turn's reply goes to the session transcript; the terminal shows only the waiting line. A parent that waits in-turn (agents_wait) returns the child's result in its own reply.
  • No end-to-end agent exec spawn test. The isolated process fixture cannot run agent exec on the base or here (auth-owner and model-resolution setup), so exec's wait is covered by the shared wait's unit tests only.
  • Ctrl-C stops the wait, not the children. The databases then close under any child that is still running. That is the behavior main has today for any detached work.

Evidence

  • New process test src/cli/agent-local-subagent-spawn.process.test.ts: real CLI child, fake Responses server. The parent spawns through dispatch_action → sessions_spawn, the child replies, and a parent continuation turn sees the child's result.
    • Red on main: published reply runtime missing for main.
    • Green here.
  • gateway-work-admission.idle.test.ts:
    • no work, or only a subscription, returns at once;
    • detached work is waited for and reported once;
    • an interrupt stops the wait.
  • local-request-context.test.ts: a one-shot context supplies its own dispatch facts and lifecycle runtime; inside a hosting Gateway it supplies neither and uses the Gateway's.
  • Consumer tests of every changed module pass. Two subagent-spawn.production-boundary cases also fail on the merge base under load: in isolated runs, "timed-out collector child" failed base 3/3 and head 1/3, and "consumed-session Stop authority" failed base 1/3 and head 0/3.
  • --local cold start, 20 interleaved base/head pairs on a fake Responses server: median time to first model request 15.5 s on the base, 14.4 s here. Both sides show the same slow outliers from host load (30-42 s). Modules loaded before the first request: 6,371 on both (+2.9 KB).
  • Gateway bench (fake provider, both routes): 48/48 turns pass on each side. Median later-turn time: Codex route 1,625 -> 1,443 ms, embedded 1,079 -> 1,112 ms. In an interleaved run, first-turn times moved in opposite directions on the two routes, with the same spread on both sides. On the Gateway path this change only moves where the lifecycle runtime is registered.
  • Behavior suite (gpt-5.4-mini, 3 trials, embedded and Codex routes), subagent-spawn: base 0/6 real delegations (published reply runtime missing for main, or no tool found); head 4/6 return the child's answer, 1 delegated and still pending at the end of the turn, 1 (embedded) did not find sessions_spawn through tool_search. Other cases: no new failures.

- Agent-turn admission takes dispatch facts from the request context; the local context loads the target agent's run generation, the Gateway keeps its publication.
- The local context builds the Gateway's own instance runtime, so agent.wait, chat.history and agent turns run in-process through the shared method owner; the Gateway kernel alone claims the process-global lifecycle registration.
- One-shot commands wait for detached root work (subagent completion, announcements) before closing their databases, with a visible line; Ctrl-C stops the wait. Subscriptions never count.
- A detached root waits for every descendant, so an open wait could hold a one-shot process; each local turn now holds an independent root for its own run, and completion keeps its own detached root.
- Admission still tracks the caller's work scope, so a closed caller scope refuses new execution.
- server-instance-runtime tests follow the contract that only the Gateway kernel claims the global lifecycle registration.
…untime lazily

- A local context inside a Gateway process (BOOT.md) keeps the Gateway's dispatch facts, execution tracking and lifecycle runtime; only a one-shot process supplies its own.
- The CLI root-work wait also listens to the owner's controller, so Ctrl-C exits; an already-aborted signal returns at once.
- The Gateway instance runtime and method registry load on first use: modules before the first request return to base (6,371).
- The production-boundary fixture stands in for the listening Gateway, so it registers the lifecycle runtime the way the kernel does.
…e-dir

- agent exec owns its own signal bridge, so the CLI signal gate never aborts the local owner; pass the bridge signal like agent --local does.
@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling size: L labels Nov 28, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 28, 2026
@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head a272a5c7c9efc9643d618f7151677a43726407a7, but the PR head is now cdd46236a2f0b976c0c55f61ec0615684487178e. Its old verdict and PR readiness labels are no longer current.

Next step
Comment @clawsweeper re-review when the current head is ready; pushes after the first review are not reviewed automatically.

Review history (1 earlier review cycle)
  • reviewed 2026-11-28T05:00:17.312Z sha a272a5c :: needs changes before merge. :: [P2] Update the announcement fixture for local lifecycle dispatch

…porary state

- One helper, waitForLocalBackgroundWork, serves both one-shot DB owners: runWithLocalStateOwner and agent exec's temporary scope.
- The process test also runs agent exec; that case is red (auth read from an uncaptured owner) and under investigation.
- The isolated process fixture cannot run agent exec on base or head (auth owner, model resolution), so it cannot prove exec's wait end to end.
…le runtime

- Local contexts now carry an in-process lifecycle runtime; the fixture's stand-in forwards to the mocked Gateway client the tests observe.
- The fixture stands in for the listening Gateway; the instance factory no longer claims the process-global registration.
@obviyus

obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

No override. Not landing this PR: proposing a split (root-work wait first, then spawn acceptance and the lifecycle registration move), each landing on its own green CI.

obviyus added a commit that referenced this pull request Nov 28, 2026
## Problem

On the default Codex app-server runtime (native OpenAI models), each request carries three overlapping subagent tool sets: Codex's native `multi_agent_v1` (14,898 B: `spawn_agent`, `send_input`, `resume_agent`, `wait_agent`, `close_agent`), OpenClaw's `sessions_spawn` (8,271 B) and `agents_wait`/`agents_list`. The developer prompt also spends paragraphs steering the model between native and managed delegation.

- Native Codex children cannot run OpenClaw tools (`thread-prompt.ts`). `sessions_spawn` covers those children, ACP, visible sessions and fork context, with the same contract as on the embedded runtime.
- A production deployment over 7 days (162 Codex-runtime sessions): 0 native multi-agent calls, against 181 `sessions_spawn` calls in 21 sessions.

Measured on main through an isolated Gateway (fake provider): 15 tools / 52,346 B per request.

## Solution

- Every thread OpenClaw starts or resumes sets `agents.enabled`, `features.multi_agent` and `features.multi_agent_v2` to false, through the existing `CODEX_DELEGATION_DISABLED_THREAD_CONFIG` in `buildCodexRuntimeThreadConfig`.
- The per-run native-delegation decision (`isCodexNativeDelegationDisabledForRun`), the gpt-5.4-nano patch it subsumed, and the native-vs-managed prompt steering are deleted.
- Native-subagent observation stays. It also owns root model-source authority, supervision of desktop threads, and recovery of native children that already exist.
- Docs follow, and the Codex prompt budget ratchet drops to the new size.

Upstream note: `multi_agent` is `Stage::Deprecated`, default on; `multi_agent_v2` is `Stage::Stable`, default off (`openai/codex` `features/src/lib.rs`).

## User impact

- Every Codex-runtime turn, Gateway and one-shot: tools 52,346 → 37,447 B per request (−14,899 B). The Codex app-server developer prompt drops 12,618 → 11,756 B (snapshot). Prompt budget ratchet 13,824 → 12,544 B (`CODEX_APP_SERVER_PROMPT_BUDGET_BYTES`). The dynamic-tools snapshot is unchanged (62,551 B): the removed tools are Codex-native, not dynamic tools, so the tools ratchet stays.
- In one-shot `agent --local`, delegation needs `sessions_spawn` working without a Gateway (#207243, landing first).
- Existing threads get the new tool list on their next cold resume: one prompt-cache miss per thread. A loaded thread keeps its tools until then (`codex-rs/app-server/src/request_processors/thread_processor.rs:291` ignores config on a running thread; `core/src/config/mod.rs:1833` maps `agents.enabled=false` to `MultiAgentVersion::Disabled`).
- Accepted loss (maintainer decision): after a cold resume, a parent that kept a native child open cannot send that child more input. `sessions_spawn` starts another worker and does not continue that child's assignment. Results already in flight are still observed and delivered. Production showed 0 native multi-agent calls in 7 days. Docs say so (`codex-harness.md`, Native subagent status).
- A managed Codex requirement that pins multi-agent on still wins, except where a session-tool deny already rejects it (documented in `restricted-turns.md`).

## Evidence

- Isolated Gateway bench, fake provider: 15 → 14 tools, 52,346 → 37,447 B.
- Codex-route behavior suite, gpt-5.4-mini, 3 trials per case, model-judged: main 24/30, this change 27/30. reply-directive is 0/3 on both, an existing gap.
- Tests: the codex thread-lifecycle, prompt and native-hook tests, the new `thread-delegation.test.ts`, and `prompt-snapshots.test.ts` with the lower budget all pass.

Co-authored-by: Ayaan Zaidi <[email protected]>
@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 28, 2026
@obviyus

obviyus commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Split per maintainer decision. Part A, the one-shot root-work wait, is #207510. Part B, subagent spawn in one-shot agent --local (the lifecycle registration move and the reply-dispatch runtime), follows after A lands.

@obviyus obviyus closed this Nov 28, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
…#207303)

## Problem

On the default Codex app-server runtime (native OpenAI models), each request carries three overlapping subagent tool sets: Codex's native `multi_agent_v1` (14,898 B: `spawn_agent`, `send_input`, `resume_agent`, `wait_agent`, `close_agent`), OpenClaw's `sessions_spawn` (8,271 B) and `agents_wait`/`agents_list`. The developer prompt also spends paragraphs steering the model between native and managed delegation.

- Native Codex children cannot run OpenClaw tools (`thread-prompt.ts`). `sessions_spawn` covers those children, ACP, visible sessions and fork context, with the same contract as on the embedded runtime.
- A production deployment over 7 days (162 Codex-runtime sessions): 0 native multi-agent calls, against 181 `sessions_spawn` calls in 21 sessions.

Measured on main through an isolated Gateway (fake provider): 15 tools / 52,346 B per request.

## Solution

- Every thread OpenClaw starts or resumes sets `agents.enabled`, `features.multi_agent` and `features.multi_agent_v2` to false, through the existing `CODEX_DELEGATION_DISABLED_THREAD_CONFIG` in `buildCodexRuntimeThreadConfig`.
- The per-run native-delegation decision (`isCodexNativeDelegationDisabledForRun`), the gpt-5.4-nano patch it subsumed, and the native-vs-managed prompt steering are deleted.
- Native-subagent observation stays. It also owns root model-source authority, supervision of desktop threads, and recovery of native children that already exist.
- Docs follow, and the Codex prompt budget ratchet drops to the new size.

Upstream note: `multi_agent` is `Stage::Deprecated`, default on; `multi_agent_v2` is `Stage::Stable`, default off (`openai/codex` `features/src/lib.rs`).

## User impact

- Every Codex-runtime turn, Gateway and one-shot: tools 52,346 → 37,447 B per request (−14,899 B). The Codex app-server developer prompt drops 12,618 → 11,756 B (snapshot). Prompt budget ratchet 13,824 → 12,544 B (`CODEX_APP_SERVER_PROMPT_BUDGET_BYTES`). The dynamic-tools snapshot is unchanged (62,551 B): the removed tools are Codex-native, not dynamic tools, so the tools ratchet stays.
- In one-shot `agent --local`, delegation needs `sessions_spawn` working without a Gateway (openclaw#207243, landing first).
- Existing threads get the new tool list on their next cold resume: one prompt-cache miss per thread. A loaded thread keeps its tools until then (`codex-rs/app-server/src/request_processors/thread_processor.rs:291` ignores config on a running thread; `core/src/config/mod.rs:1833` maps `agents.enabled=false` to `MultiAgentVersion::Disabled`).
- Accepted loss (maintainer decision): after a cold resume, a parent that kept a native child open cannot send that child more input. `sessions_spawn` starts another worker and does not continue that child's assignment. Results already in flight are still observed and delivered. Production showed 0 native multi-agent calls in 7 days. Docs say so (`codex-harness.md`, Native subagent status).
- A managed Codex requirement that pins multi-agent on still wins, except where a session-tool deny already rejects it (documented in `restricted-turns.md`).

## Evidence

- Isolated Gateway bench, fake provider: 15 → 14 tools, 52,346 → 37,447 B.
- Codex-route behavior suite, gpt-5.4-mini, 3 trials per case, model-judged: main 24/30, this change 27/30. reply-directive is 0/3 on both, an existing gap.
- Tests: the codex thread-lifecycle, prompt and native-hook tests, the new `thread-delegation.test.ts`, and `prompt-snapshots.test.ts` with the lower budget all pass.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations gateway Gateway runtime impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant