react-agent-harness 0.8.0__tar.gz → 0.9.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. {react_agent_harness-0.8.0/react_agent_harness.egg-info → react_agent_harness-0.9.1}/PKG-INFO +1 -1
  2. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/README.md +133 -18
  3. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/agents/base.py +86 -10
  4. react_agent_harness-0.9.1/harness/cancellation.py +186 -0
  5. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/cli.py +9 -6
  6. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/console.py +64 -1
  7. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/persistent.py +608 -63
  8. react_agent_harness-0.9.1/harness/persistent_completion.py +125 -0
  9. react_agent_harness-0.9.1/harness/persistent_controls.py +525 -0
  10. react_agent_harness-0.9.1/harness/persistent_prompt.py +150 -0
  11. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/pyproject.toml +1 -1
  12. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1/react_agent_harness.egg-info}/PKG-INFO +1 -1
  13. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/SOURCES.txt +10 -0
  14. react_agent_harness-0.9.1/tests/test_cancellation.py +314 -0
  15. react_agent_harness-0.9.1/tests/test_persistent_agent.py +919 -0
  16. react_agent_harness-0.9.1/tests/test_persistent_completion.py +140 -0
  17. react_agent_harness-0.9.1/tests/test_persistent_controls.py +193 -0
  18. react_agent_harness-0.9.1/tests/test_persistent_prompt.py +192 -0
  19. react_agent_harness-0.9.1/tests/test_resume_hint_banner.py +300 -0
  20. react_agent_harness-0.9.1/tests/test_system_prompt_routing.py +165 -0
  21. react_agent_harness-0.8.0/tests/test_persistent_agent.py +0 -439
  22. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/LICENSE +0 -0
  23. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/agents/__init__.py +0 -0
  24. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/__init__.py +0 -0
  25. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/annotation.py +0 -0
  26. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/checkpoint.py +0 -0
  27. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/events.py +0 -0
  28. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/executor_bridge.py +0 -0
  29. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/hitl.py +0 -0
  30. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/__init__.py +0 -0
  31. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/_streaming.py +0 -0
  32. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/anthropic.py +0 -0
  33. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/auth.py +0 -0
  34. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/claude_code.py +0 -0
  35. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/fallback.py +0 -0
  36. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/openai.py +0 -0
  37. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/openai_codex.py +0 -0
  38. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/llm/routing.py +0 -0
  39. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/oauth_browser.py +0 -0
  40. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/otel.py +0 -0
  41. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/runtime.py +0 -0
  42. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/steering.py +0 -0
  43. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/streaming.py +0 -0
  44. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/tool_policy.py +0 -0
  45. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/trace.py +0 -0
  46. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/trace_viewer.py +0 -0
  47. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/harness/utils.py +0 -0
  48. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/__init__.py +0 -0
  49. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/episodic_lance.py +0 -0
  50. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/manager.py +0 -0
  51. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/redis_store.py +0 -0
  52. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/stores.py +0 -0
  53. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/memory/working.py +0 -0
  54. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/orchestrator/__init__.py +0 -0
  55. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/orchestrator/planner.py +0 -0
  56. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  57. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/entry_points.txt +0 -0
  58. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/requires.txt +0 -0
  59. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/top_level.txt +0 -0
  60. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/setup.cfg +0 -0
  61. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_agents_base.py +0 -0
  62. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_annotation.py +0 -0
  63. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_anthropic_llm.py +0 -0
  64. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_budget_guard.py +0 -0
  65. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_checkpoint_resume.py +0 -0
  66. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_claude_code_llm.py +0 -0
  67. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_cli.py +0 -0
  68. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_console_renderer.py +0 -0
  69. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_executor_bridge.py +0 -0
  70. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_fallback_llm.py +0 -0
  71. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_fan_in.py +0 -0
  72. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_http_fetch.py +0 -0
  73. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_llm_auth.py +0 -0
  74. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_mcp_adapter.py +0 -0
  75. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_mcp_auth.py +0 -0
  76. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_memory.py +0 -0
  77. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_memory_reconciler.py +0 -0
  78. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_memory_touchpoints.py +0 -0
  79. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_oauth_browser.py +0 -0
  80. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_openai_codex_llm.py +0 -0
  81. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_openai_llm.py +0 -0
  82. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_orchestrator.py +0 -0
  83. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_otel.py +0 -0
  84. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_parse_action_json.py +0 -0
  85. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_per_call_site_llm.py +0 -0
  86. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_redis_store.py +0 -0
  87. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_routing_llm.py +0 -0
  88. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_steering.py +0 -0
  89. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_streaming.py +0 -0
  90. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_subagent_tool.py +0 -0
  91. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_tool_policy.py +0 -0
  92. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_trace.py +0 -0
  93. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_utils.py +0 -0
  94. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_vision.py +0 -0
  95. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tests/test_working_memory.py +0 -0
  96. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/__init__.py +0 -0
  97. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/builtin/__init__.py +0 -0
  98. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/builtin/fetch_image.py +0 -0
  99. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/builtin/http_fetch.py +0 -0
  100. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/builtin/subagent.py +0 -0
  101. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/mcp/__init__.py +0 -0
  102. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/mcp/adapter.py +0 -0
  103. {react_agent_harness-0.8.0 → react_agent_harness-0.9.1}/tools/mcp/auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: react-agent-harness
