react-agent-harness 0.9.1__tar.gz → 0.10.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 (105) hide show
  1. {react_agent_harness-0.9.1/react_agent_harness.egg-info → react_agent_harness-0.10.1}/PKG-INFO +1 -1
  2. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/README.md +57 -0
  3. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/agents/base.py +76 -51
  4. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/console.py +41 -0
  5. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/events.py +1 -0
  6. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/hitl.py +145 -2
  7. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/persistent.py +577 -3
  8. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/persistent_completion.py +35 -0
  9. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/persistent_controls.py +133 -4
  10. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/persistent_prompt.py +42 -3
  11. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/steering.py +11 -11
  12. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/working.py +47 -6
  13. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/pyproject.toml +1 -1
  14. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1/react_agent_harness.egg-info}/PKG-INFO +1 -1
  15. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/react_agent_harness.egg-info/SOURCES.txt +3 -0
  16. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_agents_base.py +48 -0
  17. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_persistent_agent.py +199 -0
  18. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_persistent_completion.py +14 -1
  19. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_persistent_controls.py +108 -0
  20. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_persistent_prompt.py +59 -0
  21. react_agent_harness-0.10.1/tests/test_plan_approval.py +119 -0
  22. react_agent_harness-0.10.1/tests/test_plan_mode.py +711 -0
  23. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_steering.py +16 -0
  24. react_agent_harness-0.10.1/tests/test_trailing_assistant_state.py +115 -0
  25. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_working_memory.py +31 -0
  26. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/LICENSE +0 -0
  27. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/agents/__init__.py +0 -0
  28. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/__init__.py +0 -0
  29. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/annotation.py +0 -0
  30. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/cancellation.py +0 -0
  31. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/checkpoint.py +0 -0
  32. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/cli.py +0 -0
  33. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/executor_bridge.py +0 -0
  34. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/__init__.py +0 -0
  35. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/_streaming.py +0 -0
  36. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/anthropic.py +0 -0
  37. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/auth.py +0 -0
  38. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/claude_code.py +0 -0
  39. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/fallback.py +0 -0
  40. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/openai.py +0 -0
  41. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/openai_codex.py +0 -0
  42. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/llm/routing.py +0 -0
  43. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/oauth_browser.py +0 -0
  44. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/otel.py +0 -0
  45. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/runtime.py +0 -0
  46. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/streaming.py +0 -0
  47. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/tool_policy.py +0 -0
  48. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/trace.py +0 -0
  49. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/trace_viewer.py +0 -0
  50. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/harness/utils.py +0 -0
  51. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/__init__.py +0 -0
  52. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/episodic_lance.py +0 -0
  53. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/manager.py +0 -0
  54. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/redis_store.py +0 -0
  55. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/memory/stores.py +0 -0
  56. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/orchestrator/__init__.py +0 -0
  57. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/orchestrator/planner.py +0 -0
  58. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/react_agent_harness.egg-info/dependency_links.txt +0 -0
  59. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/react_agent_harness.egg-info/entry_points.txt +0 -0
  60. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/react_agent_harness.egg-info/requires.txt +0 -0
  61. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/react_agent_harness.egg-info/top_level.txt +0 -0
  62. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/setup.cfg +0 -0
  63. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_annotation.py +0 -0
  64. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_anthropic_llm.py +0 -0
  65. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_budget_guard.py +0 -0
  66. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_cancellation.py +0 -0
  67. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_checkpoint_resume.py +0 -0
  68. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_claude_code_llm.py +0 -0
  69. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_cli.py +0 -0
  70. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_console_renderer.py +0 -0
  71. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_executor_bridge.py +0 -0
  72. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_fallback_llm.py +0 -0
  73. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_fan_in.py +0 -0
  74. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_http_fetch.py +0 -0
  75. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_llm_auth.py +0 -0
  76. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_mcp_adapter.py +0 -0
  77. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_mcp_auth.py +0 -0
  78. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_memory.py +0 -0
  79. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_memory_reconciler.py +0 -0
  80. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_memory_touchpoints.py +0 -0
  81. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_oauth_browser.py +0 -0
  82. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_openai_codex_llm.py +0 -0
  83. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_openai_llm.py +0 -0
  84. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_orchestrator.py +0 -0
  85. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_otel.py +0 -0
  86. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_parse_action_json.py +0 -0
  87. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_per_call_site_llm.py +0 -0
  88. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_redis_store.py +0 -0
  89. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_resume_hint_banner.py +0 -0
  90. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_routing_llm.py +0 -0
  91. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_streaming.py +0 -0
  92. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_subagent_tool.py +0 -0
  93. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_system_prompt_routing.py +0 -0
  94. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_tool_policy.py +0 -0
  95. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_trace.py +0 -0
  96. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_utils.py +0 -0
  97. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tests/test_vision.py +0 -0
  98. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/__init__.py +0 -0
  99. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/builtin/__init__.py +0 -0
  100. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/builtin/fetch_image.py +0 -0
  101. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/builtin/http_fetch.py +0 -0
  102. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/builtin/subagent.py +0 -0
  103. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/mcp/__init__.py +0 -0
  104. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/mcp/adapter.py +0 -0
  105. {react_agent_harness-0.9.1 → react_agent_harness-0.10.1}/tools/mcp/auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: react-agent-harness
