react-agent-harness 0.11.0__tar.gz → 0.12.0__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 (121) hide show
  1. {react_agent_harness-0.11.0/react_agent_harness.egg-info → react_agent_harness-0.12.0}/PKG-INFO +3 -3
  2. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/agents/base.py +37 -85
  3. react_agent_harness-0.12.0/harness/agent_tree.py +52 -0
  4. react_agent_harness-0.12.0/harness/background_tasks.py +217 -0
  5. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/console.py +112 -4
  6. react_agent_harness-0.12.0/harness/events.py +454 -0
  7. react_agent_harness-0.12.0/harness/model_switching.py +124 -0
  8. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/persistent.py +98 -992
  9. react_agent_harness-0.12.0/harness/plan_mode.py +280 -0
  10. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/runtime.py +5 -17
  11. react_agent_harness-0.12.0/harness/session_memory.py +479 -0
  12. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/orchestrator/planner.py +19 -38
  13. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/pyproject.toml +20 -3
  14. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0/react_agent_harness.egg-info}/PKG-INFO +3 -3
  15. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/react_agent_harness.egg-info/SOURCES.txt +11 -0
  16. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/react_agent_harness.egg-info/requires.txt +2 -2
  17. react_agent_harness-0.12.0/tests/test_background_tasks.py +146 -0
  18. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_console_renderer.py +135 -1
  19. react_agent_harness-0.12.0/tests/test_event_payloads.py +199 -0
  20. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_mcp_auth.py +14 -0
  21. react_agent_harness-0.12.0/tests/test_mcp_streamable_http.py +99 -0
  22. react_agent_harness-0.12.0/tests/test_model_switching.py +147 -0
  23. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_persistent_agent.py +8 -8
  24. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_plan_mode.py +3 -2
  25. react_agent_harness-0.12.0/tests/test_plan_mode_controller.py +187 -0
  26. react_agent_harness-0.12.0/tests/test_session_memory.py +216 -0
  27. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/builtin/subagent.py +12 -15
  28. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/mcp/adapter.py +17 -7
  29. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/mcp/auth.py +5 -5
  30. react_agent_harness-0.11.0/harness/events.py +0 -78
  31. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/LICENSE +0 -0
  32. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/README.md +0 -0
  33. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/agents/__init__.py +0 -0
  34. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/__init__.py +0 -0
  35. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/annotation.py +0 -0
  36. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/cancellation.py +0 -0
  37. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/checkpoint.py +0 -0
  38. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/cli.py +0 -0
  39. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/executor_bridge.py +0 -0
  40. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/hitl.py +0 -0
  41. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/__init__.py +0 -0
  42. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/_streaming.py +0 -0
  43. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/anthropic.py +0 -0
  44. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/auth.py +0 -0
  45. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/claude_code.py +0 -0
  46. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/fallback.py +0 -0
  47. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/openai.py +0 -0
  48. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/openai_codex.py +0 -0
  49. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/llm/routing.py +0 -0
  50. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/oauth_browser.py +0 -0
  51. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/otel.py +0 -0
  52. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/persistent_completion.py +0 -0
  53. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/persistent_controls.py +0 -0
  54. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/persistent_prompt.py +0 -0
  55. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/skills.py +0 -0
  56. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/steering.py +0 -0
  57. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/streaming.py +0 -0
  58. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/tool_policy.py +0 -0
  59. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/trace.py +0 -0
  60. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/trace_viewer.py +0 -0
  61. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/harness/utils.py +0 -0
  62. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/__init__.py +0 -0
  63. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/episodic_lance.py +0 -0
  64. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/manager.py +0 -0
  65. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/redis_store.py +0 -0
  66. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/stores.py +0 -0
  67. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/memory/working.py +0 -0
  68. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/orchestrator/__init__.py +0 -0
  69. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  70. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/react_agent_harness.egg-info/entry_points.txt +0 -0
  71. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/react_agent_harness.egg-info/top_level.txt +0 -0
  72. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/setup.cfg +0 -0
  73. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_agents_base.py +0 -0
  74. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_annotation.py +0 -0
  75. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_anthropic_llm.py +0 -0
  76. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_budget_guard.py +0 -0
  77. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_cancellation.py +0 -0
  78. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_checkpoint_resume.py +0 -0
  79. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_claude_code_llm.py +0 -0
  80. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_cli.py +0 -0
  81. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_executor_bridge.py +0 -0
  82. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_fallback_llm.py +0 -0
  83. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_fan_in.py +0 -0
  84. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_hitl_banner.py +0 -0
  85. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_http_fetch.py +0 -0
  86. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_llm_auth.py +0 -0
  87. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_mcp_adapter.py +0 -0
  88. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_memory.py +0 -0
  89. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_memory_reconciler.py +0 -0
  90. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_memory_touchpoints.py +0 -0
  91. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_oauth_browser.py +0 -0
  92. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_openai_codex_llm.py +0 -0
  93. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_openai_llm.py +0 -0
  94. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_orchestrator.py +0 -0
  95. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_otel.py +0 -0
  96. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_parse_action_json.py +0 -0
  97. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_per_call_site_llm.py +0 -0
  98. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_persistent_completion.py +0 -0
  99. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_persistent_controls.py +0 -0
  100. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_persistent_prompt.py +0 -0
  101. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_plan_approval.py +0 -0
  102. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_redis_store.py +0 -0
  103. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_resume_hint_banner.py +0 -0
  104. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_routing_llm.py +0 -0
  105. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_skills.py +0 -0
  106. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_steering.py +0 -0
  107. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_streaming.py +0 -0
  108. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_subagent_tool.py +0 -0
  109. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_system_prompt_routing.py +0 -0
  110. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_tool_policy.py +0 -0
  111. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_trace.py +0 -0
  112. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_trailing_assistant_state.py +0 -0
  113. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_utils.py +0 -0
  114. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_vision.py +0 -0
  115. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tests/test_working_memory.py +0 -0
  116. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/__init__.py +0 -0
  117. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/builtin/__init__.py +0 -0
  118. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/builtin/background.py +0 -0
  119. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/builtin/fetch_image.py +0 -0
  120. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/builtin/http_fetch.py +0 -0
  121. {react_agent_harness-0.11.0 → react_agent_harness-0.12.0}/tools/mcp/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: react-agent-harness