3
- Version: 0.8.0
3
+ Version: 0.9.1
4
4
  Summary: Multi-agent LLM orchestration: hybrid DAG planning, two-tier memory, streaming, cost/token budgets with per-call-site breakdown
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
@@ -643,12 +643,105 @@ Use `app.capabilities()` to inspect the already-wired coordinator,
643
643
  sub-agents, and MCP tools. The demo exposes this with
644
644
  `--show-capabilities`.
645
645
 
646
+ Persistent sessions also expose a small control surface for user interfaces:
647
+
648
+ ```python
649
+ state = await app.session_state("thread-1")
650
+ print(state.tokens_in_total, state.tokens_out_total)
651
+ sessions = await app.list_sessions()
652
+ matches = await app.list_sessions(query="research")
653
+ cached = app.cached_memory_context("thread-1")
654
+ await app.save_to_memory("thread-1") # reconcile pending turns, keep cache warm
655
+ await app.force_compact("thread-1") # structural reorg (summary + trim + reconcile + evict)
656
+ app.forget_memory_cache("thread-1")
657
+ await app.clear_session("thread-1") # clear transcript only; memory retained
658
+ await app.delete_session("thread-1") # delete transcript only; memory retained
659
+ ```
660
+
661
+ There is deliberately no `close()` method — the SQLite transcript is the
662
+ durable record, and any of `chat`/`save_to_memory`/`force_compact` on the
663
+ same `session_id` later will resume from it. To exit, just stop calling
664
+ `chat` (and let the process end).
665
+
666
+ For simple REPLs, `PersistentCommandHandler` maps slash commands to those
667
+ primitives and returns structured results:
668
+
669
+ ```python
670
+ from harness.persistent_controls import PersistentCommandHandler
671
+
672
+ controls = PersistentCommandHandler(app)
673
+ result = await controls.handle("/sessions research", session_id=session_id)
674
+ if result.session_id:
675
+ session_id = result.session_id
676
+ if result.text:
677
+ print(result.text)
678
+ ```
679
+
680
+ The command surface is defined once in `SLASH_COMMAND_SPECS` and exposed via
681
+ `slash_command_specs()`. Tab-completion in the demo binds those specs to
682
+ `prompt_toolkit` via `SlashCommandCompleter`:
683
+
684
+ ```python
685
+ from prompt_toolkit import PromptSession
686
+ from prompt_toolkit.history import FileHistory
687
+ from harness.persistent_completion import SlashCommandCompleter
688
+
689
+ session = PromptSession(
690
+ history=FileHistory("~/.agent-harness/demo_history"),
691
+ completer=SlashCommandCompleter(app),
692
+ complete_while_typing=False, # Tab-triggered; doesn't query the store every keystroke
693
+ )
694
+ message = (await session.prompt_async("> ")).strip()
695
+ ```
696
+
697
+ Name completion comes from the spec registry; session-id arguments call
698
+ `app.list_sessions(query=...)` (SQLite pushes the filter down to
699
+ `lower(session_id) LIKE ?` so per-keystroke cost stays bounded). Other UIs
700
+ (web autocomplete, fzf, IDE plugins) should consume `slash_command_specs()`
701
+ directly without importing the prompt_toolkit binding.
702
+
703
+ The demo uses that utility for:
704
+
705
+ - `/capabilities`, `/agents`, `/mcp` inspect wired agents and tools
706
+ - `/session` shows turns, context-pressure estimate, reconcile cadence, and summary
707
+ - `/usage` shows persisted total and last-run provider-reported token usage
708
+ - `/sessions [query]` lists known session ids, optionally filtered by id text
709
+ - `/memory` shows the cached per-session memory context
710
+ - `/save` flushes turns after the last reconcile checkpoint into long-term memory **without** evicting the cached prior (foreground prefix stays warm)
711
+ - `/compact` forces a structural reorg — summary + trim + reconcile + cache evict — used when the transcript is bloating, not for routine "save"
712
+ - `/forget` evicts cached memory context so the next turn refetches it
713
+ - `/switch <id>` resumes or creates a logical session id
714
+ - `/new [id]` starts a fresh session id and refuses to collide with an existing id
715
+ - `/clear` clears the current transcript/summary/counters; long-term memory is retained
716
+ - `/delete [id] confirm` deletes a transcript row; long-term memory is retained
717
+ - `/end` exits the demo — no auto-flush; call `/save` first if you want pending facts persisted
718
+
719
+ **Press `Esc` during a turn to cancel it.** Every example that streams a
720
+ `BusEvent` loop wraps it in `ConsoleRenderer.render_stream(events, *,
721
+ terminal_event_type=...)` — one call that renders each event, captures
722
+ the top-level terminal (TASK_DONE / DONE), and listens for Esc on stdin.
723
+ The cancel raises `asyncio.CancelledError` through the agent's `await`
724
+ points, which propagates out of `PersistentAgent.chat` (and every other
725
+ stream) before `_finalize_turn` runs — so a cancelled turn writes
726
+ nothing to the session store, matching the standard chat-UX "cancelled
727
+ turn = never happened" semantic.
728
+
729
+ The underlying primitives in `harness/cancellation.py` are reusable for
730
+ any "run X but stop early on Y" pattern: `run_until_cancelled(coro, *,
731
+ trigger)` races a coroutine against an `asyncio.Event`,
732
+ `escape_listener(trigger)` is the prompt_toolkit Esc binding,
733
+ `consume_with_cancel(events, *, on_event)` is the renderer-agnostic
734
+ lower-level form for demos that need bespoke per-event handling (e.g.
735
+ `complex_sysaudit_demo.py` capturing a custom DONE payload). The Esc
736
+ binding is a no-op on non-TTY stdin, so the same code paths work for
737
+ pipe / file / CI input without conditional wiring.
738
+
646
739
  Each chat turn gets a fresh `WorkingMemory`. Continuity comes from the