3
- Version: 0.9.1
3
+ Version: 0.10.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
@@ -633,6 +633,11 @@ app = PersistentAgent(
633
633
  session_store=SQLiteSessionStore("~/.agent-harness/sessions.sqlite"),
634
634
  memory=memory_manager,
635
635
  llm=llm,
636
+ llm_registry={
637
+ "fast": lambda: OpenAILLM(model="gpt-5.4-mini"),
638
+ "deep": lambda: OpenAILLM(model="gpt-5"),
639
+ },
640
+ default_model="fast",
636
641
  )
637
642
 
638
643
  async for event in app.chat("I like the above; can you do X?", session_id="thread-1"):
@@ -643,6 +648,23 @@ Use `app.capabilities()` to inspect the already-wired coordinator,
643
648
  sub-agents, and MCP tools. The demo exposes this with
644
649
  `--show-capabilities`.
645
650
 
651
+ Model switching is session-scoped when an `llm_registry` is configured:
652
+
653
+ ```python
654
+ await app.switch_model("thread-1", "coordinator", "deep")
655
+ await app.clear_model_override("thread-1", "coordinator")
656
+ ```
657
+
658
+ Registry values are zero-argument factories. Model names `default`,
659
+ `reset`, and `clear` are reserved for clearing overrides in interactive
660
+ controls.
661
+
662
+ The durable session stores only `{agent_id: model_name}` overrides; the
663
+ transcript is unchanged. At the start of each turn, `PersistentAgent`
664
+ resets agents to their construction-time LLMs, then applies that session's
665
+ overrides. The facade assumes one active chat turn at a time for a given
666
+ `PersistentAgent` instance.
667
+
646
668
  Persistent sessions also expose a small control surface for user interfaces:
647
669
 
648
670
  ```python
@@ -705,17 +727,52 @@ The demo uses that utility for:
705
727
  - `/capabilities`, `/agents`, `/mcp` inspect wired agents and tools
706
728
  - `/session` shows turns, context-pressure estimate, reconcile cadence, and summary
707
729
  - `/usage` shows persisted total and last-run provider-reported token usage
730
+ - `/models` lists switchable model names when an LLM registry is configured
731
+ - `/model [agent_id] [model|default]` shows or changes a session-scoped model override
708
732
  - `/sessions [query]` lists known session ids, optionally filtered by id text
709
733
  - `/memory` shows the cached per-session memory context
710
734
  - `/save` flushes turns after the last reconcile checkpoint into long-term memory **without** evicting the cached prior (foreground prefix stays warm)
711
735
  - `/compact` forces a structural reorg — summary + trim + reconcile + cache evict — used when the transcript is bloating, not for routine "save"
712
736
  - `/forget` evicts cached memory context so the next turn refetches it
737
+ - `/plan [on|off]` toggles plan-before-execute mode — see below
713
738
  - `/switch <id>` resumes or creates a logical session id
714
739
  - `/new [id]` starts a fresh session id and refuses to collide with an existing id
715
740
  - `/clear` clears the current transcript/summary/counters; long-term memory is retained
716
741
  - `/delete [id] confirm` deletes a transcript row; long-term memory is retained
717
742
  - `/end` exits the demo — no auto-flush; call `/save` first if you want pending facts persisted
718
743
 
744
+ **Plan mode** (`/plan on`, or **Shift-Tab** at the prompt) gates each turn behind an approval step. The
745
+ coordinator's LLM produces a structured plan (`{summary, steps[]}`) before
746
+ any tools run; `PersistentAgent.chat` yields a `PLAN_PROPOSED` event so
747
+ the renderer can display it, then routes approval through
748
+ `harness.hitl.request_plan_approval` — the plan-specific sibling of the
749
+ primitive that already gates individual tool calls.
750
+
751
+ **Plan mode approves intent, not arguments.** Most realistic agent tasks
752
+ have args that can only be known at runtime — a URL discovered by a
753
+ search, a file path extracted from a directory listing, a row id from a
754
+ query. The planner is told to use concrete `args` only when the value
755
+ was user-supplied or otherwise knowable upfront; for everything else it
756
+ returns `args: null` (or omits the field), and the renderer shows
757
+ `args: (resolved at runtime)` instead of fabricating placeholder JSON.
758
+ The approval banner surfaces `dynamic_steps: N` alongside the summary so
759
+ the reviewer sees how many step args will be filled in during execution.
760
+ The approved-plan prior tells the executor explicitly that
761
+ `(resolved at runtime)` means *"derive the argument from your
762
+ observations of the prior step,"* not *"a value you must invent."*
763
+
764
+ Plan approval uses a focused HITL surface:
765
+
766
+ - `Enter` or `y` approves the plan and runs the ReAct loop with the plan injected as a pinned prior.
767
+ - `n` rejects; an `ERROR` event is yielded and **nothing is written to the session store** (cancelled turn = never happened, same as `Esc`-cancel).
768
+ - Free text becomes a correction — the planner re-runs with the feedback folded into the system prompt. Up to `_PLAN_REVISION_LIMIT` revision cycles before the gate yields a clean "revision limit reached" error.
769
+
770
+ Plan mode is off by default and persists per-session in SQLite, so the
771
+ preference survives process restart (and `/clear`, which is a transcript
772
+ reset, not a settings reset). Esc during plan generation or during the
773
+ HITL wait unwinds `asyncio.CancelledError` through the chat generator
774
+ cleanly — no partial plan written. The setting is on `SessionState.plan_mode_enabled`; flip it programmatically via `PersistentAgent.set_plan_mode(session_id, enabled)`.
775
+
719
776
  **Press `Esc` during a turn to cancel it.** Every example that streams a
720
777
  `BusEvent` loop wraps it in `ConsoleRenderer.render_stream(events, *,
721
778
  terminal_event_type=...)` — one call that renders each event, captures
@@ -686,6 +686,7 @@ class BaseAgent:
686
686
  await self._commit_checkpoint(run_id, step)
687
687
 
688
688
  combined: list[dict] = []
689
+ observation_events: list[BusEvent] = []
689
690
  for i, (act, obs) in enumerate(zip(parallel_actions, observations, strict=False)):
690
691
  tool_name = act.get("tool", "")
691
692
  tool_args = act.get("args", {})
@@ -700,10 +701,12 @@ class BaseAgent:
700
701
  "observation": obs_display,
701
702
  },
702
703
  )
703
- yield BusEvent(
704
- type=EventType.OBSERVATION,
705
- agent_id=self.config.agent_id,
706
- payload={"step": step, "tool": tool_name, "observation": obs_display},
704
+ observation_events.append(
705
+ BusEvent(
706
+ type=EventType.OBSERVATION,
707
+ agent_id=self.config.agent_id,
708
+ payload={"step": step, "tool": tool_name, "observation": obs_display},
709
+ )
707
710
  )
708
711
  combined.append({"tool": tool_name, "result": obs_display})
709
712
  if obs and not isinstance(obs, str) and not _is_image_block(obs):
@@ -716,29 +719,15 @@ class BaseAgent:
716
719
  )
717
720
  )
718
721
 
719
- await self._working_memory.append("assistant", json.dumps(response))
720
722
  # Inject image observations as content blocks; text observations as a string.
721
723
  image_blocks = [
722
724
  (act.get("tool", ""), obs)
723
725
  for act, obs in zip(parallel_actions, observations, strict=False)
724
726
  if _is_image_block(obs)
725
727
  ]
726
- if image_blocks:
727
- content: list = [
728
- {
729
- "type": "text",
730
- "text": f"Observations:\n{json.dumps(combined, default=str)}",
731
- }
732
- ]
733
- for tool_name_img, img_block in image_blocks:
734
- content.append({"type": "text", "text": f"\nImage from {tool_name_img}:"})
735
- content.append(img_block)
736
- await self._working_memory.append("user", content)
737
- else:
738
- await self._working_memory.append(
739
- "user",
740
- f"Observations:\n{json.dumps(combined, default=str)}",
741
- )
728
+ await self._record_parallel_observations(response, combined, image_blocks)
729
+ for event in observation_events:
730
+ yield event
742
731
  else:
743
732
  # Single action path.
744
733
  tool_name = response.get("action", "")
@@ -774,6 +763,7 @@ class BaseAgent:
774
763
  if observation is _HITL_CORRECTION:
775
764
  continue
776
765
 
766
+ await self._record_tool_observation(response, tool_name, observation)
777
767
  obs_display = "[image]" if _is_image_block(observation) else str(observation)[:500]
778
768
  self._tracer.log(
779
769
  "action",
@@ -809,23 +799,6 @@ class BaseAgent:
809
799
  )
810
800
  )
811
801
 
812
- await self._working_memory.append("assistant", json.dumps(response))
813
- if _is_image_block(observation):
814
- await self._working_memory.append(
815
- "user",
816
- [
817
- {"type": "text", "text": f"Observation ({tool_name}):"},
818
- observation,
819
- ],
820
- )
821
- else:
822
- obs_text = (
823
- json.dumps(observation, default=str)
824
- if not isinstance(observation, str)
825
- else observation
826
- )
827
- await self._working_memory.append("user", f"Observation: {obs_text}")
828
-
829
802
  # Max steps exhausted.
830
803
  self._tracer.log(
831
804
  "task_result",
@@ -859,6 +832,21 @@ class BaseAgent:
859
832
  # honoured. OpenAI's adapter re-injects it inline when needed.
860
833
  # See ``_split_system`` docstring for the full rationale.
861
834
  system_text, messages = _split_system(self._working_memory.get_messages())
835
+
836
+ # The ReAct loop should call the LLM only after a user task or
837
+ # user observation. If working memory ends with an assistant
838
+ # message, log the invalid shape, but do not fabricate a user
839
+ # turn. Synthetic cues such as "Continue." hide the missing
840
+ # observation and can make the model continue from the wrong
841
+ # state.
842
+ if messages and messages[-1].get("role") == "assistant":
843
+ logger.warning(
844
+ "Agent %s: messages end with assistant before LLM call; "
845
+ "leaving messages unchanged. role_sequence=%r",
846
+ self.config.agent_id,
847
+ [m.get("role") for m in messages],
848
+ )
849
+
862
850
  accumulated = ""
863
851
  before_usage = self._working_memory.context_usage()
864
852
  before_summarizations = self._working_memory.summarization_count
@@ -1002,6 +990,55 @@ class BaseAgent:
1002
990
  self._last_think_error = f"Unparseable stream response: {accumulated[:300]}"
1003
991
  return response
1004
992
 
993
+ async def _record_tool_observation(
994
+ self,
995
+ response: dict,
996
+ tool_name: str,
997
+ observation: Any,
998
+ ) -> None:
999
+ """Record one ReAct action and its observation in working memory."""
1000
+ await self._working_memory.append("assistant", json.dumps(response))
1001
+ if _is_image_block(observation):
1002
+ await self._working_memory.append(
1003
+ "user",
1004
+ [
1005
+ {"type": "text", "text": f"Observation ({tool_name}):"},
1006
+ observation,
1007
+ ],
1008
+ )
1009
+ return
1010
+ obs_text = (
1011
+ json.dumps(observation, default=str)
1012
+ if not isinstance(observation, str)
1013
+ else observation
1014
+ )
1015
+ await self._working_memory.append("user", f"Observation: {obs_text}")
1016
+
1017
+ async def _record_parallel_observations(
1018
+ self,
1019
+ response: dict,
1020
+ combined: list[dict],
1021
+ image_blocks: list[tuple[str, Any]],
1022
+ ) -> None:
1023
+ """Record one parallel ReAct action batch and its observations."""
1024
+ await self._working_memory.append("assistant", json.dumps(response))
1025
+ if image_blocks:
1026
+ content: list = [
1027
+ {
1028
+ "type": "text",
1029
+ "text": f"Observations:\n{json.dumps(combined, default=str)}",
1030
+ }
1031
+ ]
1032
+ for tool_name_img, img_block in image_blocks:
1033
+ content.append({"type": "text", "text": f"\nImage from {tool_name_img}:"})
1034
+ content.append(img_block)
1035
+ await self._working_memory.append("user", content)
1036
+ return
1037
+ await self._working_memory.append(
1038
+ "user",
1039
+ f"Observations:\n{json.dumps(combined, default=str)}",
1040
+ )
1041
+
1005
1042
  # ── Tool Execution ────────────────────────────────────────────────────────
1006
1043
 
1007
1044
  async def _execute_tool(self, name: str, args: dict) -> Any:
@@ -1284,25 +1321,13 @@ class BaseAgent:
1284
1321
  if approval is None or approval.approved
1285
1322
  else f"Tool rejected by human: {approval.correction or 'no reason given'}"
1286
1323
  )
1324
+ await self._record_tool_observation(llm_response, tool_name, observation)
1287
1325
  obs_display = "[image]" if _is_image_block(observation) else str(observation)[:500]
1288
1326
  yield BusEvent(
1289
1327
  type=EventType.OBSERVATION,
1290
1328
  agent_id=self.config.agent_id,
1291
1329
  payload={"step": step, "tool": tool_name, "observation": obs_display},
1292
1330
  )
1293
- await self._working_memory.append("assistant", json.dumps(llm_response))
1294
- if _is_image_block(observation):
1295
- await self._working_memory.append(
1296
- "user",
1297
- [{"type": "text", "text": f"Observation ({tool_name}):"}, observation],
1298
- )
1299
- else:
1300
- obs_text = (
1301
- json.dumps(observation, default=str)
1302
- if not isinstance(observation, str)
1303
- else observation
1304
- )
1305
- await self._working_memory.append("user", f"Observation: {obs_text}")
1306
1331
  await self._commit_checkpoint(run_id, step)
1307
1332
 
1308
1333
 
@@ -113,6 +113,47 @@ class ConsoleRenderer:
113
113
  file=self._out,
114
114
  )
115
115
 
116
+ elif t == EventType.PLAN_PROPOSED:
117
+ # PersistentAgent plan-mode preview, before HITL approval.
118
+ # Renders the full plan so the user can read it before the
119
+ # approval banner prints; HITL's banner repeats the summary
120
+ # in a yes/no/correction context.
121
+ #
122
+ # Steps whose args are deferred to runtime render as
123
+ # ``args: (resolved at runtime)`` rather than fabricating
124
+ # placeholder JSON — keep the renderer convention in lock-
125
+ # step with ``_render_plan_for_banner`` so the user sees the
126
+ # same shape twice.
127
+ plan = p.get("plan", {}) if isinstance(p.get("plan"), dict) else {}
128
+ revision = p.get("revision", 0)
129
+ summary = plan.get("summary") or "(no summary)"
130
+ steps = plan.get("steps") or []
131
+ header = "[plan propose]"
132
+ if revision:
133
+ header = f"[plan rev {revision}]"
134
+ print(f"\n{header} {summary}", file=self._out)
135
+ for step in steps:
136
+ idx = step.get("step")
137
+ intent = step.get("intent") or "(no intent)"
138
+ tool = step.get("tool")
139
+ why = step.get("why")
140
+ prefix = f" {idx}." if idx is not None else " -"
141
+ print(f"{prefix} {intent}", file=self._out)
142
+ if tool:
143
+ # Convention: ``"args"`` key missing or ``args is None``
144
+ # → deferred. ``args == {}`` → "tool takes no args".
145
+ args_present = "args" in step and step["args"] is not None
146
+ if not args_present:
147
+ print(f" tool: {tool} args: (resolved at runtime)", file=self._out)
148
+ else:
149
+ args = step["args"] or {}
150
+ args_repr = (
151
+ json.dumps(args, ensure_ascii=False, default=str) if args else "{}"
152
+ )
153
+ print(f" tool: {tool} args: {args_repr}", file=self._out)
154
+ if why:
155
+ print(f" why: {why}", file=self._out)
156
+
116
157
  elif t == EventType.THOUGHT:
117
158
  thought = p.get("thought", "")
118
159
  if thought:
@@ -45,6 +45,7 @@ class EventType(str, Enum):
45
45
  DISPATCH = "dispatch"
46
46
  ROUTE = "route"
47
47
  PLAN = "plan"
48
+ PLAN_PROPOSED = "plan_proposed" # PersistentAgent plan-mode: pre-HITL plan
48
49
  THOUGHT = "thought"
49
50
  TOKEN = "token"
50
51
  ACTION = "action"
@@ -153,9 +153,13 @@ def _print_banner(req: ApprovalRequest) -> None:
153
153
  print(_SEP)
154
154
  print(f" Tool: {req.tool}")
155
155
  print(f" Args: {json.dumps(req.args, default=str)}")
156
+ # ``Agent: X step=N`` is the only context line — Run/ID UUIDs used
157
+ # to print here but the run_id is already echoed in the resume hint
158
+ # below (so the top line was duplicate) and the approval_id is a
159
+ # purely internal correlation token that's never user-actionable in
160
+ # the synchronous CLI flow. Both fields remain on ``ApprovalRequest``
161
+ # for callers that need them (tests, future async-approval systems).
156
162
  print(f" Agent: {req.agent_id} step={req.step}")
157
- print(f" Run: {req.run_id}")
158
- print(f" ID: {req.approval_id}")
159
163
  print(_SEP)
160
164
  print(
161
165
  " y = approve once | "
@@ -183,6 +187,145 @@ def _parse_stdin(approval_id: str, raw: str) -> ApprovalResponse:
183
187
  return ApprovalResponse(approval_id=approval_id, approved=True, correction=stripped or None)
184
188
 
185
189
 
190
+ @dataclass
191
+ class PlanApprovalResponse:
192
+ """Sibling of ``ApprovalResponse`` for ``request_plan_approval``.
193
+
194
+ Plan mode is per-turn, not per-tool — there's no a / A here because
195
+ "allow plans for the session" silently turns plan mode off (defeats
196
+ the whole feature), and "always allow plans" persistently always-
197
+ allows the gate, which is the same thing forever.
198
+
199
+ Three outcomes:
200
+ - ``approved=True``: run the plan.
201
+ - ``approved=False, correction=None``: user rejected — abort the turn.
202
+ - ``approved=False, correction=<text>``: user wants a revision; the
203
+ planner re-runs with the correction folded into its system prompt.
204
+ """
205
+
206
+ approved: bool
207
+ correction: str | None = None
208
+
209
+
210
+ async def request_plan_approval(
211
+ *,
212
+ summary: str,
213
+ step_count: int,
214
+ dynamic_step_count: int,
215
+ agent_id: str,
216
+ guard: Any,
217
+ ) -> PlanApprovalResponse:
218
+ """Plan-mode approval prompt: y / n / revision text.
219
+
220
+ Sibling of :func:`request_approval` that drops the session-allow and
221
+ persistent-allow options. They make sense for per-tool gating
222
+ (approve ``shell/grep`` for the session and stop nagging) but they're
223
+ actively wrong for plan-mode approval: ``a`` turns plan mode off
224
+ silently, ``A`` does it permanently. Both contradict the user's
225
+ intent in turning plan mode on at all.
226
+
227
+ Shares ``stdout_lock``, the steering router interop, and the
228
+ BudgetGuard suspend/resume cycle with :func:`request_approval`, so
229
+ the input plumbing stays one place.
230
+
231
+ The full plan was already rendered by the consumer when the
232
+ ``PLAN_PROPOSED`` event fired upstream of this call; the banner here
233
+ is a short confirmation prompt with just enough context to re-anchor
234
+ a reviewer who scrolled.
235
+ """
236
+ from harness.steering import get_active_router
237
+
238
+ async with stdout_lock:
239
+ router = get_active_router()
240
+ # Capital ``Y`` signals that Enter alone approves. Plan mode is
241
+ # opt-in and the full plan has already been rendered above this
242
+ # banner, so the reviewer's "I read it, proceed" gesture should
243
+ # be the cheapest possible — matches the apt / pip convention.
244
+ approve_prompt = " Approve plan? [Y/n/revision]: "
245
+ hitl_future: Any = (
246
+ router.claim_next_line(prompt=approve_prompt) if router is not None else None
247
+ )
248
+
249
+ _print_plan_banner(
250
+ summary=summary,
251
+ step_count=step_count,
252
+ dynamic_step_count=dynamic_step_count,
253
+ agent_id=agent_id,
254
+ )
255
+
256
+ guard.suspend()
257
+ try:
258
+ if hitl_future is not None:
259
+ raw = await hitl_future
260
+ else:
261
+ from prompt_toolkit import PromptSession
262
+
263
+ from harness.steering import StdinRouter
264
+
265
+ session: PromptSession = PromptSession()
266
+ raw = await session.prompt_async(
267
+ approve_prompt,
268
+ multiline=True,
269
+ key_bindings=StdinRouter._build_key_bindings(),
270
+ )
271
+ finally:
272
+ guard.resume()
273
+
274
+ print()
275
+ return _parse_plan_stdin(raw)
276
+
277
+
278
+ def _print_plan_banner(
279
+ *,
280
+ summary: str,
281
+ step_count: int,
282
+ dynamic_step_count: int,
283
+ agent_id: str,
284
+ ) -> None:
285
+ """Compact banner for plan approval. The full plan already streamed
286
+ via PLAN_PROPOSED — this banner is just a confirmation prompt with
287
+ summary / step counts as scroll anchors.
288
+
289
+ No ``--resume <run_id>`` hint here because PersistentAgent's
290
+ resumption model is session-id-based — the next ``chat()`` call on
291
+ the same session_id picks up state automatically. The
292
+ orchestrator-style ``--resume`` flag this banner used to print
293
+ doesn't apply.
294
+ """
295
+ print(f"\n{_SEP}")
296
+ print(f" Plan ready for {agent_id}")
297
+ print(_SEP)
298
+ if summary:
299
+ print(f" Summary: {summary}")
300
+ detail = f"{step_count} step{'' if step_count == 1 else 's'}"
301
+ if dynamic_step_count:
302
+ detail += f" ({dynamic_step_count} with args resolved at runtime)"
303
+ print(f" Steps: {detail}")
304
+ print(_SEP)
305
+ print(" Enter or y = approve and run | n = reject | any other text = revise the plan")
306
+ print(_SEP)
307
+
308
+
309
+ def _parse_plan_stdin(raw: str) -> PlanApprovalResponse:
310
+ """Parse a plan-approval response.
311
+
312
+ No a / A handling — plan mode gates per turn, not per tool. Any
313
+ text that isn't ``y/yes/n/no`` is treated as a revision request.
314
+
315
+ Empty input (just Enter) approves — the plan has already been
316
+ rendered above the prompt and the capital ``Y`` in the prompt
317
+ text signals the default. Mirrors the apt / pip ``[Y/n]``
318
+ convention.
319
+ """
320
+ stripped = (raw or "").strip()
321
+ lo = stripped.lower()
322
+ if lo in ("", "y", "yes"):
323
+ return PlanApprovalResponse(approved=True)
324
+ if lo in ("n", "no"):
325
+ return PlanApprovalResponse(approved=False)
326
+ return PlanApprovalResponse(approved=False, correction=stripped or None)
327
+
328
+
186
329
  async def request_approval(
187
330
  req: ApprovalRequest,
188
331
  guard: Any, # BudgetGuard — suspend/resume during wait