3
- Version: 0.11.0
3
+ Version: 0.12.0
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
@@ -18,7 +18,7 @@ Requires-Dist: openai>=1.0; extra == "openai"
18
18
  Provides-Extra: http
19
19
  Requires-Dist: httpx>=0.27; extra == "http"
20
20
  Provides-Extra: mcp
21
- Requires-Dist: mcp>=1.0; extra == "mcp"
21
+ Requires-Dist: mcp>=2; extra == "mcp"
22
22
  Provides-Extra: otel
23
23
  Requires-Dist: opentelemetry-api>=1.20; extra == "otel"
24
24
  Requires-Dist: opentelemetry-sdk>=1.20; extra == "otel"
@@ -34,7 +34,7 @@ Requires-Dist: fakeredis>=2.20; extra == "dev"
34
34
  Requires-Dist: httpx>=0.27; extra == "dev"
35
35
  Requires-Dist: openai>=1.0; extra == "dev"
36
36
  Requires-Dist: respx>=0.21; extra == "dev"
37
- Requires-Dist: mcp>=1.0; extra == "dev"
37
+ Requires-Dist: mcp>=2; extra == "dev"
38
38
  Requires-Dist: opentelemetry-api>=1.20; extra == "dev"
39
39
  Requires-Dist: opentelemetry-sdk>=1.20; extra == "dev"
40
40
  Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20; extra == "dev"
@@ -255,11 +255,7 @@ class BaseAgent:
255
255
  self.config.agent_id,
256
256
  {"step": step, "text": text},
257
257
  )
258
- yield BusEvent(
259
- type=EventType.HUMAN_GUIDANCE,
260
- agent_id=self.config.agent_id,
261
- payload={"step": step, "text": text},
262
- )
258
+ yield BusEvent.human_guidance(self.config.agent_id, step=step, text=text)
263
259
 
264
260
  # ── Streaming entry point (canonical) ─────────────────────────────────────
265
261
 
@@ -403,11 +399,7 @@ class BaseAgent:
403
399
  yield event
404
400
  except Exception as e:
405
401
  logger.exception("Agent %s stream crashed", self.config.agent_id)
406
- yield BusEvent(
407
- type=EventType.ERROR,
408
- agent_id=self.config.agent_id,
409
- error=str(e),
410
- )
402
+ yield BusEvent.error_event(self.config.agent_id, error=str(e))
411
403
  finally:
412
404
  if self._working_memory is not None:
413
405
  self._tracer.log(
@@ -533,11 +525,7 @@ class BaseAgent:
533
525
  self.config.agent_id,
534
526
  {"answer": "", "confidence": 0.0, "steps": step, "error": reason},
535
527
  )
536
- yield BusEvent(
537
- type=EventType.ERROR,
538
- agent_id=self.config.agent_id,
539
- error=reason,
540
- )
528
+ yield BusEvent.error_event(self.config.agent_id, error=reason)
541
529
  return
542
530
 
543
531
  self._tracer.log(
@@ -587,11 +575,7 @@ class BaseAgent:
587
575
  "error": "",
588
576
  },
589
577
  )
590
- yield BusEvent(
591
- type=EventType.TASK_DONE,
592
- agent_id=self.config.agent_id,
593
- payload=result,
594
- )
578
+ yield BusEvent.task_done_agent(self.config.agent_id, result=result)
595
579
  return
596
580
 
597
581
  # Act — parallel or single
@@ -622,14 +606,11 @@ class BaseAgent:
622
606
 
623
607
  # Emit ACTION events first so callers see what's being launched.
624
608
  for act in parallel_actions:
625
- yield BusEvent(
626
- type=EventType.ACTION,
627
- agent_id=self.config.agent_id,
628
- payload={
629
- "step": step,
630
- "tool": act.get("tool", ""),
631
- "args": act.get("args", {}),
632
- },
609
+ yield BusEvent.action(
610
+ self.config.agent_id,
611
+ step=step,
612
+ tool=act.get("tool", ""),
613
+ args=act.get("args", {}),
633
614
  )
634
615
 
635
616
  # Fan out all approved tool calls concurrently. Mixed
@@ -723,10 +704,11 @@ class BaseAgent:
723
704
  },
724
705
  )
725
706
  observation_events.append(
726
- BusEvent(
727
- type=EventType.OBSERVATION,
728
- agent_id=self.config.agent_id,
729
- payload={"step": step, "tool": tool_name, "observation": obs_raw},
707
+ BusEvent.observation(
708
+ self.config.agent_id,
709
+ step=step,
710
+ tool=tool_name,
711
+ observation=obs_raw,
730
712
  )
731
713
  )
732
714
  combined.append({"tool": tool_name, "result": obs_raw})
@@ -753,10 +735,8 @@ class BaseAgent:
753
735
  # Single action path.
754
736
  tool_name = response.get("action", "")
755
737
  tool_args = response.get("args", {})
756
- yield BusEvent(
757
- type=EventType.ACTION,
758
- agent_id=self.config.agent_id,
759
- payload={"step": step, "tool": tool_name, "args": tool_args},
738
+ yield BusEvent.action(
739
+ self.config.agent_id, step=step, tool=tool_name, args=tool_args
760
740
  )
761
741
 
762
742
  tool_obj = self._tools.get(tool_name)
@@ -798,14 +778,8 @@ class BaseAgent:
798
778
  "observation": obs_display,
799
779
  },
800
780
  )
801
- yield BusEvent(
802
- type=EventType.OBSERVATION,
803
- agent_id=self.config.agent_id,
804
- payload={
805
- "step": step,
806
- "tool": tool_name,
807
- "observation": obs_raw,
808
- },
781
+ yield BusEvent.observation(
782
+ self.config.agent_id, step=step, tool=tool_name, observation=obs_raw
809
783
  )
810
784
 
811
785
  if (
@@ -833,11 +807,10 @@ class BaseAgent:
833
807
  "error": f"Max steps ({self.config.max_steps}) reached",
834
808
  },
835
809
  )
836
- yield BusEvent(
837
- type=EventType.ERROR,
838
- agent_id=self.config.agent_id,
810
+ yield BusEvent.error_event(
811
+ self.config.agent_id,
839
812
  error=f"Max steps ({self.config.max_steps}) reached",
840
- payload={"steps": self.config.max_steps},
813
+ steps=self.config.max_steps,
841
814
  )
842
815
 
843
816
  # ── Think ─────────────────────────────────────────────────────────────────
@@ -900,11 +873,7 @@ class BaseAgent:
900
873
  ):
901
874
  accumulated += token
902
875
  if self.config.stream_tokens:
903
- yield BusEvent(
904
- type=EventType.TOKEN,
905
- agent_id=self.config.agent_id,
906
- token=token,
907
- )
876
+ yield BusEvent.token_event(self.config.agent_id, token=token)
908
877
  response = _normalize_response(accumulated)
909
878
  if response is None:
910
879
  response = await self._retry_complete_after_bad_stream(
@@ -938,39 +907,24 @@ class BaseAgent:
938
907
 
939
908
  after_usage = self._working_memory.context_usage()
940
909
  if self._working_memory.summarization_count > before_summarizations:
941
- yield BusEvent(
942
- type=EventType.MEMORY,
943
- agent_id=self.config.agent_id,
944
- payload={
945
- "event": "summarized",
946
- "before": before_usage,
947
- "after": after_usage,
948
- "summarizations": self._working_memory.summarization_count,
949
- },
910
+ yield BusEvent.memory(
911
+ self.config.agent_id,
912
+ before=before_usage,
913
+ after=after_usage,
914
+ summarizations=self._working_memory.summarization_count,
950
915
  )
951
916
  llm_usage = getattr(self._llm, "last_usage", None) or {}
952
917
  if llm_usage or after_usage != before_usage:
953
- yield BusEvent(
954
- type=EventType.CONTEXT,
955
- agent_id=self.config.agent_id,
956
- payload={
957
- **after_usage,
958
- "tokens_in": llm_usage.get("tokens_in"),
959
- "tokens_out": llm_usage.get("tokens_out"),
960
- "cache_read_tokens": llm_usage.get("cache_read_tokens"),
961
- "cache_creation_tokens": llm_usage.get("cache_creation_tokens"),
962
- },
918
+ yield BusEvent.context_usage(
919
+ self.config.agent_id,
920
+ usage=after_usage,
921
+ tokens_in=llm_usage.get("tokens_in"),
922
+ tokens_out=llm_usage.get("tokens_out"),
923
+ cache_read_tokens=llm_usage.get("cache_read_tokens"),
924
+ cache_creation_tokens=llm_usage.get("cache_creation_tokens"),
963
925
  )
964
926
 
965
- yield BusEvent(
966
- type=EventType.THOUGHT,
967
- agent_id=self.config.agent_id,
968
- payload={
969
- "response": response,
970
- "thought": response.get("thought", "") if response else "",
971
- "action": response.get("action") if response else None,
972
- },
973
- )
927
+ yield BusEvent.thought(self.config.agent_id, response=response)
974
928
 
975
929
  async def _retry_complete_after_bad_stream(
976
930
  self,
@@ -1363,10 +1317,8 @@ class BaseAgent:
1363
1317
  )
1364
1318
  await self._record_tool_observation(llm_response, tool_name, observation)
1365
1319
  obs_display = "[image]" if _is_image_block(observation) else str(observation)[:500]
1366
- yield BusEvent(
1367
- type=EventType.OBSERVATION,
1368
- agent_id=self.config.agent_id,
1369
- payload={"step": step, "tool": tool_name, "observation": obs_display},
1320
+ yield BusEvent.observation(
1321
+ self.config.agent_id, step=step, tool=tool_name, observation=obs_display
1370
1322
  )
1371
1323
  await self._commit_checkpoint(run_id, step)
1372
1324
 
@@ -0,0 +1,52 @@
1
+ """Agent-tree traversal shared across the persistent-agent concerns.
2
+
3
+ A coordinator ``BaseAgent`` may have ``SubAgentTool``s wired in as tools, each
4
+ wrapping another ``BaseAgent`` (which may itself delegate further). Model
5
+ switching, background tasks, and guard assignment all need to walk this tree.
6
+ These pure helpers are the single place that knows its shape.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ if TYPE_CHECKING:
14
+ from agents.base import BaseAgent
15
+
16
+
17
+ def subagent_tool_agent(tool: Any) -> BaseAgent | None:
18
+ """Return the ``BaseAgent`` wrapped by a ``SubAgentTool``, else ``None``."""
19
+ from agents.base import BaseAgent # noqa: PLC0415 — avoid import cycle at module load
20
+
21
+ if tool.__class__.__name__ != "SubAgentTool":
22
+ return None
23
+ agent = getattr(tool, "_agent", None)
24
+ return agent if isinstance(agent, BaseAgent) else None
25
+
26
+
27
+ def iter_agents(coordinator: BaseAgent) -> list[BaseAgent]:
28
+ """Return the coordinator and every sub-agent reachable through its tools,
29
+ depth-first, each visited once."""
30
+ agents: list[BaseAgent] = []
31
+ seen: set[int] = set()
32
+
33
+ def visit(agent: BaseAgent) -> None:
34
+ if id(agent) in seen:
35
+ return
36
+ seen.add(id(agent))
37
+ agents.append(agent)
38
+ for tool in getattr(agent, "_tools", {}).values():
39
+ sub = subagent_tool_agent(tool)
40
+ if sub is not None:
41
+ visit(sub)
42
+
43
+ visit(coordinator)
44
+ return agents
45
+
46
+
47
+ def find_agent(coordinator: BaseAgent, agent_id: str) -> BaseAgent | None:
48
+ """Return the reachable agent whose ``config.agent_id`` matches, else ``None``."""
49
+ for agent in iter_agents(coordinator):
50
+ if agent.config.agent_id == agent_id:
51
+ return agent
52
+ return None
@@ -0,0 +1,217 @@
1
+ """Process-local background sub-agent task management for ``PersistentAgent``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import uuid
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass, field
9
+ from datetime import datetime, timezone
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from harness.agent_tree import find_agent, subagent_tool_agent
13
+ from harness.events import EventType
14
+ from tools.builtin.background import (
15
+ BackgroundDelegateTool,
16
+ CheckBackgroundTaskTool,
17
+ CollectBackgroundTaskTool,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from agents.base import BaseAgent
22
+
23
+
24
+ def _now() -> str:
25
+ return datetime.now(timezone.utc).isoformat()
26
+
27
+
28
+ @dataclass
29
+ class BackgroundTaskState:
30
+ """Process-local background sub-agent task metadata."""
31
+
32
+ task_id: str
33
+ session_id: str
34
+ agent_id: str
35
+ instruction: str
36
+ status: str = "running"
37
+ answer: str = ""
38
+ confidence: float = 0.0
39
+ steps: int = 0
40
+ error: str = ""
41
+ collected: bool = False
42
+ created_at: str = field(default_factory=_now)
43
+ updated_at: str = field(default_factory=_now)
44
+
45
+
46
+ class BackgroundTaskManager:
47
+ """Own background sub-agent task state and LLM-visible task tools."""
48
+
49
+ def __init__(
50
+ self,
51
+ *,
52
+ coordinator: BaseAgent,
53
+ session_store: Any,
54
+ session_id_provider: Callable[[], str],
55
+ apply_overrides: Callable[[Any], None],
56
+ session_message_factory: Callable[[str], Any],
57
+ ) -> None:
58
+ self._coordinator = coordinator
59
+ self._session_store = session_store
60
+ self._session_id_provider = session_id_provider
61
+ self._apply_overrides = apply_overrides
62
+ self._session_message_factory = session_message_factory
63
+ self._tasks: dict[str, BackgroundTaskState] = {}
64
+ self._handles: dict[str, asyncio.Task[None]] = {}
65
+
66
+ async def start(
67
+ self,
68
+ session_id: str,
69
+ agent_id: str,
70
+ instruction: str,
71
+ ) -> BackgroundTaskState:
72
+ instruction = instruction.strip()
73
+ if not instruction:
74
+ raise ValueError("background task instruction is required")
75
+ agent = find_agent(self._coordinator, agent_id)
76
+ if agent is None or agent is self._coordinator:
77
+ raise ValueError(f"unknown sub-agent {agent_id!r}")
78
+ if self._session_id_provider() != session_id:
79
+ state = await self._session_store.load(session_id)
80
+ self._apply_overrides(state)
81
+ task_id = f"bg_{uuid.uuid4().hex[:12]}"
82
+ task = BackgroundTaskState(
83
+ task_id=task_id,
84
+ session_id=session_id,
85
+ agent_id=agent_id,
86
+ instruction=instruction,
87
+ )
88
+ self._tasks[task_id] = task
89
+ self._handles[task_id] = asyncio.create_task(self._run(task, agent))
90
+ return copy_background_task(task)
91
+
92
+ async def list(self, session_id: str | None = None) -> list[BackgroundTaskState]:
93
+ tasks = self._tasks.values()
94
+ if session_id is not None:
95
+ tasks = [task for task in tasks if task.session_id == session_id]
96
+ return sorted(
97
+ (copy_background_task(task) for task in tasks),
98
+ key=lambda task: task.created_at,
99
+ reverse=True,
100
+ )
101
+
102
+ async def collect(self, session_id: str, task_id: str) -> BackgroundTaskState:
103
+ task = self._tasks.get(task_id)
104
+ if task is None or task.session_id != session_id:
105
+ raise ValueError(f"background task not found: {task_id}")
106
+ if task.status == "running":
107
+ raise ValueError(f"background task still running: {task_id}")
108
+ if not task.collected:
109
+ await self._session_store.append_messages(
110
+ session_id,
111
+ [self._session_message_factory(render_background_result(task))],
112
+ )
113
+ task.collected = True
114
+ task.updated_at = _now()
115
+ return copy_background_task(task)
116
+
117
+ async def cancel(self, session_id: str, task_id: str) -> BackgroundTaskState:
118
+ task = self._tasks.get(task_id)
119
+ if task is None or task.session_id != session_id:
120
+ raise ValueError(f"background task not found: {task_id}")
121
+ handle = self._handles.get(task_id)
122
+ if task.status == "running" and handle is not None and not handle.done():
123
+ handle.cancel()
124
+ task.status = "cancelled"
125
+ task.error = "cancelled by user"
126
+ task.updated_at = _now()
127
+ return copy_background_task(task)
128
+
129
+ def install_tools(self) -> None:
130
+ tools = getattr(self._coordinator, "_tools", {})
131
+ if not isinstance(tools, dict):
132
+ return
133
+ background_tools: dict[str, Any] = {}
134
+ for tool in list(tools.values()):
135
+ sub = subagent_tool_agent(tool)
136
+ if sub is None:
137
+ continue
138
+ background = BackgroundDelegateTool(
139
+ agent_id=sub.config.agent_id,
140
+ start_task=self.start,
141
+ session_id_provider=self._session_id_provider,
142
+ )
143
+ background_tools.setdefault(background.name, background)
144
+ if background_tools:
145
+ background_tools.setdefault(
146
+ CheckBackgroundTaskTool.name,
147
+ CheckBackgroundTaskTool(
148
+ list_tasks=self.list,
149
+ session_id_provider=self._session_id_provider,
150
+ ),
151
+ )
152
+ background_tools.setdefault(
153
+ CollectBackgroundTaskTool.name,
154
+ CollectBackgroundTaskTool(
155
+ collect_task=self.collect,
156
+ session_id_provider=self._session_id_provider,
157
+ ),
158
+ )
159
+ for name, tool in background_tools.items():
160
+ tools.setdefault(name, tool)
161
+ if name not in self._coordinator.config.allowed_tools:
162
+ self._coordinator.config.allowed_tools.append(name)
163
+
164
+ async def _run(self, task: BackgroundTaskState, agent: BaseAgent) -> None:
165
+ last_done: dict[str, Any] | None = None
166
+ last_error = ""
167
+ try:
168
+ async for event in agent.run_stream(
169
+ task=task.instruction,
170
+ run_id=task.task_id,
171
+ ):
172
+ if event.type == EventType.TASK_DONE:
173
+ last_done = event.payload
174
+ elif event.type == EventType.ERROR:
175
+ last_error = event.error
176
+ except asyncio.CancelledError:
177
+ task.status = "cancelled"
178
+ task.error = "cancelled by user"
179
+ raise
180
+ except Exception as exc: # noqa: BLE001 — store for /tasks
181
+ task.status = "failed"
182
+ task.error = f"{type(exc).__name__}: {exc}"
183
+ else:
184
+ if last_done is not None:
185
+ task.status = "done"
186
+ task.answer = str(last_done.get("answer", ""))
187
+ task.confidence = float(last_done.get("confidence", 0.0) or 0.0)
188
+ task.steps = int(last_done.get("steps", 0) or 0)
189
+ else:
190
+ task.status = "failed"
191
+ task.error = last_error or "sub-agent stream ended without TASK_DONE"
192
+ finally:
193
+ task.updated_at = _now()
194
+
195
+
196
+ def copy_background_task(task: BackgroundTaskState) -> BackgroundTaskState:
197
+ return BackgroundTaskState(
198
+ task_id=task.task_id,
199
+ session_id=task.session_id,
200
+ agent_id=task.agent_id,
201
+ instruction=task.instruction,
202
+ status=task.status,
203
+ answer=task.answer,
204
+ confidence=task.confidence,
205
+ steps=task.steps,
206
+ error=task.error,
207
+ collected=task.collected,
208
+ created_at=task.created_at,
209
+ updated_at=task.updated_at,
210
+ )
211
+
212
+
213
+ def render_background_result(task: BackgroundTaskState) -> str:
214
+ header = f"[Background task {task.task_id}] {task.agent_id} {task.status}: {task.instruction}"
215
+ if task.status == "done":
216
+ return f"{header}\n\n{task.answer}\n\nconfidence={task.confidence:.2f} steps={task.steps}"
217
+ return f"{header}\n\nerror: {task.error or task.status}"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import shutil
6
7
  import sys
7
8
  import threading
8
9
  from collections.abc import AsyncIterator
@@ -34,6 +35,65 @@ def trunc(s: str, n: int) -> str:
34
35
  return s if len(s) <= n else s[:n] + "…"
35
36
 
36
37
 
38
+ def clip_middle(s: str, n: int) -> str:
39
+ """Fit *s* into *n* characters by eliding its middle.
40
+
41
+ Unlike :func:`trunc` this keeps the end of the line, which is where a
42
+ single-line tool result (a status, an error) usually carries its point.
43
+ """
44
+ if len(s) <= n or n <= 1:
45
+ return trunc(s, n)
46
+ head = (n - 1) * 2 // 3
47
+ tail = n - 1 - head
48
+ return f"{s[:head]}…{s[-tail:]}" if tail else f"{s[:head]}…"
49
+
50
+
51
+ class _Excerpt(NamedTuple):
52
+ """A head+tail view of multi-line text, with the middle elided.
53
+
54
+ Tool output carries context at the top (the command, a header row) and
55
+ the verdict at the bottom, so both ends are worth keeping.
56
+ """
57
+
58
+ head: list[str]
59
+ tail: list[str]
60
+ elided: int
61
+ total_lines: int
62
+ total_chars: int
63
+
64
+ @property
65
+ def truncated(self) -> bool:
66
+ return self.elided > 0
67
+
68
+
69
+ def excerpt(text: str, *, head_lines: int, tail_lines: int) -> _Excerpt:
70
+ """Split *text* into leading and trailing line windows.
71
+
72
+ When the text fits within ``head_lines + tail_lines`` every line lands in
73
+ ``head`` and ``tail`` is empty, so callers can render the two windows
74
+ unconditionally.
75
+ """
76
+ head_lines = max(0, head_lines)
77
+ tail_lines = max(0, tail_lines)
78
+ lines = text.splitlines()
79
+ total = len(lines)
80
+ if total <= head_lines + tail_lines:
81
+ return _Excerpt(
82
+ head=lines,
83
+ tail=[],
84
+ elided=0,
85
+ total_lines=total,
86
+ total_chars=len(text),
87
+ )
88
+ return _Excerpt(
89
+ head=lines[:head_lines],
90
+ tail=lines[total - tail_lines :] if tail_lines else [],
91
+ elided=total - head_lines - tail_lines,
92
+ total_lines=total,
93
+ total_chars=len(text),
94
+ )
95
+
96
+
37
97
  class ConsoleRenderer:
38
98
  """Renders BusEvent objects to a text stream.
39
99
 
@@ -48,6 +108,12 @@ class ConsoleRenderer:
48
108
  show_tokens: If True, TOKEN events are printed inline.
49
109
  spinner: If True, show a TTY-only busy spinner between events.
50
110
  spinner_delay: Seconds to wait before drawing the spinner.
111
+ excerpt_large_outputs: Render large observations as a head+tail excerpt
112
+ instead of first-N-character truncation.
113
+ excerpt_head_lines: Lines to show from the start of an observation.
114
+ excerpt_tail_lines: Lines to show from the end of an observation.
115
+ width: Display width for excerpt lines; None auto-detects
116
+ the terminal size at render time.
51
117
  out: Output stream (defaults to ``sys.stdout``).
52
118
  """
53
119
 
@@ -61,6 +127,10 @@ class ConsoleRenderer:
61
127
  show_tokens: bool = False,
62
128
  spinner: bool = True,
63
129
  spinner_delay: float = 0.4,
130
+ excerpt_large_outputs: bool = True,
131
+ excerpt_head_lines: int = 2,
132
+ excerpt_tail_lines: int = 5,
133
+ width: int | None = None,
64
134
  out: TextIO | None = None,
65
135
  ) -> None:
66
136
  self._truncate = truncate
@@ -68,6 +138,10 @@ class ConsoleRenderer:
68
138
  self._sep_width = sep_width
69
139
  self._label_w = agent_label_width
70
140
  self._show_tokens = show_tokens
141
+ self._excerpt_large_outputs = excerpt_large_outputs
142
+ self._excerpt_head_lines = excerpt_head_lines
143
+ self._excerpt_tail_lines = excerpt_tail_lines
144
+ self._width = width
71
145
  self._out = out or sys.stdout
72
146
  self._in_token_stream = False
73
147
  is_tty = bool(getattr(self._out, "isatty", lambda: False)())
@@ -190,10 +264,7 @@ class ConsoleRenderer:
190
264
 
191
265
  elif t == EventType.OBSERVATION:
192
266
  obs = p.get("observation", "")
193
- print(
194
- f"{self._label(event)} obs {trunc(obs, 110)}",
195
- file=self._out,
196
- )
267
+ self._render_observation(event, str(obs))
197
268
 
198
269
  elif t == EventType.CONTEXT:
199
270
  tokens = int(p.get("tokens") or 0)
@@ -391,6 +462,43 @@ class ConsoleRenderer:
391
462
  return f"[{event.agent_id:<{self._label_w}}]"
392
463
  return f"[{event.type.value:<{self._label_w}}]"
393
464
 
465
+ def _render_observation(self, event: BusEvent, obs: str) -> None:
466
+ label = self._label(event)
467
+ large = len(obs) > self._truncate or "\n" in obs
468
+ if not (self._excerpt_large_outputs and large):
469
+ print(f"{label} obs {trunc(obs, self._truncate)}", file=self._out)
470
+ return
471
+
472
+ view = excerpt(
473
+ obs,
474
+ head_lines=self._excerpt_head_lines,
475
+ tail_lines=self._excerpt_tail_lines,
476
+ )
477
+ self._print_excerpt(label, view)
478
+
479
+ def _print_excerpt(self, label: str, view: _Excerpt) -> None:
480
+ shown = len(view.head) + len(view.tail)
481
+ if view.truncated:
482
+ summary = f"{shown} of {view.total_lines:,} lines / {view.total_chars:,} chars"
483
+ else:
484
+ plural = "" if view.total_lines == 1 else "s"
485
+ summary = f"{view.total_lines:,} line{plural} / {view.total_chars:,} chars"
486
+ print(f"{label} obs [{summary}]", file=self._out)
487
+
488
+ indent = self._label_w + 11
489
+ avail = max(20, self._line_width() - indent - 1)
490
+ for line in view.head:
491
+ print(f"{'':<{indent}}{clip_middle(line, avail)}", file=self._out)
492
+ if view.truncated:
493
+ print(f"{'':<{indent}}… {view.elided:,} lines elided …", file=self._out)
494
+ for line in view.tail:
495
+ print(f"{'':<{indent}}{clip_middle(line, avail)}", file=self._out)
496
+
497
+ def _line_width(self) -> int:
498
+ if self._width is not None:
499
+ return self._width
500
+ return shutil.get_terminal_size((100, 24)).columns
501
+
394
502
  def _schedule_spinner(self, event: BusEvent) -> None:
395
503
  label = self._spinner_label(event)
396
504
  if label: