react-agent-harness 0.9.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 (102) hide show
  1. {react_agent_harness-0.9.0/react_agent_harness.egg-info → react_agent_harness-0.9.1}/PKG-INFO +1 -1
  2. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/README.md +20 -0
  3. {react_agent_harness-0.9.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.9.0 → react_agent_harness-0.9.1}/harness/cli.py +9 -6
  6. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/console.py +64 -1
  7. react_agent_harness-0.9.1/harness/persistent_prompt.py +150 -0
  8. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/pyproject.toml +1 -1
  9. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1/react_agent_harness.egg-info}/PKG-INFO +1 -1
  10. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/SOURCES.txt +6 -0
  11. react_agent_harness-0.9.1/tests/test_cancellation.py +314 -0
  12. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_persistent_agent.py +13 -5
  13. react_agent_harness-0.9.1/tests/test_persistent_prompt.py +192 -0
  14. react_agent_harness-0.9.1/tests/test_resume_hint_banner.py +300 -0
  15. react_agent_harness-0.9.1/tests/test_system_prompt_routing.py +165 -0
  16. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/LICENSE +0 -0
  17. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/agents/__init__.py +0 -0
  18. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/__init__.py +0 -0
  19. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/annotation.py +0 -0
  20. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/checkpoint.py +0 -0
  21. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/events.py +0 -0
  22. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/executor_bridge.py +0 -0
  23. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/hitl.py +0 -0
  24. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/__init__.py +0 -0
  25. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/_streaming.py +0 -0
  26. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/anthropic.py +0 -0
  27. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/auth.py +0 -0
  28. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/claude_code.py +0 -0
  29. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/fallback.py +0 -0
  30. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/openai.py +0 -0
  31. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/openai_codex.py +0 -0
  32. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/llm/routing.py +0 -0
  33. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/oauth_browser.py +0 -0
  34. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/otel.py +0 -0
  35. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/persistent.py +0 -0
  36. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/persistent_completion.py +0 -0
  37. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/persistent_controls.py +0 -0
  38. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/runtime.py +0 -0
  39. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/steering.py +0 -0
  40. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/streaming.py +0 -0
  41. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/tool_policy.py +0 -0
  42. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/trace.py +0 -0
  43. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/trace_viewer.py +0 -0
  44. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/harness/utils.py +0 -0
  45. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/__init__.py +0 -0
  46. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/episodic_lance.py +0 -0
  47. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/manager.py +0 -0
  48. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/redis_store.py +0 -0
  49. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/stores.py +0 -0
  50. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/memory/working.py +0 -0
  51. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/orchestrator/__init__.py +0 -0
  52. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/orchestrator/planner.py +0 -0
  53. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  54. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/entry_points.txt +0 -0
  55. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/requires.txt +0 -0
  56. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/react_agent_harness.egg-info/top_level.txt +0 -0
  57. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/setup.cfg +0 -0
  58. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_agents_base.py +0 -0
  59. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_annotation.py +0 -0
  60. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_anthropic_llm.py +0 -0
  61. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_budget_guard.py +0 -0
  62. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_checkpoint_resume.py +0 -0
  63. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_claude_code_llm.py +0 -0
  64. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_cli.py +0 -0
  65. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_console_renderer.py +0 -0
  66. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_executor_bridge.py +0 -0
  67. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_fallback_llm.py +0 -0
  68. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_fan_in.py +0 -0
  69. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_http_fetch.py +0 -0
  70. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_llm_auth.py +0 -0
  71. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_mcp_adapter.py +0 -0
  72. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_mcp_auth.py +0 -0
  73. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_memory.py +0 -0
  74. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_memory_reconciler.py +0 -0
  75. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_memory_touchpoints.py +0 -0
  76. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_oauth_browser.py +0 -0
  77. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_openai_codex_llm.py +0 -0
  78. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_openai_llm.py +0 -0
  79. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_orchestrator.py +0 -0
  80. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_otel.py +0 -0
  81. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_parse_action_json.py +0 -0
  82. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_per_call_site_llm.py +0 -0
  83. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_persistent_completion.py +0 -0
  84. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_persistent_controls.py +0 -0
  85. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_redis_store.py +0 -0
  86. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_routing_llm.py +0 -0
  87. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_steering.py +0 -0
  88. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_streaming.py +0 -0
  89. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_subagent_tool.py +0 -0
  90. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_tool_policy.py +0 -0
  91. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_trace.py +0 -0
  92. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_utils.py +0 -0
  93. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_vision.py +0 -0
  94. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tests/test_working_memory.py +0 -0
  95. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/__init__.py +0 -0
  96. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/builtin/__init__.py +0 -0
  97. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/builtin/fetch_image.py +0 -0
  98. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/builtin/http_fetch.py +0 -0
  99. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/builtin/subagent.py +0 -0
  100. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/mcp/__init__.py +0 -0
  101. {react_agent_harness-0.9.0 → react_agent_harness-0.9.1}/tools/mcp/adapter.py +0 -0
  102. {react_agent_harness-0.9.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.9.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
@@ -716,6 +716,26 @@ The demo uses that utility for:
716
716
  - `/delete [id] confirm` deletes a transcript row; long-term memory is retained
717
717
  - `/end` exits the demo — no auto-flush; call `/save` first if you want pending facts persisted
718
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
+
719
739
  Each chat turn gets a fresh `WorkingMemory`. Continuity comes from the
720
740
  SQLite session state (rolling summary + recent messages) and normal
721
741
  `MemoryManager` recall, not from carrying old ReAct scratchpads forever.
@@ -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:
@@ -0,0 +1,150 @@
1
+ """prompt_toolkit ``PromptSession`` factory for ``PersistentAgent`` chat UIs.
2
+
3
+ The slash-command spec + completer live in ``persistent_controls`` /
4
+ ``persistent_completion``. This module handles the third piece of the
5
+ input layer: assembling a ``PromptSession`` with the chat-style key
6
+ bindings (Enter to submit, Ctrl+J / Esc-Enter for newline), command
7
+ completion, and persistent history, so demos and downstream CLIs don't
8
+ re-derive the same wiring.
9
+
10
+ Why a helper, not a per-demo block: multi-line input, slash-command
11
+ completion, and command history are baseline expectations of a chat
12
+ CLI — not demo-specific UX choices. Encoding them in the library
13
+ means every consumer gets the same defaults and the bug surface stays
14
+ in one place.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Iterable
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING, Any
22
+
23
+ from prompt_toolkit import PromptSession
24
+ from prompt_toolkit.filters import has_completions
25
+ from prompt_toolkit.history import FileHistory, History, InMemoryHistory
26
+ from prompt_toolkit.key_binding import KeyBindings
27
+
28
+ from harness.persistent_completion import SlashCommandCompleter
29
+
30
+ if TYPE_CHECKING:
31
+ from prompt_toolkit.completion import Completer
32
+
33
+ from harness.persistent import PersistentAgent
34
+
35
+
36
+ def build_chat_prompt_session(
37
+ app: PersistentAgent | None = None,
38
+ *,
39
+ history_path: str | Path | None = None,
40
+ completer: Completer | None = None,
41
+ multiline: bool = True,
42
+ complete_while_typing: bool = False,
43
+ extra_key_bindings: KeyBindings | None = None,
44
+ ) -> PromptSession[str]:
45
+ """Construct a ``PromptSession`` suitable for multi-turn chat input.
46
+
47
+ Defaults (each one overridable via the corresponding kwarg):
48
+
49
+ - ``multiline=True``: buffer can hold and render multiple lines.
50
+ - **Enter** submits — overrides prompt_toolkit's default in multiline
51
+ mode (which inserts a newline) so the prompt feels like a regular
52
+ chat input. Yielded to the completer dropdown when one is open, so
53
+ Enter still picks a Tab-completion candidate before being treated
54
+ as submit.
55
+ - **Ctrl+J** and **Esc-Enter** (Meta-Enter / Alt-Enter) insert a
56
+ literal newline. Two bindings because some terminals strip Esc
57
+ modifiers, and Ctrl+J is the convention modern AI CLIs use.
58
+ - ``complete_while_typing=False``: Tab-triggered completion. The
59
+ session-id completer otherwise hits the store on every keystroke.
60
+ - ``completer=SlashCommandCompleter(app)`` when ``app`` is given.
61
+ Pass ``completer=...`` to override (e.g. a richer completer that
62
+ composes the slash-command one with something else); pass
63
+ ``completer=None`` *and* ``app=None`` to disable completion
64
+ entirely (single-input demos that don't need slash commands).
65
+ - History at ``history_path`` when provided
66
+ (``FileHistory(history_path)``). Parent directory is created on
67
+ demand. Pass ``history_path=None`` for ephemeral in-memory history.
68
+
69
+ ``extra_key_bindings`` are merged after the chat defaults, so user
70
+ bindings can override them.
71
+ """
72
+ bindings = _chat_key_bindings()
73
+ if extra_key_bindings is not None:
74
+ # KeyBindings.add_binding via merge: prompt_toolkit's
75
+ # merge_key_bindings is the proper composition primitive when
76
+ # the caller wants to extend without losing defaults.
77
+ from prompt_toolkit.key_binding import merge_key_bindings # noqa: PLC0415
78
+
79
+ merged = merge_key_bindings([bindings, extra_key_bindings])
80
+ else:
81
+ merged = bindings
82
+
83
+ if completer is None and app is not None:
84
+ completer = SlashCommandCompleter(app)
85
+
86
+ history = _resolve_history(history_path)
87
+
88
+ return PromptSession(
89
+ history=history,
90
+ completer=completer,
91
+ complete_while_typing=complete_while_typing,
92
+ multiline=multiline,
93
+ key_bindings=merged,
94
+ )
95
+
96
+
97
+ def _chat_key_bindings() -> KeyBindings:
98
+ """The default keybinding set for chat-style multi-line input.
99
+
100
+ Kept as a module-level factory so tests can introspect the bindings
101
+ independently of constructing a full ``PromptSession``.
102
+ """
103
+ bindings = KeyBindings()
104
+
105
+ @bindings.add("enter", filter=~has_completions)
106
+ def _submit(event: Any) -> None:
107
+ # In multiline mode prompt_toolkit's default for Enter is
108
+ # "insert newline". Override to submit — but only when the
109
+ # completer dropdown isn't open. ``~has_completions`` yields
110
+ # Enter to the completer when it's showing, so Tab-then-Enter
111
+ # picks a completion without accidentally submitting.
112
+ event.current_buffer.validate_and_handle()
113
+
114
+ @bindings.add("c-j")
115
+ def _ctrl_j_newline(event: Any) -> None:
116
+ # Ctrl+J is the modern-AI-CLI convention for "newline within
117
+ # the current message." On Unix terminals Ctrl+J is literally
118
+ # the line-feed byte; in single-line mode that's
119
+ # indistinguishable from Enter, which is one of the reasons
120
+ # this helper defaults to ``multiline=True``.
121
+ event.current_buffer.insert_text("\n")
122
+
123
+ @bindings.add("escape", "enter")
124
+ def _meta_enter_newline(event: Any) -> None:
125
+ # Alt-Enter / Meta-Enter / Esc-Enter — common convention from
126
+ # editors and other REPLs. Bound alongside Ctrl+J because some
127
+ # terminals strip the Esc modifier and some users have one or
128
+ # the other in muscle memory.
129
+ event.current_buffer.insert_text("\n")
130
+
131
+ return bindings
132
+
133
+
134
+ def _resolve_history(history_path: str | Path | None) -> History:
135
+ if history_path is None:
136
+ return InMemoryHistory()
137
+ path = Path(history_path).expanduser()
138
+ path.parent.mkdir(parents=True, exist_ok=True)
139
+ return FileHistory(str(path))
140
+
141
+
142
+ def _binding_handler_names(bindings: KeyBindings) -> Iterable[str]:
143
+ """Return the registered handler function names — useful for tests
144
+ asserting "Enter is bound to submit, Ctrl+J is bound to newline" without
145
+ needing to spin up a full prompt_toolkit Application.
146
+
147
+ Public for tests; not part of the supported API surface.
148
+ """
149
+ for binding in bindings.bindings:
150
+ yield binding.handler.__name__
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "react-agent-harness"
7
- version = "0.9.0"
7
+ version = "0.9.1"
8
8
  description = "Multi-agent LLM orchestration: hybrid DAG planning, two-tier memory, streaming, cost/token budgets with per-call-site breakdown"
9
9
  requires-python = ">=3.10"
10
10
  dependencies = [
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: react-agent-harness
3
- Version: 0.9.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