647
740
  SQLite session state (rolling summary + recent messages) and normal
648
741
  `MemoryManager` recall, not from carrying old ReAct scratchpads forever.
649
742
 
650
743
  **Prefix-cache aware.** The full prompt stays byte-identical across plain
651
- chat turns within a compaction window. Three things make that work:
744
+ chat turns within a compaction window. Four things make that work:
652
745
 
653
746
  1. The accumulated session transcript is sent to the coordinator as real
654
747
  `user`/`assistant` role messages — not folded into one inline-rendered
@@ -658,20 +751,40 @@ chat turns within a compaction window. Three things make that work:
658
751
  pinned user-message prior, **not in the system prompt**. The system
659
752
  prompt is now pure agent identity + tool list + ReAct format — purely
660
753
  static. Memory context is fetched once per session, cached on the
661
- `PersistentAgent`, and refreshed only at compaction or high-signal
662
- reconcile (so it doesn't shift turn-to-turn just because the goal
663
- changed).
664
- 3. Long-term memory writes are **deferred to compaction**, not fired
665
- periodically. The session transcript is the per-turn journal — facts
666
- land in long-term memory only when we're already breaking cache (at
667
- compaction or high-signal events like tool runs / "remember" terms).
668
- The legacy `reconcile_every_turns` knob is a no-op.
754
+ `PersistentAgent`, and refreshed only at compaction or explicit
755
+ "remember" signals.
756
+ 3. **Compaction triggers on context-size pressure, not turn counts.**
757
+ `compact_at_context_fraction=0.5` (default) reads the coordinator
758
+ LLM's `input_token_budget` and fires when the transcript crosses
759
+ ~50% of it. After compaction, `retain_context_fraction=0.15`
760
+ keeps the newest messages that fit in ~15% of the input budget
761
+ verbatim and folds older messages into the rolling summary.
762
+ Chat-only sessions go thousands of turns between
763
+ compactions; browser-heavy sessions compact when budget pressure
764
+ actually warrants it.
765
+ 4. **Background memory accumulation, foreground cache stability.**
766
+ Every `async_reconcile_every_turns` turns (default 10), a
767
+ non-blocking `write_run_end` samples the last N turn-pairs from the
768
+ durable transcript and updates long-term memory — but does **not**
769
+ evict the per-session memory cache. New facts are immediately
770
+ visible to OTHER sessions; THIS session sees them at the next
771
+ compaction (where the cache is already breaking for the summary
772
+ refresh).
669
773
 
