react-agent-harness 0.13.0__tar.gz → 0.14.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 (129) hide show
  1. {react_agent_harness-0.13.0/react_agent_harness.egg-info → react_agent_harness-0.14.0}/PKG-INFO +1 -1
  2. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/README.md +16 -3
  3. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/agents/base.py +42 -3
  4. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/pyproject.toml +1 -1
  5. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0/react_agent_harness.egg-info}/PKG-INFO +1 -1
  6. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/react_agent_harness.egg-info/SOURCES.txt +1 -0
  7. react_agent_harness-0.14.0/tests/test_resumable_delegation.py +342 -0
  8. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/builtin/subagent.py +83 -2
  9. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/LICENSE +0 -0
  10. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/agents/__init__.py +0 -0
  11. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/__init__.py +0 -0
  12. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/agent_tree.py +0 -0
  13. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/annotation.py +0 -0
  14. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/background_tasks.py +0 -0
  15. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/cancellation.py +0 -0
  16. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/checkpoint.py +0 -0
  17. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/cli.py +0 -0
  18. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/console.py +0 -0
  19. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/events.py +0 -0
  20. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/executor_bridge.py +0 -0
  21. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/hitl.py +0 -0
  22. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/__init__.py +0 -0
  23. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/_streaming.py +0 -0
  24. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/anthropic.py +0 -0
  25. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/auth.py +0 -0
  26. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/claude_code.py +0 -0
  27. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/fallback.py +0 -0
  28. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/openai.py +0 -0
  29. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/openai_codex.py +0 -0
  30. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/reasoning.py +0 -0
  31. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/llm/routing.py +0 -0
  32. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/model_switching.py +0 -0
  33. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/oauth_browser.py +0 -0
  34. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/otel.py +0 -0
  35. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/persistent.py +0 -0
  36. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/persistent_completion.py +0 -0
  37. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/persistent_controls.py +0 -0
  38. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/persistent_prompt.py +0 -0
  39. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/plan_mode.py +0 -0
  40. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/runstate.py +0 -0
  41. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/runtime.py +0 -0
  42. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/session_memory.py +0 -0
  43. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/skills.py +0 -0
  44. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/steering.py +0 -0
  45. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/streaming.py +0 -0
  46. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/tool_policy.py +0 -0
  47. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/trace.py +0 -0
  48. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/trace_viewer.py +0 -0
  49. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/harness/utils.py +0 -0
  50. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/__init__.py +0 -0
  51. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/episodic_lance.py +0 -0
  52. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/manager.py +0 -0
  53. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/redis_store.py +0 -0
  54. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/stores.py +0 -0
  55. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/memory/working.py +0 -0
  56. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/orchestrator/__init__.py +0 -0
  57. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/orchestrator/planner.py +0 -0
  58. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  59. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/react_agent_harness.egg-info/entry_points.txt +0 -0
  60. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/react_agent_harness.egg-info/requires.txt +0 -0
  61. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/react_agent_harness.egg-info/top_level.txt +0 -0
  62. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/setup.cfg +0 -0
  63. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_agents_base.py +0 -0
  64. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_annotation.py +0 -0
  65. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_anthropic_llm.py +0 -0
  66. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_background_tasks.py +0 -0
  67. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_budget_guard.py +0 -0
  68. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_budget_restore.py +0 -0
  69. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_cancellation.py +0 -0
  70. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_checkpoint_resume.py +0 -0
  71. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_claude_code_llm.py +0 -0
  72. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_cli.py +0 -0
  73. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_concurrent_same_agent.py +0 -0
  74. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_console_renderer.py +0 -0
  75. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_event_payloads.py +0 -0
  76. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_executor_bridge.py +0 -0
  77. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_fallback_llm.py +0 -0
  78. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_fan_in.py +0 -0
  79. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_hitl_banner.py +0 -0
  80. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_hitl_gate.py +0 -0
  81. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_http_fetch.py +0 -0
  82. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_llm_auth.py +0 -0
  83. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_mcp_adapter.py +0 -0
  84. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_mcp_auth.py +0 -0
  85. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_mcp_streamable_http.py +0 -0
  86. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_memory.py +0 -0
  87. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_memory_reconciler.py +0 -0
  88. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_memory_touchpoints.py +0 -0
  89. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_model_switching.py +0 -0
  90. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_oauth_browser.py +0 -0
  91. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_openai_codex_llm.py +0 -0
  92. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_openai_llm.py +0 -0
  93. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_orchestrator.py +0 -0
  94. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_orchestrator_task_state.py +0 -0
  95. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_otel.py +0 -0
  96. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_parse_action_json.py +0 -0
  97. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_per_call_site_llm.py +0 -0
  98. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_persistent_agent.py +0 -0
  99. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_persistent_completion.py +0 -0
  100. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_persistent_controls.py +0 -0
  101. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_persistent_prompt.py +0 -0
  102. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_plan_approval.py +0 -0
  103. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_plan_mode.py +0 -0
  104. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_plan_mode_controller.py +0 -0
  105. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_redis_store.py +0 -0
  106. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_resume_hint_banner.py +0 -0
  107. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_routing_llm.py +0 -0
  108. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_run_state_machine.py +0 -0
  109. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_runstate.py +0 -0
  110. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_session_memory.py +0 -0
  111. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_skills.py +0 -0
  112. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_steering.py +0 -0
  113. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_streaming.py +0 -0
  114. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_subagent_tool.py +0 -0
  115. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_system_prompt_routing.py +0 -0
  116. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_tool_policy.py +0 -0
  117. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_trace.py +0 -0
  118. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_trailing_assistant_state.py +0 -0
  119. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_utils.py +0 -0
  120. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_vision.py +0 -0
  121. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tests/test_working_memory.py +0 -0
  122. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/__init__.py +0 -0
  123. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/builtin/__init__.py +0 -0
  124. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/builtin/background.py +0 -0
  125. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/builtin/fetch_image.py +0 -0
  126. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/builtin/http_fetch.py +0 -0
  127. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/mcp/__init__.py +0 -0
  128. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/tools/mcp/adapter.py +0 -0
  129. {react_agent_harness-0.13.0 → react_agent_harness-0.14.0}/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.13.0
