react-agent-harness 0.11.0__tar.gz → 0.11.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 (120) hide show
  1. {react_agent_harness-0.11.0/react_agent_harness.egg-info → react_agent_harness-0.11.1}/PKG-INFO +1 -1
  2. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/agents/base.py +37 -85
  3. react_agent_harness-0.11.1/harness/agent_tree.py +52 -0
  4. react_agent_harness-0.11.1/harness/background_tasks.py +217 -0
  5. react_agent_harness-0.11.1/harness/events.py +454 -0
  6. react_agent_harness-0.11.1/harness/model_switching.py +124 -0
  7. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/persistent.py +98 -992
  8. react_agent_harness-0.11.1/harness/plan_mode.py +280 -0
  9. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/runtime.py +5 -17
  10. react_agent_harness-0.11.1/harness/session_memory.py +479 -0
  11. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/orchestrator/planner.py +19 -38
  12. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/pyproject.toml +18 -1
  13. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1/react_agent_harness.egg-info}/PKG-INFO +1 -1
  14. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/react_agent_harness.egg-info/SOURCES.txt +10 -0
  15. react_agent_harness-0.11.1/tests/test_background_tasks.py +146 -0
  16. react_agent_harness-0.11.1/tests/test_event_payloads.py +199 -0
  17. react_agent_harness-0.11.1/tests/test_model_switching.py +147 -0
  18. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_persistent_agent.py +8 -8
  19. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_plan_mode.py +3 -2
  20. react_agent_harness-0.11.1/tests/test_plan_mode_controller.py +187 -0
  21. react_agent_harness-0.11.1/tests/test_session_memory.py +216 -0
  22. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/builtin/subagent.py +12 -15
  23. react_agent_harness-0.11.0/harness/events.py +0 -78
  24. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/LICENSE +0 -0
  25. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/README.md +0 -0
  26. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/agents/__init__.py +0 -0
  27. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/__init__.py +0 -0
  28. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/annotation.py +0 -0
  29. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/cancellation.py +0 -0
  30. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/checkpoint.py +0 -0
  31. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/cli.py +0 -0
  32. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/console.py +0 -0
  33. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/executor_bridge.py +0 -0
  34. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/hitl.py +0 -0
  35. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/__init__.py +0 -0
  36. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/_streaming.py +0 -0
  37. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/anthropic.py +0 -0
  38. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/auth.py +0 -0
  39. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/claude_code.py +0 -0
  40. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/fallback.py +0 -0
  41. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/openai.py +0 -0
  42. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/openai_codex.py +0 -0
  43. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/llm/routing.py +0 -0
  44. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/oauth_browser.py +0 -0
  45. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/otel.py +0 -0
  46. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/persistent_completion.py +0 -0
  47. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/persistent_controls.py +0 -0
  48. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/persistent_prompt.py +0 -0
  49. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/skills.py +0 -0
  50. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/steering.py +0 -0
  51. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/streaming.py +0 -0
  52. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/tool_policy.py +0 -0
  53. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/trace.py +0 -0
  54. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/trace_viewer.py +0 -0
  55. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/harness/utils.py +0 -0
  56. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/__init__.py +0 -0
  57. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/episodic_lance.py +0 -0
  58. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/manager.py +0 -0
  59. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/redis_store.py +0 -0
  60. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/stores.py +0 -0
  61. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/memory/working.py +0 -0
  62. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/orchestrator/__init__.py +0 -0
  63. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  64. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/react_agent_harness.egg-info/entry_points.txt +0 -0
  65. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/react_agent_harness.egg-info/requires.txt +0 -0
  66. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/react_agent_harness.egg-info/top_level.txt +0 -0
  67. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/setup.cfg +0 -0
  68. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_agents_base.py +0 -0
  69. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_annotation.py +0 -0
  70. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_anthropic_llm.py +0 -0
  71. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_budget_guard.py +0 -0
  72. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_cancellation.py +0 -0
  73. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_checkpoint_resume.py +0 -0
  74. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_claude_code_llm.py +0 -0
  75. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_cli.py +0 -0
  76. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_console_renderer.py +0 -0
  77. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_executor_bridge.py +0 -0
  78. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_fallback_llm.py +0 -0
  79. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_fan_in.py +0 -0
  80. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_hitl_banner.py +0 -0
  81. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_http_fetch.py +0 -0
  82. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_llm_auth.py +0 -0
  83. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_mcp_adapter.py +0 -0
  84. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_mcp_auth.py +0 -0
  85. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_memory.py +0 -0
  86. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_memory_reconciler.py +0 -0
  87. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_memory_touchpoints.py +0 -0
  88. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_oauth_browser.py +0 -0
  89. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_openai_codex_llm.py +0 -0
  90. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_openai_llm.py +0 -0
  91. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_orchestrator.py +0 -0
  92. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_otel.py +0 -0
  93. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_parse_action_json.py +0 -0
  94. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_per_call_site_llm.py +0 -0
  95. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_persistent_completion.py +0 -0
  96. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_persistent_controls.py +0 -0
  97. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_persistent_prompt.py +0 -0
  98. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_plan_approval.py +0 -0
  99. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_redis_store.py +0 -0
  100. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_resume_hint_banner.py +0 -0
  101. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_routing_llm.py +0 -0
  102. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_skills.py +0 -0
  103. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_steering.py +0 -0
  104. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_streaming.py +0 -0
  105. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_subagent_tool.py +0 -0
  106. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_system_prompt_routing.py +0 -0
  107. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_tool_policy.py +0 -0
  108. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_trace.py +0 -0
  109. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_trailing_assistant_state.py +0 -0
  110. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_utils.py +0 -0
  111. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_vision.py +0 -0
  112. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tests/test_working_memory.py +0 -0
  113. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/__init__.py +0 -0
  114. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/builtin/__init__.py +0 -0
  115. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/builtin/background.py +0 -0
  116. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/builtin/fetch_image.py +0 -0
  117. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/builtin/http_fetch.py +0 -0
  118. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/mcp/__init__.py +0 -0
  119. {react_agent_harness-0.11.0 → react_agent_harness-0.11.1}/tools/mcp/adapter.py +0 -0
  120. {react_agent_harness-0.11.0 → react_agent_harness-0.11.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.11.0
3
+ Version: 0.11.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
@@ -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}"