Skip to content

collab_tool_call "spawn_agent" item missing from exec --experimental-json stream; "wait" item's receiver_thread_ids stays empty despite a real, successful delegation underneath #34919

Open

Description

@tic-top

What version of Codex CLI is running?

0.144.5 (installed via @openai/codex-sdk / @openai/codex npm packages)

Which model were you using?

gpt-5.6-sol

What platform is your computer?

Linux (Ubuntu 20.04 focal), invoked via @openai/codex-sdk's Codex.startThread().runStreamed(), which shells out to codex exec --experimental-json (see node_modules/@openai/codex-sdk/src/exec.ts).

What happened?

Using native subagent support ([features] multi_agent = true, a custom
agent defined at <CODEX_HOME>/agents/<name>.toml), I asked the root agent
to spawn a named custom agent and relay its exact reply. The
--experimental-json event stream only ever shows:

{"type":"item.started","item":{"id":"item_1","type":"collab_tool_call","tool":"wait","sender_thread_id":"...","receiver_thread_ids":[],"prompt":null,"agents_states":{},"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"wait","sender_thread_id":"...","receiver_thread_ids":[],"prompt":null,"agents_states":{},"status":"completed"}}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"SPECIALIST SAID: PONG"}}

Note: no collab_tool_call with tool: "spawn_agent" (or similar) ever
appears in this stream, and the wait item's receiver_thread_ids is
always [], even though the final agent_message content is correct.

This reproduced identically across 6 separate runs, with and without
[features.multi_agent_v2].

Reading the FULL session rollout (~/.codex/sessions/**/*.jsonl) for the
same turn tells a different, complete story — it contains the actual
function_call/function_call_output pair for the spawn, a
sub_agent_activity event ("kind": "started"), the child thread's own
rollout file (session_meta subagent.thread_spawn with the correct
agent_path/agent_nickname), and the real agent_message reply routed
back from the child. state_5.sqlite's thread_spawn_edges table also
correctly records the parent→child edge for every one of the 6 runs.

So: delegation genuinely works end-to-end. The bug is that the
--experimental-json stream — the one @openai/codex-sdk consumes and
exposes to SDK users — is missing the spawn_agent collab_tool_call event
entirely, and the wait item it does emit never reflects the real
receiver thread. This is different from #28318 (missing TypeScript type for
collab_tool_call — that reporter's runtime JSON did include a populated
spawn_agent item with real receiver_thread_ids); here the data itself
is missing from this event source, not just its type.

Expected behavior

exec --experimental-json (and therefore @openai/codex-sdk's public
event stream) should include the spawn_agent collab_tool_call item, and
wait's receiver_thread_ids should reflect the actual spawned child
thread(s) — matching what the full session rollout already records
correctly.

Why this matters

Any SDK consumer trying to observe or verify subagent delegation
(logging, tracing, debugging, deciding whether to trust a delegated
result) via the public event stream currently gets a false negative —
delegation looks like a silent no-op even when it succeeded. We only
caught this by cross-referencing the full rollout JSONL and
state_5.sqlite directly, which isn't part of the SDK's public surface.

Activity

  1. added
    bug
    CLI
    exec
    subagent
    on Jul 23, 2026
  2. drewmt commented on Jul 24, 2026

    @drewmt

    Confirmed on codex-cli 0.145.0-alpha.18 with codex exec --json using one v2 spawn, one wait, and an exact PONG-34919 relay. The public JSONL still emitted only a wait item with receiver_thread_ids: []; the matching rollout contained the spawn_agent function call, a sub_agent_activity started event with the child thread ID, and the child reply. The turn context confirmed multi_agent_version: "v2".

    On current main (99744cf), this appears to be the v2 event-shape boundary rather than the JSON serializer itself:

    A focused regression would ideally exercise the v2 spawn/wait flow through the exec/app-server boundary and assert that the public JSONL exposes the spawned child ID, rather than only testing the synthetic CollabAgentToolCall mapper. Happy to prepare that patch if the maintainers would like an external PR.

  3. coygeek commented on Nov 5, 2026

    @coygeek

    Summary

    The missing-spawn behavior remains reproducible on the latest stable CLI with a standalone loopback Responses fixture. A real V2 child request reaches the fixture and the parent receives a successful spawn result, but codex exec --json emits no spawn item. A V1 control emits both spawn lifecycle items. This adds a model-free reproduction and a current release check to this issue; it does not test the separate empty-wait-receiver symptom.

    Runtime or environment

    • Executed: a fresh isolated npm install of @openai/codex, reporting codex-cli 0.166.0, on macOS Apple Silicon (Darwin 27.2.0 arm64); npm latest and the latest non-prerelease GitHub release matched.
    • Source inspection only: current main at 9a7213ca37c6aa19127100027f041599d2d28eb9; I did not build or execute this checkout.
    • Model catalog names: gpt-6-sol (bundled V2 hint), gpt-5.6-luna (V1 hint), and gpt-5.5 (no multi-agent version hint). There is no real model inference, subscription, authentication, terminal emulator, or copied user configuration in the reproduction.

    Steps to reproduce

    Save the following as repro.py and run python3 repro.py /absolute/path/to/codex. It uses Python's standard library, a fresh HOME, CODEX_HOME and working directory per case, --ignore-user-config, and an unauthenticated loopback custom provider. It scripts one spawn call, completes the child locally if one starts, and prints event types and the tool result. All test tasks are synthetic.

    import json
    import os
    import pathlib
    import signal
    import subprocess
    import sys
    import tempfile
    import threading
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    
    # Run: python3 repro.py /absolute/path/to/codex
    binary = sys.argv[1]
    for model, agents_off, namespace in [
        ('gpt-6-sol', False, 'collaboration'),
        ('gpt-6-sol', True, 'collaboration'),
        ('gpt-5.5', False, 'collaboration'),
        ('gpt-5.6-luna', False, 'multi_agent_v1'),
    ]:
        requests = []
        child_seen = threading.Event()
    
        class Handler(BaseHTTPRequestHandler):
            def log_message(self, *args):
                pass
    
            def do_GET(self):
                body = b'{"models":[]}'
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Content-Length', str(len(body)))
                self.end_headers()
                self.wfile.write(body)
    
            def do_POST(self):
                req = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
                requests.append(req)
                outputs = [i for i in req.get('input', []) if i.get('type') == 'function_call_output']
                if len(requests) == 1:
                    args = {'message': 'CHILD_MARKER'}
                    if namespace == 'collaboration':
                        args.update(task_name='probe', fork_turns='none')
                    item = dict(type='function_call', id='call-spawn', call_id='spawn-1',
                                namespace=namespace, name='spawn_agent', arguments=json.dumps(args))
                else:
                    if not outputs:
                        child_seen.set()
                    elif not agents_off:
                        child_seen.wait(1)
                    item = dict(type='message', id='message', role='assistant',
                                content=[dict(type='output_text', text='done')])
                self.send_response(200)
                self.send_header('Content-Type', 'text/event-stream')
                self.end_headers()
                events = [dict(type='response.created', response={'id': 'r'}),
                          dict(type='response.output_item.done', item=item),
                          dict(type='response.completed', response={'id': 'r', 'usage': {
                              'input_tokens': 1, 'output_tokens': 1, 'total_tokens': 2}})]
                for event in events:
                    self.wfile.write(('data: ' + json.dumps(event) + '\n\n').encode())
                    self.wfile.flush()
    
        server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
        thread = threading.Thread(target=server.serve_forever)
        thread.start()
        try:
            with tempfile.TemporaryDirectory() as td:
                root = pathlib.Path(td)
                for name in ('home', 'codex', 'work'):
                    (root / name).mkdir()
                env = dict(PATH=os.environ['PATH'], HOME=str(root / 'home'), CODEX_HOME=str(root / 'codex'))
                cmd = [binary, 'exec', '--ignore-user-config', '--ephemeral', '--skip-git-repo-check',
                       '-s', 'read-only', '--json', '-m', model,
                       '--disable', 'multi_agent', '--disable', 'multi_agent_v2',
                       '-c', 'web_search="disabled"', '-c', 'skills.bundled.enabled=false',
                       '-c', 'model_provider="fixture"', '-c',
                       f'model_providers.fixture={{name="fixture",base_url="http://127.0.0.1:{server.server_port}/v1",wire_api="responses",requires_openai_auth=false}}']
                if agents_off:
                    cmd += ['-c', 'agents.enabled=false']
                process = subprocess.Popen(cmd + ['-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE, text=True, cwd=root / 'work',
                                           env=env, start_new_session=True)
                try:
                    stdout, stderr = process.communicate('Local protocol fixture.', timeout=30)
                except subprocess.TimeoutExpired:
                    os.killpg(process.pid, signal.SIGKILL)
                    process.communicate()
                    raise
                events = [json.loads(line) for line in stdout.splitlines()]
                outputs = [i['output'] for r in requests for i in r.get('input', [])
                           if i.get('type') == 'function_call_output']
                print(json.dumps(dict(model=model, agents_off=agents_off, exit=process.returncode,
                    child_request=child_seen.is_set(), spawn_outputs=outputs,
                    events=[e['type'] + (':' + e['item']['type'] + ':' + e['item'].get('tool', '')
                            if 'item' in e else '') for e in events])))
        finally:
            server.shutdown()
            server.server_close()
            thread.join()

    Expected behavior

    A successful V2 spawn should be observable through the public exec JSONL stream, with enough identity to correlate the spawn and child. The same binary already exposes successful V1 spawns as collab_tool_call lifecycle items. A disabled-spawn control should remain rejected; it must not count as restored event visibility.

    Actual behavior

    All four standalone cases exited zero. In the V2 case the fixture observed a child request and received {"task_name":"/root/probe"} as the parent-visible spawn output, but the entire stdout event sequence was:

    thread.started
    turn.started
    item.completed:agent_message:
    turn.completed
    

    The V1 control observed a child request and additionally emitted item.started:collab_tool_call:spawn_agent and item.completed:collab_tool_call:spawn_agent. The control with agents.enabled=false exposed no collaboration declarations and returned unsupported call: collaborationspawn_agent, with no child request. The no-version-hint model control also rejected that call. These controls distinguish successful-but-unreported spawning from disabled or rejected calls.

    Both feature flags are false in all four cases. That does not by itself mean subagents are disabled: the model's catalog hint can select V2. -c 'agents.enabled=false' is the tested control for disabling the collaboration declarations and execution while the V2 feature override is false. It is not a replacement for observing spawns when delegation is intentionally enabled. This report does not assert a common cause between configuration precedence and the JSONL omission.

    Evidence

    • Expected source: the release's public exec CollabTool::SpawnAgent event representation and the directly executed V1 control above establish the spawn observability contract; the non-interactive output documentation describes the JSONL event stream.
    • Failure source: the standalone fixture above recorded a successful V2 spawn result plus an independent child request, while its complete stdout event sequence had no spawn item.
    • Evidence provenance: observed
    • Local verification: reproduced
    • Reproduction completeness: complete

    The inspected source remains consistent with the runtime distinction: core/src/tools/handlers/multi_agents_v2/spawn.rs emits SubAgentActivityKind::Started and records private collaboration analytics, while exec/src/event_processor_with_jsonl_output.rs maps CollabAgentToolCall and falls through for the activity shape. The V1 spawn handler emits the mapped collaboration item. This is a source-level explanation, not a claim that I executed main.

    The fixture uses no login and the bundled catalog metadata for the named models. Logged-in requests were not tested here; earlier local capture attempts could not read their zstd-compressed bodies. The reproduced claim is bounded to the unauthenticated custom Responses provider path. No sandbox or approval boundary crossing is claimed.

    Restoration check

    Run the V2 case with the same scripted successful spawn. Require an observable spawn event correlated with the child that actually starts, while preserving the V1 lifecycle events. Keep the agents.enabled=false case rejected with no child request. A final assistant message saying a spawn occurred does not replace an event emitted by the runtime.

    Triage assessment

    • Impact level: P2
    • Assessment status: supported
    • Impact basis: Stream consumers cannot detect a real successful V2 delegation in this bounded case, breaking logging and tool-use monitoring; no data loss, privilege escalation, broad outage, or population frequency is established.
    • Workaround status: unverified
    • Workaround basis: Disabling agents prevents the action but does not preserve observability when delegation is required. Persisted rollout inspection may offer another evidence source in non-ephemeral runs, but this reproduction is ephemeral and did not verify that workaround.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugexecsubagent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions