Skip to content

feat(agent)!: make interrupt, resume and events predictable (ENG-505) - #15

Merged
folathecoder merged 1 commit into
mainfrom
folathecoder/eng-505-020-2-reliability-fixes-bundled-into-the-break
Nov 3, 2026
Merged

folathecoder merged 1 commit into
mainfrom
folathecoder/eng-505-020-2-reliability-fixes-bundled-into-the-break

Conversation

@folathecoder

Copy link
Copy Markdown
Collaborator

Summary

Apps built on agentling work around its interrupt and event behaviour today by reaching into AgentSession._interrupt or filtering events. This fixes that: an idle interrupt() no longer stops the next run, resume() continues an interrupted run without repeating the task, a session refuses a second concurrent run, and final_answer no longer appears as a tool in the event stream. Step callbacks can be async, and a tool call cut off by the model's output limit raises a clear error instead of asking the model to fix JSON it can't fix. These are breaking changes, so they ship in 0.2.0 with the model contract and apps migrate once.

Ticket

ENG-505. Closes ENG-505. Dev plan: ENG-517. Test plan: ENG-518.

Changes

Interrupt and resume (agent.py)

  • interrupt() while no run is active does nothing. The flag is cleared once, when a run starts. It used to stop the next run before its first step and leave that run's task in memory.
  • AgentSession.resume(stream=False, max_steps=None) continues an interrupted or failed run from memory without adding a TaskStep. It raises ValueError("Nothing to resume") when memory is empty or ends with a FinalStep. run(task, reset=False) still appends the task, as in 0.1.x.
  • An interrupt during the last step stops the run before the step-limit answer, instead of making one more model call.

One run per session (agent.py)

  • AgentSession.is_running is True from the first iteration of a run until it returns or raises.
  • run() or resume() during a run raises RuntimeError("Session is already running. ..."). With stream=True the error comes from the first anext, so a stream that is created but never iterated doesn't hold the session.
  • _run_stream is now a small guard around the loop body, which moved to _loop. The guard closes the inner generator with contextlib.aclosing.

Events (agent.py, events.py)

  • final_answer produces no ToolCallEvent or ToolResultEvent. A step that calls it yields its StepEvent, then the FinalEvent. The call and its result are still in the ActionStep, so memory replays as before.

Step callbacks (agent.py)

  • A callback can be async. Callbacks run in registration order and are awaited before the step's StepEvent. StepCallback is exported for typing.
  • On a step where final_answer succeeds, the FinalStep is written before the callbacks run. A callback that raises, or a cancellation while one awaits, no longer loses the answer or leaves the run looking resumable.

Cut-off and malformed output (agent.py, errors.py)

  • New ModelOutputTruncatedError(ModelError), not retryable. The loop raises it when a turn's tool call can't be parsed and the turn's last finish_reason is "length", in a normal step and in the step-limit answer. It no longer asks the model to fix such a call. Text cut off by the limit still completes, with FinalEvent.finish_reason == "length".
  • Turns whose tool calls can't be parsed no longer count towards max_steps. Three in a row still raise ModelError.

Typing

  • run(stream=True) and resume(stream=True) are typed AsyncGenerator[Event, None], so they work with contextlib.aclosing. The non-streaming forms are typed Coroutine[Any, Any, str], so they work with asyncio.create_task. The objects returned haven't changed, and code annotated the 0.1.1 way still passes mypy --strict.

Docs

  • README: "Sessions and concurrency", "Memory and resuming a run", "Interruption", the loop diagram, the events table, the step_callbacks row and the run() reference are updated, and a new rule covers unparseable and cut-off tool calls.
  • CHANGELOG: entries under [0.2.0] - Unreleased.

How it was tested

  • uv run pytest: 405 passed in 1.55 s, offline, on Python 3.11.15.
  • uv run ruff check src tests examples, uv run ruff format --check src tests examples, uv run mypy src tests examples and uv run mypy --strict src: clean. uv build succeeds.
  • Test plan ENG-518: TC-01 to TC-51 are automated and pass. TC-52 to TC-54 were checked by hand. Three existing tests were rewritten for the new behaviour, and none was deleted.
  • Each fix was undone in turn to confirm a test fails: 13 of 13 did.
  • Scripts outside the suite drove the branch the way an app would, and all behaved as documented:
    • a stream abandoned without closing frees the session two event-loop ticks after it's dropped, and the next run works;
    • Aldwin's pattern of cancelling a turn and starting the next one works with and without aclosing;
    • a run interrupted at the step limit resumes, saves, and replays after a JSON reload;
    • a callback that raises (sync or async), or a cancellation during an async callback, on the final_answer step keeps the answer, and the model is called once;
    • a consumer annotated the 0.1.1 way passes mypy --strict;
    • the README's interruption example runs.
  • The four offline examples run: cli_advanced_observer, cli_dynamic_tools, cli_failure_recovery and cli_memory_chat.
  • TC-52: agent.py is 880 lines, +114 against 766.
  • Not run: a live model. The changes are in the loop, not in an adapter.

Screenshots / recordings

None: the library has no UI.

Notes for reviewers

  • Suggested reading order: _run_stream, _loop and resume() in agent.py, then the interruption and "one run at a time" sections of tests/test_agent.py, then the truncation and step-accounting tests in tests/test_model_turns.py.
  • Breaking for callers that relied on an idle interrupt() stopping the next run, on a ToolCallEvent for final_answer, or on two runs at once on one session.
  • agent.py grew by 114 lines, more than the 60 to 75 the plan expected. Most of it is resume() with its overloads, the guard and _loop split, and two small helpers. The breakdown is on ENG-517.
  • An interrupt() made before a run starts iterating is ignored by design. The README example yields once before interrupting.
  • The RuntimeError message keeps "Session is already running" as its first sentence and adds a pointer to contextlib.aclosing, so a match on the first sentence still works.
  • Known limits, unchanged: a tool call cut off right after its name reassembles with {} and runs, because it can't be told apart from a complete call with no arguments. A final_answer with bad arguments emits no events; its error is on the ActionStep, and the README says so.
  • Follow-ups: add uv run mypy --strict src to CI. ENG-506 is the testing kit and ENG-507 the release. In ENG-508, Aldwin deletes its three _interrupt.clear() calls and its final_answer filters, and wraps its streaming loop in aclosing.

Apps worked around the interrupt flag, duplicated tasks on resume and
final_answer tool events by reaching into private state or filtering
events. These fixes are breaking, so they ship in 0.2.0 with the model
contract and apps migrate once.

- interrupt() while no run is active does nothing. The flag is cleared
  once, when a run starts.
- AgentSession.resume() continues an interrupted or failed run from
  memory without adding the task again. run(task, reset=False) still
  appends it.
- A session runs one task at a time: run() or resume() during a run
  raises RuntimeError. is_running reports whether a run is active.
- final_answer produces no ToolCallEvent or ToolResultEvent. The call
  is still recorded in the ActionStep.
- Step callbacks can be async and are awaited in order before the
  step's StepEvent. The FinalStep is written before they run, so a
  callback that raises no longer loses the answer.
- A tool call cut short by the model's output limit raises
  ModelOutputTruncatedError instead of asking the model to fix it.
- Turns whose tool calls can't be parsed no longer count towards
  max_steps.
- An interrupt during the last step stops the run before the
  step-limit answer.
- run(stream=True) is typed as an async generator, so it works with
  contextlib.aclosing, and run() as a coroutine, so it works with
  asyncio.create_task.

BREAKING CHANGE: an idle interrupt() no longer stops the next run,
run() or resume() on a running session raises RuntimeError,
final_answer emits no tool events, and malformed turns no longer use
up max_steps.
@folathecoder
folathecoder merged commit cae5fba into main Nov 3, 2026
2 checks passed
@folathecoder
folathecoder deleted the folathecoder/eng-505-020-2-reliability-fixes-bundled-into-the-break branch November 3, 2026 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant