Fix `RuntimeError: coroutine ignored GeneratorExit` and an escaping `KeyboardInterrupt` on `Agent.iter()` teardown

Merged
PY
1mo ago
+177-8

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

Closes #10249

Why we make these changes

Closing an async generator that owns an Agent.iter() run, or raising GeneratorExit inside the run, raised RuntimeError: coroutine ignored GeneratorExit. A KeyboardInterrupt raised inside the run escaped the event loop even when the caller caught it. Both came from _run_lifecycle_hooks letting the wrap_run task fail with the exception and then awaiting that task. asyncio resumes the waiter through throw(), which closes its whole await chain on GeneratorExit, and re-raises KeyboardInterrupt out of the loop.

On these two exceptions the run now cancels and drains the wrap_run task, the same way a break out of iter() already does.

New public surface

none

User-visible behavior

async def first_event(agent):
    async with agent.iter('Hello') as run:
        node = await run.next(run.next_node)
        async with node.stream(run.ctx) as stream:
            yield await anext(aiter(stream))

events = first_event(agent)
await anext(events)
await events.aclose()  # before: RuntimeError: coroutine ignored GeneratorExit; now: returns

A capability's wrap_run gets asyncio.CancelledError from handler() in these cases, as it already did for a break. Its cleanup finishes before the async with block exits. The wrap_run docstring now says so.

Verification

What changes for existing users

Closing a generator that owns an iter() run or a realtime session, or raising GeneratorExit/KeyboardInterrupt inside one, now propagates the original exception after cleanup instead of crashing teardown.

PR decisions

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it. (N/A: the changed paths crashed on main.)
  • PR title is fit for the release changelog.