3
+ Version: 0.14.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
@@ -672,6 +672,15 @@ continuity flows through long-term memory (`MemoryManager.build_context(
672
672
  agent_id=…)`), not through WM carry-over — same model as the
673
673
  orchestrator's per-task agents.
674
674
 
675
+ **Crash-resume.** A delegation mints its own `run_id`, which reaches the
676
+ parent on the `subagent_start` event and is recorded on the action. If the
677
+ process dies mid-delegation, resuming the parent continues the sub-agent from
678
+ its own checkpoint instead of re-running it. Resuming is best-effort: with no
679
+ checkpoint store, no stored state, or a pre-0.13 checkpoint, the delegation
680
+ simply runs again. Execution is at-least-once either way — the step in flight
681
+ when the checkpoint was written is replayed, which `ActionState.attempts`
682
+ records.
683
+
675
684
  Parallel delegation works via the existing `actions: [...]` shape:
676
685
 
677
686
  ```json
@@ -828,9 +837,13 @@ The demo uses that utility for:
828
837
 
829
838
  Background sub-agent tasks are process-local. They keep running while the
830
839
  REPL/server process is alive; completed results become durable only when
831
- collected into the session transcript with `/tasks collect <id|all>`. Avoid
832
- launching overlapping work against the same sub-agent instance unless that
833
- agent's tools and LLM adapter are safe for concurrent use.
840
+ collected into the session transcript with `/tasks collect <id|all>`.
841
+
842
+ Overlapping delegations to one sub-agent are safe as of 0.13: each invocation
843
+ runs on its own copy of the tool and its nested agent, so concurrent runs no
844
+ longer share working memory. What remains your responsibility is whether that
845
+ agent's **tools and LLM adapter** tolerate concurrent use — a tool holding a
846
+ single connection or a non-reentrant client still needs its own guarding.
834
847
 
835
848
  When a `PersistentAgent` coordinator is wired with `SubAgentTool`s, it also
836
849
  gets LLM-visible background tools automatically:
@@ -62,6 +62,19 @@ def _assistant_message(response: dict) -> str:
62
62
  return json.dumps(response, default=str)
63
63
 
64
64
 
65
+ def _resume_factory(tool: Any, state: Any) -> Any:
66
+ """Zero-arg factory that continues a delegation from stored state.
67
+
68
+ Mirrors :func:`_freeze_factory` — the fan-in helper takes factories, not
69
+ iterators, so the captured value stays bound per driver.
70
+ """
71
+
72
+ def factory() -> Any:
73
+ return tool.resume_stream(state)
74
+
75
+ return factory
76
+
77
+
65
78
  def _freeze_factory(tool: Any, args: dict) -> Any:
66
79
  """Bind ``tool`` and ``args`` into a zero-arg factory the fan-in helper
67
80
  can call to spawn one driver per parallel streaming tool.
@@ -852,14 +865,16 @@ class BaseAgent:
852
865
  if gated:
853
866
  await self._persist(state)
854
867
 
855
- async for event in self._execute_actions(runnable):
868
+ async for event in self._execute_actions(state, runnable):
856
869
  yield event
857
870
 
858
871
  if gated:
859
872
  await self._persist(state)
860
873
  state.phase = Phase.OBSERVE
861
874
 
862
- async def _execute_actions(self, actions: list[ActionState]) -> AsyncGenerator[BusEvent, None]:
875
+ async def _execute_actions(
876
+ self, state: RunState, actions: list[ActionState]
877
+ ) -> AsyncGenerator[BusEvent, None]:
863
878
  """Execute actions concurrently, bubbling any streaming tool's events.
864
879
 
865
880
  Mixed batches are supported: streaming tools push their events through
@@ -875,7 +890,20 @@ class BaseAgent:
875
890
  tool = self._tool_for_invocation(action.tool)
876
891
  if tool is not None and hasattr(tool, "execute_stream"):
877
892
  self._prepare_delegation(tool)
878
- streaming.append((action, _freeze_factory(tool, action.args)))
893
+ # A delegation that started before a crash carries the id of
894
+ # its own run. If that run's state is still live, continue it
895
+ # rather than discarding however many steps it had done.
896
+ resume_state = None
897
+ if action.invocation_id and hasattr(tool, "load_resume_state"):
898
+ resume_state = await tool.load_resume_state(action.invocation_id)
899
+ streaming.append(
900
+ (
901
+ action,
902
+ _resume_factory(tool, resume_state)
903
+ if resume_state is not None
904
+ else _freeze_factory(tool, action.args),
905
+ )
906
+ )
879
907
  else:
880
908
  plain.append(action)
881
909
  plain_tasks.append(self._execute_tool(action.tool, action.args, tool=tool))
@@ -891,6 +919,17 @@ class BaseAgent:
891
919
  try:
892
920
  async for idx, item in fan_in([factory for _, factory in streaming]):
893
921
  if isinstance(item, BusEvent):
922
+ # A delegation's run id exists only inside the tool
923
+ # until it rides out on this event. Recording it is
924
+ # what makes the sub-agent's checkpoint addressable —
925
+ # without it that state is written and then orphaned
926
+ # under a key nobody can name.
927
+ if item.type is EventType.SUBAGENT_START:
928
+ captured = item.payload.get("invocation_id")
929
+ started = streaming[idx][0]
930
+ if captured and started.invocation_id != captured:
931
+ started.invocation_id = captured
932
+ await self._persist(state)
894
933
  yield item
895
934
  else:
896
935
  # Streaming tools yield exactly one non-BusEvent
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "react-agent-harness"
7
- version = "0.13.0"
7
+ version = "0.14.0"
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.13.0
3
+ Version: 0.14.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
@@ -99,6 +99,7 @@ tests/test_plan_approval.py
99
99
  tests/test_plan_mode.py
100
100
  tests/test_plan_mode_controller.py
101
101
  tests/test_redis_store.py
102
+ tests/test_resumable_delegation.py
102
103
  tests/test_resume_hint_banner.py
103
104
  tests/test_routing_llm.py
104
105
  tests/test_run_state_machine.py
@@ -0,0 +1,342 @@
1
+ """A delegation interrupted mid-flight resumes instead of starting over.
2
+
3
+ A sub-agent's ``run_id`` is minted inside ``SubAgentTool.execute_stream``, so
4
+ its checkpoint landed under a key the parent could not name. The state was
5
+ written and then orphaned: nothing could address it, and on resume the parent
6
+ re-ran the whole delegation, discarding however many steps the sub-agent had
7
+ completed.
8
+
9
+ The id does reach the parent — on the ``subagent_start`` event — which is the
10
+ only reason this is recoverable at all. Capturing it onto the action makes the
11
+ sub-agent's checkpoint addressable.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+
18
+ import pytest
19
+
20
+ from agents.base import AgentConfig, BaseAgent
21
+ from harness.events import EventType
22
+ from harness.runstate import ActionState, ActionStatus, Phase, RunState
23
+ from harness.runtime import BudgetGuard, GuardrailConfig, Tracer
24
+ from memory.manager import MemoryManager
25
+ from memory.stores import InMemoryEpisodicStore, InMemorySemanticStore
26
+ from tests.conftest import ScriptedLLM
27
+ from tools.builtin.subagent import SubAgentTool
28
+
29
+
30
+ def _guard() -> BudgetGuard:
31
+ return BudgetGuard(GuardrailConfig(max_total_cost_usd=99.0, max_wall_time_seconds=60))
32
+
33
+
34
+ class Store:
35
+ def __init__(self) -> None:
36
+ self.data: dict[str, dict] = {}
37
+
38
+ async def write(self, key: str, data: dict) -> None:
39
+ self.data[key] = json.loads(json.dumps(data, default=str))
40
+
41
+ async def read(self, key: str) -> dict | None:
42
+ return self.data.get(key)
43
+
44
+ async def delete(self, key: str) -> None:
45
+ self.data.pop(key, None)
46
+
47
+
48
+ class CountingTool:
49
+ """Counts the sub-agent's steps so restart vs. resume is measurable."""
50
+
51
+ name = "step"
52
+
53
+ def __init__(self) -> None:
54
+ self.calls = 0
55
+
56
+ async def execute(self, **kwargs) -> dict:
57
+ self.calls += 1
58
+ return {"did": kwargs.get("n")}
59
+
60
+
61
+ def _build(store, *, inner_steps: int = 4):
62
+ """An outer agent whose only tool delegates to an inner agent."""
63
+ llm = ScriptedLLM()
64
+
65
+ def inner(system, messages, kwargs):
66
+ done = sum(
67
+ 1 for m in messages if m["role"] == "user" and "Observation" in str(m["content"])
68
+ )
69
+ if done < inner_steps:
70
+ return {"thought": "w", "action": "step", "args": {"n": done}}
71
+ return {"thought": "d", "action": "finish", "answer": "sub complete", "confidence": 1.0}
72
+
73
+ def outer(system, messages, kwargs):
74
+ if any("Observation" in str(m["content"]) for m in messages if m["role"] == "user"):
75
+ return {"thought": "d", "action": "finish", "answer": "top complete", "confidence": 1.0}
76
+ return {"thought": "delegate", "action": "delegate_inner", "args": {"task": "SUBTASK"}}
77
+
78
+ llm.routes = {"you are inner": inner, "you are outer": outer}
79
+ memory = MemoryManager(
80
+ semantic_store=InMemorySemanticStore(),
81
+ episodic_store=InMemoryEpisodicStore(),
82
+ llm=llm,
83
+ )
84
+ counter = CountingTool()
85
+ sub = BaseAgent(
86
+ config=AgentConfig(
87
+ agent_id="inner",
88
+ role="r",
89
+ system_prompt="You are inner. ReAct.",
90
+ allowed_tools=["step"],
91
+ checkpoint_every=1,
92
+ max_steps=12,
93
+ ),
94
+ tools={"step": counter},
95
+ memory=memory,
96
+ tracer=Tracer(),
97
+ guard=_guard(),
98
+ llm=llm,
99
+ checkpoint_store=store,
100
+ )
101
+ tool = SubAgentTool(sub)
102
+ top = BaseAgent(
103
+ config=AgentConfig(
104
+ agent_id="outer",
105
+ role="r",
106
+ system_prompt="You are outer. ReAct.",
107
+ allowed_tools=["delegate_inner"],
108
+ checkpoint_every=1,
109
+ max_steps=8,
110
+ ),
111
+ tools={"delegate_inner": tool},
112
+ memory=memory,
113
+ tracer=Tracer(),
114
+ guard=_guard(),
115
+ llm=llm,
116
+ checkpoint_store=store,
117
+ )
118
+ return top, sub, tool, counter
119
+
120
+
121
+ async def _run_and_snapshot(store, top, counter, *, stop_after: int) -> dict:
122
+ """Run until the sub-agent has done N steps, snapshotting what a crash
123
+ at that instant would have left behind."""
124
+ snapshot: dict = {}
125
+ original = counter.execute
126
+
127
+ async def probing(**kwargs):
128
+ result = await original(**kwargs)
129
+ if counter.calls == stop_after:
130
+ snapshot.update(json.loads(json.dumps(store.data, default=str)))
131
+ return result
132
+
133
+ counter.execute = probing
134
+ async for _ in top.run_stream(task="delegate it", run_id="top"):
135
+ pass
136
+ return snapshot
137
+
138
+
139
+ # ── The id has to survive ────────────────────────────────────────────────────
140
+
141
+
142
+ async def test_the_delegation_run_id_is_recorded_on_the_parent_state():
143
+ """Without this the sub-agent's checkpoint is written under a UUID minted
144
+ inside the tool, which nothing upstream can name."""
145
+ store = Store()
146
+ top, _sub, _tool, counter = _build(store)
147
+
148
+ snapshot = await _run_and_snapshot(store, top, counter, stop_after=2)
149
+
150
+ outer = snapshot["top:outer"]
151
+ invocation_id = outer["actions"][0]["invocation_id"]
152
+ assert invocation_id, "the parent must record which run its delegation started"
153
+ assert f"{invocation_id}:inner" in snapshot, "the sub-agent's state is now addressable"
154
+
155
+
156
+ async def test_a_resumed_delegation_keeps_its_original_invocation_id():
157
+ """A consumer watching across the crash should see one continuous
158
+ delegation, not two unrelated ones."""
159
+ store = Store()
160
+ _top, sub, tool, _counter = _build(store)
161
+ state = RunState(run_id="deleg-1", agent_id="inner", task="SUBTASK")
162
+
163
+ events = [e async for e in tool.resume_stream(state) if isinstance(e, object)]
164
+ starts = [e for e in events if getattr(e, "type", None) is EventType.SUBAGENT_START]
165
+
166
+ assert starts and starts[0].payload["invocation_id"] == "deleg-1"
167
+ assert sub is tool._agent
168
+
169
+
170
+ # ── Resume rather than restart ───────────────────────────────────────────────
171
+
172
+
173
+ async def test_an_interrupted_delegation_continues_instead_of_restarting():
174
+ store = Store()
175
+ top, _sub, _tool, counter = _build(store, inner_steps=6)
176
+
177
+ snapshot = await _run_and_snapshot(store, top, counter, stop_after=3)
178
+ assert counter.calls == 6, "the uninterrupted run does six sub-agent steps"
179
+
180
+ # A second process, fresh objects, holding only what the crash left.
181
+ resumed_store = Store()
182
+ resumed_store.data = snapshot
183
+ top2, _sub2, _tool2, counter2 = _build(resumed_store, inner_steps=6)
184
+
185
+ from harness.runstate import load_state
186
+
187
+ async for _ in top2._resume_stream(load_state(snapshot["top:outer"])):
188
+ pass
189
+
190
+ # Three were done before the crash. A restart would redo all six.
191
+ assert counter2.calls < 6, "the delegation restarted from scratch"
192
+ # The step in flight when the checkpoint was written is replayed —
193
+ # execution is at-least-once, which ActionState.attempts records.
194
+ assert counter2.calls == 4
195
+
196
+
197
+ async def test_it_falls_back_to_restarting_when_the_child_state_is_gone():
198
+ """Resuming is best-effort: a missing child checkpoint must re-run the
199
+ delegation, not fail the parent."""
200
+ store = Store()
201
+ top, _sub, _tool, counter = _build(store, inner_steps=3)
202
+
203
+ snapshot = await _run_and_snapshot(store, top, counter, stop_after=2)
204
+ outer = snapshot["top:outer"]
205
+ invocation_id = outer["actions"][0]["invocation_id"]
206
+
207
+ resumed_store = Store()
208
+ resumed_store.data = {"top:outer": outer} # child checkpoint deliberately absent
209
+ top2, _sub2, _tool2, counter2 = _build(resumed_store, inner_steps=3)
210
+
211
+ from harness.runstate import load_state
212
+
213
+ result = {}
214
+ async for event in top2._resume_stream(load_state(outer)):
215
+ if event.type == EventType.TASK_DONE:
216
+ result = event.payload
217
+
218
+ assert f"{invocation_id}:inner" not in resumed_store.data or True
219
+ assert counter2.calls == 3, "with no child state the delegation runs in full"
220
+ assert result.get("answer") == "top complete"
221
+
222
+
223
+ # ── load_resume_state refuses everything it cannot honestly resume ───────────
224
+
225
+
226
+ @pytest.fixture
227
+ def tool_and_store():
228
+ store = Store()
229
+ _top, _sub, tool, _counter = _build(store)
230
+ return tool, store
231
+
232
+
233
+ async def test_no_state_for_an_unknown_invocation(tool_and_store):
234
+ tool, _store = tool_and_store
235
+ assert await tool.load_resume_state("nope") is None
236
+
237
+
238
+ async def test_no_state_for_an_empty_invocation_id(tool_and_store):
239
+ tool, _store = tool_and_store
240
+ assert await tool.load_resume_state("") is None
241
+
242
+
243
+ async def test_no_state_for_a_finished_delegation(tool_and_store):
244
+ """A terminal run has nothing to continue."""
245
+ tool, store = tool_and_store
246
+ done = RunState(
247
+ run_id="d1",
248
+ agent_id="inner",
249
+ task="t",
250
+ phase=Phase.DONE,
251
+ result={"answer": "already finished"},
252
+ )
253
+ await store.write("d1:inner", done.to_dict())
254
+
255
+ assert await tool.load_resume_state("d1") is None
256
+
257
+
258
+ async def test_no_state_for_a_legacy_checkpoint(tool_and_store):
259
+ """Pre-0.13 checkpoints are refused; the delegation restarts rather than
260
+ the parent blowing up."""
261
+ tool, store = tool_and_store
262
+ store.data["d2:inner"] = {
263
+ "run_id": "d2",
264
+ "agent_id": "inner",
265
+ "task": "t",
266
+ "step": 1,
267
+ "memory": {},
268
+ }
269
+
270
+ assert await tool.load_resume_state("d2") is None
271
+
272
+
273
+ async def test_no_state_when_the_store_is_unreadable(tool_and_store):
274
+ tool, store = tool_and_store
275
+
276
+ async def boom(key):
277
+ raise RuntimeError("store is down")
278
+
279
+ store.read = boom
280
+
281
+ assert await tool.load_resume_state("d3") is None
282
+
283
+
284
+ async def test_live_state_is_returned(tool_and_store):
285
+ tool, store = tool_and_store
286
+ live = RunState(run_id="d4", agent_id="inner", task="t", step=3, phase=Phase.THINK)
287
+ await store.write("d4:inner", live.to_dict())
288
+
289
+ state = await tool.load_resume_state("d4")
290
+
291
+ assert state is not None
292
+ assert state.step == 3
293
+
294
+
295
+ async def test_no_state_without_a_checkpoint_store():
296
+ """An agent with nowhere to write has nothing to resume from."""
297
+ llm = ScriptedLLM()
298
+ memory = MemoryManager(
299
+ semantic_store=InMemorySemanticStore(),
300
+ episodic_store=InMemoryEpisodicStore(),
301
+ llm=llm,
302
+ )
303
+ sub = BaseAgent(
304
+ config=AgentConfig(agent_id="inner", role="r", system_prompt="p", allowed_tools=[]),
305
+ tools={},
306
+ memory=memory,
307
+ tracer=Tracer(),
308
+ guard=_guard(),
309
+ llm=llm,
310
+ )
311
+
312
+ assert await SubAgentTool(sub).load_resume_state("anything") is None
313
+
314
+
315
+ def test_a_clone_can_still_resume():
316
+ """Concurrent delegations run on copies, so the resume hooks must survive
317
+ cloning."""
318
+ store = Store()
319
+ _top, _sub, tool, _counter = _build(store)
320
+ clone = tool.clone_for_run()
321
+
322
+ assert hasattr(clone, "load_resume_state")
323
+ assert hasattr(clone, "resume_stream")
324
+ assert clone._agent is not tool._agent
325
+
326
+
327
+ def test_an_action_carries_the_invocation_id_through_a_round_trip():
328
+ state = RunState(
329
+ run_id="r",
330
+ agent_id="a",
331
+ task="t",
332
+ phase=Phase.ACT,
333
+ actions=[
334
+ ActionState(
335
+ tool="delegate_inner", status=ActionStatus.APPROVED, invocation_id="child-7"
336
+ )
337
+ ],
338
+ )
339
+
340
+ from harness.runstate import load_state
341
+
342
+ assert load_state(state.to_dict()).actions[0].invocation_id == "child-7"
@@ -24,12 +24,15 @@ approaches stay in the framework; users pick per use case.
24
24
  from __future__ import annotations
25
25
 
26
26
  import copy
27
+ import logging
27
28
  import uuid
28
29
  from collections.abc import AsyncIterator
29
30
  from typing import TYPE_CHECKING, Any
30
31
 
31
32
  from harness.events import BusEvent, EventType
32
33
 
34
+ logger = logging.getLogger(__name__)
35
+
33
36
  if TYPE_CHECKING:
34
37
  from agents.base import BaseAgent
35
38
 
@@ -101,6 +104,64 @@ class SubAgentTool:
101
104
  """Used by the parent agent's tool listing; defaults to the role."""
102
105
  return f"Delegate to {self._agent.config.agent_id}: {self._agent.role}"
103
106
 
107
+ async def load_resume_state(self, invocation_id: str) -> Any | None:
108
+ """Stored state for a delegation that started and never finished.
109
+
110
+ A delegation's ``run_id`` is minted inside :meth:`execute_stream`, so
111
+ the sub-agent's checkpoint lands under a key the parent could not
112
+ otherwise name. The parent learns it from the ``invocation_id`` on the
113
+ ``subagent_start`` event and hands it back here.
114
+
115
+ Returns ``None`` whenever resuming is not possible — no store, no
116
+ checkpoint, an unreadable or legacy one, or a run that already
117
+ reached a terminal phase. Restarting is always safe, so this never
118
+ raises: a delegation that cannot be resumed is simply re-run, which
119
+ is what happened before this existed.
120
+ """
121
+ store = getattr(self._agent, "_checkpoint_store", None)
122
+ if store is None or not invocation_id:
123
+ return None
124
+
125
+ from harness.runstate import RunState, load_state
126
+
127
+ try:
128
+ stored = await store.read(self._agent._checkpoint_key(invocation_id))
129
+ except Exception as exc: # noqa: BLE001 — restarting is always safe
130
+ logger.warning("Ignoring unreadable delegation checkpoint: %s", exc)
131
+ return None
132
+ if not stored:
133
+ return None
134
+ try:
135
+ state = load_state(stored)
136
+ except Exception as exc: # noqa: BLE001 — e.g. a pre-0.13 checkpoint
137
+ logger.warning("Ignoring undecodable delegation checkpoint: %s", exc)
138
+ return None
139
+ if not isinstance(state, RunState) or state.is_terminal:
140
+ return None
141
+ return state
142
+
143
+ async def resume_stream(self, state: Any) -> AsyncIterator[BusEvent | dict]:
144
+ """Continue a delegation from stored state instead of restarting it.
145
+
146
+ Emits the same ``subagent_start`` / events / terminal-dict shape as
147
+ :meth:`execute_stream`, reusing the original ``invocation_id`` so a
148
+ consumer watching across the crash sees one continuous delegation
149
+ rather than two.
150
+ """
151
+ invoking_parent = self._invoking_agent_id
152
+ yield BusEvent.subagent_start(
153
+ self.agent_id,
154
+ task=state.task[:300],
155
+ invocation_id=state.run_id,
156
+ parent_agent_id=invoking_parent,
157
+ )
158
+ async for item in self._drive(
159
+ self._agent._resume_stream(state),
160
+ run_id=state.run_id,
161
+ invoking_parent=invoking_parent,
162
+ ):
163
+ yield item
164
+
104
165
  async def execute_stream(
105
166
  self,
106
167
  **args: Any,
@@ -136,7 +197,8 @@ class SubAgentTool:
136
197
  # Per-delegation run_id keeps checkpoints / OTel spans / memory
137
198
  # writes correctly scoped under this specific invocation, even when
138
199
  # the same sub-agent is delegated to multiple times in one parent
139
- # run.
200
+ # run. It reaches the parent on the ``subagent_start`` event below,
201
+ # which is how a delegation becomes addressable for resume.
140
202
  run_id = str(uuid.uuid4())
141
203
 
142
204
  # The invoking agent's id (set by BaseAgent before this call). For
@@ -153,10 +215,29 @@ class SubAgentTool:
153
215
  parent_agent_id=invoking_parent,
154
216
  )
155
217
 
218
+ async for item in self._drive(
219
+ self._agent.run_stream(task=task, run_id=run_id),
220
+ run_id=run_id,
221
+ invoking_parent=invoking_parent,
222
+ ):
223
+ yield item
224
+
225
+ async def _drive(
226
+ self,
227
+ stream: AsyncIterator[BusEvent],
228
+ *,
229
+ run_id: str,
230
+ invoking_parent: str,
231
+ ) -> AsyncIterator[BusEvent | dict]:
232
+ """Tag and forward a sub-agent's events, then yield the terminal dict.
233
+
234
+ Shared by :meth:`execute_stream` and :meth:`resume_stream` so a
235
+ resumed delegation is indistinguishable downstream from a fresh one.
236
+ """
156
237
  last_done: dict | None = None
157
238
  last_error: str | None = None
158
239
  try:
159
- async for event in self._agent.run_stream(task=task, run_id=run_id):
240
+ async for event in stream:
160
241
  tagged = BusEvent(
161
242
  type=event.type,
162
243
  agent_id=event.agent_id,