670
774
  OpenAI's automatic prefix cache and Anthropic's `cache_control` markers
671
- both match on longest-identical prefix. Together these three changes let
672
- a typical session pay one cold compaction every ~12 turns plus ~K turns
673
- of warm-prefix hits in between, instead of paying full price every
674
- turn.
775
+ both match on longest-identical prefix. Together these four changes let
776
+ a typical session pay one cold compaction when the transcript actually
777
+ fills the context window, with warm cache hits on every turn in
778
+ between, while still accumulating memory in the background.
779
+
780
+ The legacy `reconcile_every_turns`, `compact_every_turns`, and
781
+ `compact_message_threshold` knobs have been **removed** — passing them
782
+ to `PersistentAgentConfig` is a clear `TypeError` rather than a silent
783
+ no-op so existing user code can be updated explicitly. Reconciliation
784
+ fires on (a) user-explicit `remember` / `prefer` / `always` / etc.
785
+ signals (immediate, evicts cache), (b) periodic background async path
786
+ (non-blocking, no eviction), or (c) compaction (with the summary LLM
787
+ call, evicts cache).
675
788
 
676
789
  The demo stores local state under `~/.agent-harness` by default:
677
790
 
@@ -697,11 +810,13 @@ python examples/persistent_agent_demo.py --provider claude-code
697
810
  The wrapper owns cadence:
698
811
 
699
812
  - session transcript is written every turn without an LLM;
700
- - `MemoryManager.write_run_end(...)` is called only when the turn has a
701
- durable signal, tool/sub-agent work, errors, or the configured interval
702
- has elapsed;
703
- - session compaction runs at message/turn thresholds and updates the
704
- stored summary.
813
+ - `MemoryManager.write_run_end(...)` runs synchronously only for explicit
814
+ durable user signals such as "remember" / "prefer" / "always";
815
+ - background async reconciliation samples the durable transcript every
816
+ `async_reconcile_every_turns` turns without evicting the current
817
+ session's memory-context cache;
818
+ - session compaction runs under context pressure and updates the stored
819
+ summary while trimming older transcript messages.
705
820
 
706
821
  For MCP, put MCP tools on the coordinator or sub-agents before wrapping.
707
822
  `PersistentAgent` does not special-case MCP auth; it preserves the existing
@@ -311,9 +311,25 @@ class BaseAgent:
311
311
  check_key=self._ckp_id,
312
312
  ) as hint:
313
313
  async for event in self._run_stream_internal(run_id):
314
- if event.type == EventType.TASK_DONE:
315
- await self._clear_checkpoint(run_id)
316
- hint.done = True
314
+ # ``parent_agent_id`` filtering: sub-agent events bubble up
315
+ # through this loop tagged with their invoker's id. A sub's
316
+ # TASK_DONE / ERROR is NOT terminal for the outer agent —
317
+ # the outer keeps running. Without this guard the FIRST
318
+ # delegated sub-agent that completes would wrongly clear
319
+ # the outer's checkpoint and suppress its resume hint.
320
+ if not event.parent_agent_id:
321
+ if event.type == EventType.TASK_DONE:
322
+ await self._clear_checkpoint(run_id)
323
+ hint.done = True
324
+ elif event.type == EventType.ERROR:
325
+ # Terminal ERROR (max_steps, budget exceeded, mid-run
326
+ # crash translated to ERROR by ``_run_stream_internal``)
327
+ # is "the agent ran to completion but failed", NOT a
328
+ # user interrupt. Suppress the misleading "interrupted
329
+ # — Resume:" banner; leave the checkpoint intact so the
330
+ # user can deliberately resume with new config (higher
331
+ # max_steps, larger budget) if they want.
332
+ hint.done = True
317
333
  yield event
318
334
 
319
335
  async def _resume_stream(
@@ -350,9 +366,17 @@ class BaseAgent:
350
366
  check_key=self._ckp_id,
351
367
  ) as hint:
352
368
  async for event in self._run_stream_internal(run_id, start_step=start_step):
353
- if event.type == EventType.TASK_DONE:
354
- await self._clear_checkpoint(run_id)
355
- hint.done = True
369
+ # See ``run_stream`` for why both branches gate on
370
+ # ``not event.parent_agent_id`` (sub-agent terminals are
371
+ # not terminal for the outer) and why a top-level ERROR
372
+ # marks ``done`` without clearing the checkpoint
373
+ # (it's "ran-but-failed", not an interrupt).
374
+ if not event.parent_agent_id:
375
+ if event.type == EventType.TASK_DONE:
376
+ await self._clear_checkpoint(run_id)
377
+ hint.done = True
378
+ elif event.type == EventType.ERROR:
379
+ hint.done = True
356
380
  yield event
357
381
 
358
382
  async def _run_stream_internal(
@@ -829,7 +853,12 @@ class BaseAgent:
829
853
  into the action JSON and yields it as a THOUGHT event. Otherwise
830
854
  falls back to one `complete` call.
831
855
  """
832
- messages = self._working_memory.get_messages()
856
+ # Working memory stores the system prompt as a role="system"
857
+ # entry for uniform summarisation + token accounting; split it
858
+ # back out here so Anthropic's top-level ``system=`` contract is
859
+ # honoured. OpenAI's adapter re-injects it inline when needed.
860
+ # See ``_split_system`` docstring for the full rationale.
861
+ system_text, messages = _split_system(self._working_memory.get_messages())
833
862
  accumulated = ""
834
863
  before_usage = self._working_memory.context_usage()
835
864
  before_summarizations = self._working_memory.summarization_count
@@ -853,7 +882,7 @@ class BaseAgent:
853
882
  # don't take the kwarg (older custom stubs) get it via
854
883
  # ``**kwargs`` and ignore it.
855
884
  async for token in self._llm.stream_complete(
856
- system=None,
885
+ system=system_text,
857
886
  messages=messages,
858
887
  source=react_source,
859
888
  response_format={"type": "json_object"},
@@ -868,13 +897,14 @@ class BaseAgent:
868
897
  response = _normalize_response(accumulated)
869
898
  if response is None:
870
899
  response = await self._retry_complete_after_bad_stream(
900
+ system_text=system_text,
871
901
  messages=messages,
872
902
  react_source=react_source,
873
903
  accumulated=accumulated,
874
904
  )
875
905
  else:
876
906
  raw = await self._llm.complete(
877
- system=None,
907
+ system=system_text,
878
908
  messages=messages,
879
909
  response_format={"type": "json_object"},
880
910
  source=react_source,
@@ -934,6 +964,7 @@ class BaseAgent:
934
964
  async def _retry_complete_after_bad_stream(
935
965
  self,
936
966
  *,
967
+ system_text: str | None,
937
968
  messages: list[dict],
938
969
  react_source: str,
939
970
  accumulated: str,
@@ -946,7 +977,7 @@ class BaseAgent:
946
977
  )
947
978
  try:
948
979
  raw = await self._llm.complete(
949
- system=None,
980
+ system=system_text,
950
981
  messages=[
951
982
  *messages,
952
983
  {
@@ -1275,6 +1306,51 @@ class BaseAgent:
1275
1306
  await self._commit_checkpoint(run_id, step)
1276
1307
 
1277
1308
 
1309
+ # ── LLM call shaping (module-level for testability) ──────────────────────────
1310
+
1311
+
1312
+ def _split_system(messages: list[dict]) -> tuple[str | None, list[dict]]:
1313
+ """Pull system-role entries out of a messages list and join them.
1314
+
1315
+ Returns ``(system_text, non_system_messages)``. ``system_text`` is the
1316
+ concatenation of every ``role == "system"`` entry's ``content``
1317
+ (joined with a blank line) or ``None`` when no system entries are
1318
+ present.
1319
+
1320
+ Why this exists
1321
+ ---------------
1322
+ ``BaseAgent`` keeps the system prompt inside ``WorkingMemory`` (as a
1323
+ pinned ``role="system"`` entry) so summarisation, token accounting,
1324
+ and checkpoint serialisation treat it uniformly with every other
1325
+ message. But the two LLM adapter contracts diverge at the wire:
1326
+
1327
+ - **OpenAI** accepts ``role="system"`` entries *inside* the messages
1328
+ array — passing ``system=None`` + an inline system entry works.
1329
+ - **Anthropic** requires the system prompt as a *top-level* ``system=``
1330
+ parameter and ``_build_messages`` silently drops any
1331
+ ``role="system"`` entries in the messages list. Passing
1332
+ ``system=None`` + an inline system entry causes the entire system
1333
+ prompt to be discarded — the model sees only the user turn.
1334
+
1335
+ Splitting at the call boundary picks up any system entries (including
1336
+ those that arrived via ``prior_messages`` priors, not just the one
1337
+ BaseAgent appended itself), produces one joined system string, and
1338
+ leaves the rest as a clean user/assistant transcript. Both adapter
1339
+ contracts are then satisfied identically.
1340
+ """
1341
+ system_parts: list[str] = []
1342
+ rest: list[dict] = []
1343
+ for m in messages:
1344
+ if m.get("role") == "system":
1345
+ content = m.get("content", "")
1346
+ if isinstance(content, str) and content:
1347
+ system_parts.append(content)
1348
+ continue
1349
+ rest.append(m)
1350
+ system_text = "\n\n".join(system_parts) if system_parts else None
1351
+ return system_text, rest
1352
+
1353
+
1278
1354
  # ── Response normalization (module-level for testability) ────────────────────
1279
1355
 
1280
1356
 
@@ -0,0 +1,186 @@
1
+ """User-initiated cancellation for streaming agent runs.
2
+
3
+ Two layers:
4
+
5
+ - ``run_until_cancelled`` runs an awaitable as an ``asyncio.Task`` and
6
+ cancels it when a caller-supplied ``trigger`` event fires. Pure
7
+ asyncio; no UI dependency. Reusable for any "run X but stop early on
8
+ Y" pattern — REPL turns, batch jobs, scheduled probes.
9
+
10
+ - ``escape_listener`` is a prompt_toolkit-backed async context manager
11
+ that sets a trigger event when the user presses Escape. Composes with
12
+ ``run_until_cancelled`` to give CLIs the standard "press Esc to
13
+ cancel the current turn" affordance.
14
+
15
+ Agent code itself does not need to know about cancellation —
16
+ ``asyncio.CancelledError`` propagates naturally through every ``await``
17
+ and through ``async for`` over an async generator. Cleanup happens via
18
+ ordinary ``try/finally`` blocks where they already exist. The
19
+ ``PersistentAgent.chat`` flow is shaped so that mid-stream cancellation
20
+ writes nothing to the session store (``_finalize_turn`` only runs on
21
+ ``TASK_DONE``/``ERROR`` or at clean generator end), which matches the
22
+ standard chat-UX semantic of "cancelled turn = never happened".
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import sys
29
+ from collections.abc import AsyncIterator, Awaitable, Callable
30
+ from contextlib import asynccontextmanager
31
+ from typing import TYPE_CHECKING, TypeVar
32
+
33
+ if TYPE_CHECKING:
34
+ from harness.events import BusEvent
35
+
36
+ T = TypeVar("T")
37
+
38
+
39
+ async def run_until_cancelled(
40
+ coro_factory: Callable[[], Awaitable[T]],
41
+ *,
42
+ trigger: asyncio.Event,
43
+ ) -> tuple[bool, T | None]:
44
+ """Run ``coro_factory()`` until it finishes or ``trigger`` fires.
45
+
46
+ Returns ``(cancelled, result)``:
47
+
48
+ - ``cancelled`` is ``True`` if the trigger fired before the
49
+ coroutine finished; the task was then cancelled and awaited so any
50
+ ``finally`` cleanup completed before this function returned.
51
+ ``result`` is ``None`` in this case.
52
+ - ``cancelled`` is ``False`` if the coroutine completed first;
53
+ ``result`` is the coroutine's return value. Any waiter on the
54
+ trigger is cancelled before returning.
55
+
56
+ The trigger is cleared at entry so the caller can reuse the same
57
+ event across many turns. If the trigger was already set before this
58
+ call, the coroutine still gets a chance to start and run for at
59
+ least one event-loop tick — clearing-then-checking would otherwise
60
+ race with a key press that arrived just before this turn began.
61
+ """
62
+ trigger.clear()
63
+ task: asyncio.Task[T] = asyncio.create_task(coro_factory())
64
+ waiter: asyncio.Task[bool] = asyncio.create_task(trigger.wait())
65
+ try:
66
+ done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)
67
+ except asyncio.CancelledError:
68
+ # Outer cancellation — propagate inward so neither child leaks.
69
+ task.cancel()
70
+ waiter.cancel()
71
+ raise
72
+
73
+ if waiter in done and not task.done():
74
+ task.cancel()
75
+ try:
76
+ await task
77
+ except asyncio.CancelledError:
78
+ pass
79
+ except Exception:
80
+ # Cancellation path is best-effort; the caller has already
81
+ # observed "user wanted to stop" — don't shadow that with a
82
+ # late exception from the cancelled task.
83
+ pass
84
+ return True, None
85
+
86
+ # Task completed (or errored) first; stop the trigger waiter.
87
+ waiter.cancel()
88
+ try:
89
+ await waiter
90
+ except asyncio.CancelledError:
91
+ pass
92
+ return False, task.result()
93
+
94
+
95
+ @asynccontextmanager
96
+ async def escape_listener(trigger: asyncio.Event) -> AsyncIterator[None]:
97
+ """Set ``trigger`` when the user presses Escape on stdin.
98
+
99
+ Active only for the duration of the ``async with`` block. Uses
100
+ prompt_toolkit's input abstraction so terminal mode handling stays
101
+ correct across platforms and so it composes cleanly with
102
+ ``PromptSession`` used elsewhere in the same process.
103
+
104
+ No-ops (yields immediately, never sets ``trigger``) when:
105
+
106
+ - ``stdin`` is not a TTY (pipe / file / no terminal) — keypress
107
+ capture doesn't apply.
108
+ - prompt_toolkit's input cannot be created on this platform / shell
109
+ configuration — surfacing a startup error here would mask the
110
+ user's actual workload. The trigger simply stays unset, matching
111
+ the pre-Esc-feature behavior.
112
+ """
113
+ if not sys.stdin.isatty():
114
+ yield
115
+ return
116
+
117
+ # Local import so consumers that don't need ESC handling (e.g. unit
118
+ # tests that exercise ``run_until_cancelled`` alone) don't pay the
119
+ # prompt_toolkit import cost or its terminal capability probing.
120
+ try:
121
+ from prompt_toolkit.input import create_input
122
+ from prompt_toolkit.keys import Keys
123
+ except Exception: # noqa: BLE001 — best-effort UI feature
124
+ yield
125
+ return
126
+
127
+ try:
128
+ input_obj = create_input()
129
+ except Exception: # noqa: BLE001 — terminal config refused; degrade silently
130
+ yield
131
+ return
132
+
133
+ def _on_input_ready() -> None:
134
+ # Read all currently-available key presses; trigger on the first
135
+ # Escape seen. Other keys are deliberately dropped — this is a
136
+ # cancel listener, not an input layer, and the active
137
+ # ``async for`` over chat events doesn't expect any user input.
138
+ try:
139
+ for key_press in input_obj.read_keys():
140
+ if key_press.key == Keys.Escape:
141
+ trigger.set()
142
+ return
143
+ except Exception: # noqa: BLE001 — listener must not raise into the loop
144
+ return
145
+
146
+ # ``raw_mode()`` disables canonical line buffering + echo so we
147
+ # actually see Escape as a keypress rather than after the user hits
148
+ # Enter. ``attach()`` registers ``_on_input_ready`` with the running
149
+ # event loop's reader for ``input_obj``'s file descriptor.
150
+ try:
151
+ with input_obj.raw_mode():
152
+ with input_obj.attach(_on_input_ready):
153
+ yield
154
+ except Exception: # noqa: BLE001 — terminal manipulation failed mid-flight
155
+ yield
156
+
157
+
158
+ async def consume_with_cancel(
159
+ events: AsyncIterator[BusEvent],
160
+ *,
161
+ on_event: Callable[[BusEvent], None],
162
+ ) -> bool:
163
+ """Consume a ``BusEvent`` async iterator until completion or user Esc.
164
+
165
+ Returns ``True`` if the user pressed Escape (the stream was
166
+ cancelled mid-flight); ``False`` if the stream completed naturally.
167
+ The caller's ``on_event`` callback runs for every event up to the
168
+ cancel point — rendering, final-result extraction, parent-agent
169
+ filtering all live in the callback so this helper stays
170
+ UI-agnostic.
171
+
172
+ Most consumers should use ``ConsoleRenderer.render_stream`` instead;
173
+ this lower-level helper is for renderers that aren't
174
+ ``ConsoleRenderer`` (web UI, JSON-stream output, custom orchestrator
175
+ demos that render a bespoke report on DONE) or that need
176
+ per-event logic the renderer method doesn't expose.
177
+ """
178
+ cancel_event = asyncio.Event()
179
+
180
+ async def _drain() -> None:
181
+ async for event in events:
182
+ on_event(event)
183
+
184
+ async with escape_listener(cancel_event):
185
+ cancelled, _ = await run_until_cancelled(_drain, trigger=cancel_event)
186
+ return cancelled
@@ -204,14 +204,17 @@ def _policy_clear(path: Path) -> int:
204
204
 
205
205
 
206
206
  async def _trace_replay(path: str, *, realtime: bool, speed: float) -> int:
207
- """Read a JSONL trace and render it via ConsoleRenderer."""
208
- from harness.console import ConsoleRenderer
209
- from harness.trace import replay
207
+ """Read a JSONL trace and render it via ConsoleRenderer.
208
+
209
+ Esc cancels the replay — useful when ``--realtime`` is in effect and
210
+ the original run was long.
211
+ """
212
+ from harness.console import ConsoleRenderer # noqa: PLC0415
213
+ from harness.trace import replay # noqa: PLC0415
210
214
 
211
215
  renderer = ConsoleRenderer()
212
- async for event in replay(path, realtime=realtime, speed=speed):
213
- renderer.render(event)
214
- return 0
216
+ cancelled, _ = await renderer.render_stream(replay(path, realtime=realtime, speed=speed))
217
+ return 130 if cancelled else 0
215
218
 
216
219
 
217
220
  if __name__ == "__main__":
@@ -4,11 +4,29 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import sys
7
- from typing import TextIO
7
+ from collections.abc import AsyncIterator
8
+ from typing import NamedTuple, TextIO
8
9
 
9
10
  from harness.events import BusEvent, EventType
10
11
 
11
12
 
13
+ class StreamResult(NamedTuple):
14
+ """Return shape of ``ConsoleRenderer.render_stream``.
15
+
16
+ ``cancelled`` is True when the user pressed Esc mid-stream (only
17
+ possible on TTY stdin; non-TTY hosts never set it). ``terminal`` is
18
+ the last event matching the requested ``terminal_event_type`` (and,
19
+ when ``top_level_only`` is True, having no ``parent_agent_id``), or
20
+ None when no such event arrived before cancellation / end-of-stream.
21
+
22
+ Tuple shape so callers can write ``cancelled, terminal = await
23
+ renderer.render_stream(...)`` without importing the class.
24
+ """
25
+
26
+ cancelled: bool
27
+ terminal: BusEvent | None
28
+
29
+
12
30
  def trunc(s: str, n: int) -> str:
13
31
  """Truncate *s* to *n* characters, appending '…' when clipped."""
14
32
  return s if len(s) <= n else s[:n] + "…"
@@ -226,6 +244,51 @@ class ConsoleRenderer:
226
244
  file=self._out,
227
245
  )
228
246
 
247
+ async def render_stream(
248
+ self,
249
+ events: AsyncIterator[BusEvent],
250
+ *,
251
+ terminal_event_type: EventType | None = None,
252
+ top_level_only: bool = True,
253
+ cancel_message: str = "[cancelled by user]",
254
+ print_cancel_banner: bool = True,
255
+ ) -> StreamResult:
256
+ """Render an event stream until completion or user Esc.
257
+
258
+ Composes the rendering loop (``self.render``), the per-event
259
+ terminal capture (so callers don't repeat the "find last
260
+ TASK_DONE / DONE" boilerplate), and the Esc-cancel listener from
261
+ ``harness.cancellation`` into one call. Most consumers only need
262
+ this — the lower-level ``consume_with_cancel`` is the escape
263
+ hatch for bespoke per-event handling (orchestrator demos that
264
+ print a custom report on DONE, etc.).
265
+
266
+ Returns ``StreamResult(cancelled, terminal)``. Defaults to
267
+ printing a banner when ``cancelled`` so call sites don't repeat
268
+ the ``sep / print / sep`` pattern; pass
269
+ ``print_cancel_banner=False`` to suppress.
270
+ """
271
+ # Local import keeps ``ConsoleRenderer`` light to import for
272
+ # consumers that never render a stream (snapshot/JSON output etc.).
273
+ from harness.cancellation import consume_with_cancel # noqa: PLC0415
274
+
275
+ terminal_holder: list[BusEvent | None] = [None]
276
+
277
+ def _on_event(event: BusEvent) -> None:
278
+ self.render(event)
279
+ if terminal_event_type is None or event.type != terminal_event_type:
280
+ return
281
+ if top_level_only and event.parent_agent_id:
282
+ return
283
+ terminal_holder[0] = event
284
+
285
+ cancelled = await consume_with_cancel(events, on_event=_on_event)
286
+ if cancelled and print_cancel_banner:
287
+ self.sep("═")
288
+ print(cancel_message, file=self._out)
289
+ self.sep("═")
290
+ return StreamResult(cancelled=cancelled, terminal=terminal_holder[0])
291
+
229
292
  # ── private helpers ───────────────────────────────────────────────────────
230
293
 
231
294
  def _label(self, event: BusEvent) -> str: