react-agent-harness 0.9.0__tar.gz → 0.10.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.
- {react_agent_harness-0.9.0/react_agent_harness.egg-info → react_agent_harness-0.10.0}/PKG-INFO +1 -1
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/README.md +53 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/agents/base.py +162 -61
- react_agent_harness-0.10.0/harness/cancellation.py +186 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/cli.py +9 -6
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/console.py +105 -1
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/events.py +1 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/hitl.py +145 -2
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/persistent.py +408 -3
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/persistent_completion.py +10 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/persistent_controls.py +41 -0
- react_agent_harness-0.10.0/harness/persistent_prompt.py +189 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/steering.py +11 -11
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/working.py +47 -6
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/pyproject.toml +1 -1
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0/react_agent_harness.egg-info}/PKG-INFO +1 -1
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/react_agent_harness.egg-info/SOURCES.txt +9 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_agents_base.py +48 -0
- react_agent_harness-0.10.0/tests/test_cancellation.py +314 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_persistent_agent.py +13 -5
- react_agent_harness-0.10.0/tests/test_persistent_prompt.py +251 -0
- react_agent_harness-0.10.0/tests/test_plan_approval.py +119 -0
- react_agent_harness-0.10.0/tests/test_plan_mode.py +711 -0
- react_agent_harness-0.10.0/tests/test_resume_hint_banner.py +300 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_steering.py +16 -0
- react_agent_harness-0.10.0/tests/test_system_prompt_routing.py +165 -0
- react_agent_harness-0.10.0/tests/test_trailing_assistant_state.py +115 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_working_memory.py +31 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/LICENSE +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/agents/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/annotation.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/checkpoint.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/executor_bridge.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/_streaming.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/anthropic.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/auth.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/claude_code.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/fallback.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/openai.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/openai_codex.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/llm/routing.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/oauth_browser.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/otel.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/runtime.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/streaming.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/tool_policy.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/trace.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/trace_viewer.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/harness/utils.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/episodic_lance.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/manager.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/redis_store.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/memory/stores.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/orchestrator/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/orchestrator/planner.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/react_agent_harness.egg-info/dependency_links.txt +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/react_agent_harness.egg-info/entry_points.txt +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/react_agent_harness.egg-info/requires.txt +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/react_agent_harness.egg-info/top_level.txt +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/setup.cfg +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_annotation.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_anthropic_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_budget_guard.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_checkpoint_resume.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_claude_code_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_cli.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_console_renderer.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_executor_bridge.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_fallback_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_fan_in.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_http_fetch.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_llm_auth.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_mcp_adapter.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_mcp_auth.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_memory.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_memory_reconciler.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_memory_touchpoints.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_oauth_browser.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_openai_codex_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_openai_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_orchestrator.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_otel.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_parse_action_json.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_per_call_site_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_persistent_completion.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_persistent_controls.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_redis_store.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_routing_llm.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_streaming.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_subagent_tool.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_tool_policy.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_trace.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_utils.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tests/test_vision.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/builtin/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/builtin/fetch_image.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/builtin/http_fetch.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/builtin/subagent.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/mcp/__init__.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/mcp/adapter.py +0 -0
- {react_agent_harness-0.9.0 → react_agent_harness-0.10.0}/tools/mcp/auth.py +0 -0
{react_agent_harness-0.9.0/react_agent_harness.egg-info → react_agent_harness-0.10.0}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: react-agent-harness
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.10.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
|
|
@@ -710,12 +710,65 @@ The demo uses that utility for:
|
|
|
710
710
|
- `/save` flushes turns after the last reconcile checkpoint into long-term memory **without** evicting the cached prior (foreground prefix stays warm)
|
|
711
711
|
- `/compact` forces a structural reorg — summary + trim + reconcile + cache evict — used when the transcript is bloating, not for routine "save"
|
|
712
712
|
- `/forget` evicts cached memory context so the next turn refetches it
|
|
713
|
+
- `/plan [on|off]` toggles plan-before-execute mode — see below
|
|
713
714
|
- `/switch <id>` resumes or creates a logical session id
|
|
714
715
|
- `/new [id]` starts a fresh session id and refuses to collide with an existing id
|
|
715
716
|
- `/clear` clears the current transcript/summary/counters; long-term memory is retained
|
|
716
717
|
- `/delete [id] confirm` deletes a transcript row; long-term memory is retained
|
|
717
718
|
- `/end` exits the demo — no auto-flush; call `/save` first if you want pending facts persisted
|
|
718
719
|
|
|
720
|
+
**Plan mode** (`/plan on`, or **Shift-Tab** at the prompt) gates each turn behind an approval step. The
|
|
721
|
+
coordinator's LLM produces a structured plan (`{summary, steps[]}`) before
|
|
722
|
+
any tools run; `PersistentAgent.chat` yields a `PLAN_PROPOSED` event so
|
|
723
|
+
the renderer can display it, then routes approval through
|
|
724
|
+
`harness.hitl.request_plan_approval` — the plan-specific sibling of the
|
|
725
|
+
primitive that already gates individual tool calls.
|
|
726
|
+
|
|
727
|
+
**Plan mode approves intent, not arguments.** Most realistic agent tasks
|
|
728
|
+
have args that can only be known at runtime — a URL discovered by a
|
|
729
|
+
search, a file path extracted from a directory listing, a row id from a
|
|
730
|
+
query. The planner is told to use concrete `args` only when the value
|
|
731
|
+
was user-supplied or otherwise knowable upfront; for everything else it
|
|
732
|
+
returns `args: null` (or omits the field), and the renderer shows
|
|
733
|
+
`args: (resolved at runtime)` instead of fabricating placeholder JSON.
|
|
734
|
+
The approval banner surfaces `dynamic_steps: N` alongside the summary so
|
|
735
|
+
the reviewer sees how many step args will be filled in during execution.
|
|
736
|
+
The approved-plan prior tells the executor explicitly that
|
|
737
|
+
`(resolved at runtime)` means *"derive the argument from your
|
|
738
|
+
observations of the prior step,"* not *"a value you must invent."*
|
|
739
|
+
|
|
740
|
+
Plan approval uses a focused HITL surface:
|
|
741
|
+
|
|
742
|
+
- `Enter` or `y` approves the plan and runs the ReAct loop with the plan injected as a pinned prior.
|
|
743
|
+
- `n` rejects; an `ERROR` event is yielded and **nothing is written to the session store** (cancelled turn = never happened, same as `Esc`-cancel).
|
|
744
|
+
- 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.
|
|
745
|
+
|
|
746
|
+
Plan mode is off by default and persists per-session in SQLite, so the
|
|
747
|
+
preference survives process restart (and `/clear`, which is a transcript
|
|
748
|
+
reset, not a settings reset). Esc during plan generation or during the
|
|
749
|
+
HITL wait unwinds `asyncio.CancelledError` through the chat generator
|
|
750
|
+
cleanly — no partial plan written. The setting is on `SessionState.plan_mode_enabled`; flip it programmatically via `PersistentAgent.set_plan_mode(session_id, enabled)`.
|
|
751
|
+
|
|
752
|
+
**Press `Esc` during a turn to cancel it.** Every example that streams a
|
|
753
|
+
`BusEvent` loop wraps it in `ConsoleRenderer.render_stream(events, *,
|
|
754
|
+
terminal_event_type=...)` — one call that renders each event, captures
|
|
755
|
+
the top-level terminal (TASK_DONE / DONE), and listens for Esc on stdin.
|
|
756
|
+
The cancel raises `asyncio.CancelledError` through the agent's `await`
|
|
757
|
+
points, which propagates out of `PersistentAgent.chat` (and every other
|
|
758
|
+
stream) before `_finalize_turn` runs — so a cancelled turn writes
|
|
759
|
+
nothing to the session store, matching the standard chat-UX "cancelled
|
|
760
|
+
turn = never happened" semantic.
|
|
761
|
+
|
|
762
|
+
The underlying primitives in `harness/cancellation.py` are reusable for
|
|
763
|
+
any "run X but stop early on Y" pattern: `run_until_cancelled(coro, *,
|
|
764
|
+
trigger)` races a coroutine against an `asyncio.Event`,
|
|
765
|
+
`escape_listener(trigger)` is the prompt_toolkit Esc binding,
|
|
766
|
+
`consume_with_cancel(events, *, on_event)` is the renderer-agnostic
|
|
767
|
+
lower-level form for demos that need bespoke per-event handling (e.g.
|
|
768
|
+
`complex_sysaudit_demo.py` capturing a custom DONE payload). The Esc
|
|
769
|
+
binding is a no-op on non-TTY stdin, so the same code paths work for
|
|
770
|
+
pipe / file / CI input without conditional wiring.
|
|
771
|
+
|
|
719
772
|
Each chat turn gets a fresh `WorkingMemory`. Continuity comes from the
|
|
720
773
|
SQLite session state (rolling summary + recent messages) and normal
|
|
721
774
|
`MemoryManager` recall, not from carrying old ReAct scratchpads forever.
|
|
@@ -311,9 +311,25 @@ class BaseAgent:
|
|
|
311
311
|
check_key=self._ckp_id,
|
|
312
312
|
) as hint:
|
|
313
313
|
async for event in self._run_stream_internal(run_id):
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
314
|
+
# ``parent_agent_id`` filtering: sub-agent events bubble up
|
|
315
|
+
# through this loop tagged with their invoker's id. A sub's
|
|
316
|
+
# TASK_DONE / ERROR is NOT terminal for the outer agent —
|
|
317
|
+
# the outer keeps running. Without this guard the FIRST
|
|
318
|
+
# delegated sub-agent that completes would wrongly clear
|
|
319
|
+
# the outer's checkpoint and suppress its resume hint.
|
|
320
|
+
if not event.parent_agent_id:
|
|
321
|
+
if event.type == EventType.TASK_DONE:
|
|
322
|
+
await self._clear_checkpoint(run_id)
|
|
323
|
+
hint.done = True
|
|
324
|
+
elif event.type == EventType.ERROR:
|
|
325
|
+
# Terminal ERROR (max_steps, budget exceeded, mid-run
|
|
326
|
+
# crash translated to ERROR by ``_run_stream_internal``)
|
|
327
|
+
# is "the agent ran to completion but failed", NOT a
|
|
328
|
+
# user interrupt. Suppress the misleading "interrupted
|
|
329
|
+
# — Resume:" banner; leave the checkpoint intact so the
|
|
330
|
+
# user can deliberately resume with new config (higher
|
|
331
|
+
# max_steps, larger budget) if they want.
|
|
332
|
+
hint.done = True
|
|
317
333
|
yield event
|
|
318
334
|
|
|
319
335
|
async def _resume_stream(
|
|
@@ -350,9 +366,17 @@ class BaseAgent:
|
|
|
350
366
|
check_key=self._ckp_id,
|
|
351
367
|
) as hint:
|
|
352
368
|
async for event in self._run_stream_internal(run_id, start_step=start_step):
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
369
|
+
# See ``run_stream`` for why both branches gate on
|
|
370
|
+
# ``not event.parent_agent_id`` (sub-agent terminals are
|
|
371
|
+
# not terminal for the outer) and why a top-level ERROR
|
|
372
|
+
# marks ``done`` without clearing the checkpoint
|
|
373
|
+
# (it's "ran-but-failed", not an interrupt).
|
|
374
|
+
if not event.parent_agent_id:
|
|
375
|
+
if event.type == EventType.TASK_DONE:
|
|
376
|
+
await self._clear_checkpoint(run_id)
|
|
377
|
+
hint.done = True
|
|
378
|
+
elif event.type == EventType.ERROR:
|
|
379
|
+
hint.done = True
|
|
356
380
|
yield event
|
|
357
381
|
|
|
358
382
|
async def _run_stream_internal(
|
|
@@ -662,6 +686,7 @@ class BaseAgent:
|
|
|
662
686
|
await self._commit_checkpoint(run_id, step)
|
|
663
687
|
|
|
664
688
|
combined: list[dict] = []
|
|
689
|
+
observation_events: list[BusEvent] = []
|
|
665
690
|
for i, (act, obs) in enumerate(zip(parallel_actions, observations, strict=False)):
|
|
666
691
|
tool_name = act.get("tool", "")
|
|
667
692
|
tool_args = act.get("args", {})
|
|
@@ -676,10 +701,12 @@ class BaseAgent:
|
|
|
676
701
|
"observation": obs_display,
|
|
677
702
|
},
|
|
678
703
|
)
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
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
|
+
)
|
|
683
710
|
)
|
|
684
711
|
combined.append({"tool": tool_name, "result": obs_display})
|
|
685
712
|
if obs and not isinstance(obs, str) and not _is_image_block(obs):
|
|
@@ -692,29 +719,15 @@ class BaseAgent:
|
|
|
692
719
|
)
|
|
693
720
|
)
|
|
694
721
|
|
|
695
|
-
await self._working_memory.append("assistant", json.dumps(response))
|
|
696
722
|
# Inject image observations as content blocks; text observations as a string.
|
|
697
723
|
image_blocks = [
|
|
698
724
|
(act.get("tool", ""), obs)
|
|
699
725
|
for act, obs in zip(parallel_actions, observations, strict=False)
|
|
700
726
|
if _is_image_block(obs)
|
|
701
727
|
]
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
"type": "text",
|
|
706
|
-
"text": f"Observations:\n{json.dumps(combined, default=str)}",
|
|
707
|
-
}
|
|
708
|
-
]
|
|
709
|
-
for tool_name_img, img_block in image_blocks:
|
|
710
|
-
content.append({"type": "text", "text": f"\nImage from {tool_name_img}:"})
|
|
711
|
-
content.append(img_block)
|
|
712
|
-
await self._working_memory.append("user", content)
|
|
713
|
-
else:
|
|
714
|
-
await self._working_memory.append(
|
|
715
|
-
"user",
|
|
716
|
-
f"Observations:\n{json.dumps(combined, default=str)}",
|
|
717
|
-
)
|
|
728
|
+
await self._record_parallel_observations(response, combined, image_blocks)
|
|
729
|
+
for event in observation_events:
|
|
730
|
+
yield event
|
|
718
731
|
else:
|
|
719
732
|
# Single action path.
|
|
720
733
|
tool_name = response.get("action", "")
|
|
@@ -750,6 +763,7 @@ class BaseAgent:
|
|
|
750
763
|
if observation is _HITL_CORRECTION:
|
|
751
764
|
continue
|
|
752
765
|
|
|
766
|
+
await self._record_tool_observation(response, tool_name, observation)
|
|
753
767
|
obs_display = "[image]" if _is_image_block(observation) else str(observation)[:500]
|
|
754
768
|
self._tracer.log(
|
|
755
769
|
"action",
|
|
@@ -785,23 +799,6 @@ class BaseAgent:
|
|
|
785
799
|
)
|
|
786
800
|
)
|
|
787
801
|
|
|
788
|
-
await self._working_memory.append("assistant", json.dumps(response))
|
|
789
|
-
if _is_image_block(observation):
|
|
790
|
-
await self._working_memory.append(
|
|
791
|
-
"user",
|
|
792
|
-
[
|
|
793
|
-
{"type": "text", "text": f"Observation ({tool_name}):"},
|
|
794
|
-
observation,
|
|
795
|
-
],
|
|
796
|
-
)
|
|
797
|
-
else:
|
|
798
|
-
obs_text = (
|
|
799
|
-
json.dumps(observation, default=str)
|
|
800
|
-
if not isinstance(observation, str)
|
|
801
|
-
else observation
|
|
802
|
-
)
|
|
803
|
-
await self._working_memory.append("user", f"Observation: {obs_text}")
|
|
804
|
-
|
|
805
802
|
# Max steps exhausted.
|
|
806
803
|
self._tracer.log(
|
|
807
804
|
"task_result",
|
|
@@ -829,7 +826,27 @@ class BaseAgent:
|
|
|
829
826
|
into the action JSON and yields it as a THOUGHT event. Otherwise
|
|
830
827
|
falls back to one `complete` call.
|
|
831
828
|
"""
|
|
832
|
-
|
|
829
|
+
# Working memory stores the system prompt as a role="system"
|
|
830
|
+
# entry for uniform summarisation + token accounting; split it
|
|
831
|
+
# back out here so Anthropic's top-level ``system=`` contract is
|
|
832
|
+
# honoured. OpenAI's adapter re-injects it inline when needed.
|
|
833
|
+
# See ``_split_system`` docstring for the full rationale.
|
|
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
|
+
|
|
833
850
|
accumulated = ""
|
|
834
851
|
before_usage = self._working_memory.context_usage()
|
|
835
852
|
before_summarizations = self._working_memory.summarization_count
|
|
@@ -853,7 +870,7 @@ class BaseAgent:
|
|
|
853
870
|
# don't take the kwarg (older custom stubs) get it via
|
|
854
871
|
# ``**kwargs`` and ignore it.
|
|
855
872
|
async for token in self._llm.stream_complete(
|
|
856
|
-
system=
|
|
873
|
+
system=system_text,
|
|
857
874
|
messages=messages,
|
|
858
875
|
source=react_source,
|
|
859
876
|
response_format={"type": "json_object"},
|
|
@@ -868,13 +885,14 @@ class BaseAgent:
|
|
|
868
885
|
response = _normalize_response(accumulated)
|
|
869
886
|
if response is None:
|
|
870
887
|
response = await self._retry_complete_after_bad_stream(
|
|
888
|
+
system_text=system_text,
|
|
871
889
|
messages=messages,
|
|
872
890
|
react_source=react_source,
|
|
873
891
|
accumulated=accumulated,
|
|
874
892
|
)
|
|
875
893
|
else:
|
|
876
894
|
raw = await self._llm.complete(
|
|
877
|
-
system=
|
|
895
|
+
system=system_text,
|
|
878
896
|
messages=messages,
|
|
879
897
|
response_format={"type": "json_object"},
|
|
880
898
|
source=react_source,
|
|
@@ -934,6 +952,7 @@ class BaseAgent:
|
|
|
934
952
|
async def _retry_complete_after_bad_stream(
|
|
935
953
|
self,
|
|
936
954
|
*,
|
|
955
|
+
system_text: str | None,
|
|
937
956
|
messages: list[dict],
|
|
938
957
|
react_source: str,
|
|
939
958
|
accumulated: str,
|
|
@@ -946,7 +965,7 @@ class BaseAgent:
|
|
|
946
965
|
)
|
|
947
966
|
try:
|
|
948
967
|
raw = await self._llm.complete(
|
|
949
|
-
system=
|
|
968
|
+
system=system_text,
|
|
950
969
|
messages=[
|
|
951
970
|
*messages,
|
|
952
971
|
{
|
|
@@ -971,6 +990,55 @@ class BaseAgent:
|
|
|
971
990
|
self._last_think_error = f"Unparseable stream response: {accumulated[:300]}"
|
|
972
991
|
return response
|
|
973
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
|
+
|
|
974
1042
|
# ── Tool Execution ────────────────────────────────────────────────────────
|
|
975
1043
|
|
|
976
1044
|
async def _execute_tool(self, name: str, args: dict) -> Any:
|
|
@@ -1253,28 +1321,61 @@ class BaseAgent:
|
|
|
1253
1321
|
if approval is None or approval.approved
|
|
1254
1322
|
else f"Tool rejected by human: {approval.correction or 'no reason given'}"
|
|
1255
1323
|
)
|
|
1324
|
+
await self._record_tool_observation(llm_response, tool_name, observation)
|
|
1256
1325
|
obs_display = "[image]" if _is_image_block(observation) else str(observation)[:500]
|
|
1257
1326
|
yield BusEvent(
|
|
1258
1327
|
type=EventType.OBSERVATION,
|
|
1259
1328
|
agent_id=self.config.agent_id,
|
|
1260
1329
|
payload={"step": step, "tool": tool_name, "observation": obs_display},
|
|
1261
1330
|
)
|
|
1262
|
-
await self._working_memory.append("assistant", json.dumps(llm_response))
|
|
1263
|
-
if _is_image_block(observation):
|
|
1264
|
-
await self._working_memory.append(
|
|
1265
|
-
"user",
|
|
1266
|
-
[{"type": "text", "text": f"Observation ({tool_name}):"}, observation],
|
|
1267
|
-
)
|
|
1268
|
-
else:
|
|
1269
|
-
obs_text = (
|
|
1270
|
-
json.dumps(observation, default=str)
|
|
1271
|
-
if not isinstance(observation, str)
|
|
1272
|
-
else observation
|
|
1273
|
-
)
|
|
1274
|
-
await self._working_memory.append("user", f"Observation: {obs_text}")
|
|
1275
1331
|
await self._commit_checkpoint(run_id, step)
|
|
1276
1332
|
|
|
1277
1333
|
|
|
1334
|
+
# ── LLM call shaping (module-level for testability) ──────────────────────────
|
|
1335
|
+
|
|
1336
|
+
|
|
1337
|
+
def _split_system(messages: list[dict]) -> tuple[str | None, list[dict]]:
|
|
1338
|
+
"""Pull system-role entries out of a messages list and join them.
|
|
1339
|
+
|
|
1340
|
+
Returns ``(system_text, non_system_messages)``. ``system_text`` is the
|
|
1341
|
+
concatenation of every ``role == "system"`` entry's ``content``
|
|
1342
|
+
(joined with a blank line) or ``None`` when no system entries are
|
|
1343
|
+
present.
|
|
1344
|
+
|
|
1345
|
+
Why this exists
|
|
1346
|
+
---------------
|
|
1347
|
+
``BaseAgent`` keeps the system prompt inside ``WorkingMemory`` (as a
|
|
1348
|
+
pinned ``role="system"`` entry) so summarisation, token accounting,
|
|
1349
|
+
and checkpoint serialisation treat it uniformly with every other
|
|
1350
|
+
message. But the two LLM adapter contracts diverge at the wire:
|
|
1351
|
+
|
|
1352
|
+
- **OpenAI** accepts ``role="system"`` entries *inside* the messages
|
|
1353
|
+
array — passing ``system=None`` + an inline system entry works.
|
|
1354
|
+
- **Anthropic** requires the system prompt as a *top-level* ``system=``
|
|
1355
|
+
parameter and ``_build_messages`` silently drops any
|
|
1356
|
+
``role="system"`` entries in the messages list. Passing
|
|
1357
|
+
``system=None`` + an inline system entry causes the entire system
|
|
1358
|
+
prompt to be discarded — the model sees only the user turn.
|
|
1359
|
+
|
|
1360
|
+
Splitting at the call boundary picks up any system entries (including
|
|
1361
|
+
those that arrived via ``prior_messages`` priors, not just the one
|
|
1362
|
+
BaseAgent appended itself), produces one joined system string, and
|
|
1363
|
+
leaves the rest as a clean user/assistant transcript. Both adapter
|
|
1364
|
+
contracts are then satisfied identically.
|
|
1365
|
+
"""
|
|
1366
|
+
system_parts: list[str] = []
|
|
1367
|
+
rest: list[dict] = []
|
|
1368
|
+
for m in messages:
|
|
1369
|
+
if m.get("role") == "system":
|
|
1370
|
+
content = m.get("content", "")
|
|
1371
|
+
if isinstance(content, str) and content:
|
|
1372
|
+
system_parts.append(content)
|
|
1373
|
+
continue
|
|
1374
|
+
rest.append(m)
|
|
1375
|
+
system_text = "\n\n".join(system_parts) if system_parts else None
|
|
1376
|
+
return system_text, rest
|
|
1377
|
+
|
|
1378
|
+
|
|
1278
1379
|
# ── Response normalization (module-level for testability) ────────────────────
|
|
1279
1380
|
|
|
1280
1381
|
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""User-initiated cancellation for streaming agent runs.
|
|
2
|
+
|
|
3
|
+
Two layers:
|
|
4
|
+
|
|
5
|
+
- ``run_until_cancelled`` runs an awaitable as an ``asyncio.Task`` and
|
|
6
|
+
cancels it when a caller-supplied ``trigger`` event fires. Pure
|
|
7
|
+
asyncio; no UI dependency. Reusable for any "run X but stop early on
|
|
8
|
+
Y" pattern — REPL turns, batch jobs, scheduled probes.
|
|
9
|
+
|
|
10
|
+
- ``escape_listener`` is a prompt_toolkit-backed async context manager
|
|
11
|
+
that sets a trigger event when the user presses Escape. Composes with
|
|
12
|
+
``run_until_cancelled`` to give CLIs the standard "press Esc to
|
|
13
|
+
cancel the current turn" affordance.
|
|
14
|
+
|
|
15
|
+
Agent code itself does not need to know about cancellation —
|
|
16
|
+
``asyncio.CancelledError`` propagates naturally through every ``await``
|
|
17
|
+
and through ``async for`` over an async generator. Cleanup happens via
|
|
18
|
+
ordinary ``try/finally`` blocks where they already exist. The
|
|
19
|
+
``PersistentAgent.chat`` flow is shaped so that mid-stream cancellation
|
|
20
|
+
writes nothing to the session store (``_finalize_turn`` only runs on
|
|
21
|
+
``TASK_DONE``/``ERROR`` or at clean generator end), which matches the
|
|
22
|
+
standard chat-UX semantic of "cancelled turn = never happened".
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import sys
|
|
29
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
30
|
+
from contextlib import asynccontextmanager
|
|
31
|
+
from typing import TYPE_CHECKING, TypeVar
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from harness.events import BusEvent
|
|
35
|
+
|
|
36
|
+
T = TypeVar("T")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def run_until_cancelled(
|
|
40
|
+
coro_factory: Callable[[], Awaitable[T]],
|
|
41
|
+
*,
|
|
42
|
+
trigger: asyncio.Event,
|
|
43
|
+
) -> tuple[bool, T | None]:
|
|
44
|
+
"""Run ``coro_factory()`` until it finishes or ``trigger`` fires.
|
|
45
|
+
|
|
46
|
+
Returns ``(cancelled, result)``:
|
|
47
|
+
|
|
48
|
+
- ``cancelled`` is ``True`` if the trigger fired before the
|
|
49
|
+
coroutine finished; the task was then cancelled and awaited so any
|
|
50
|
+
``finally`` cleanup completed before this function returned.
|
|
51
|
+
``result`` is ``None`` in this case.
|
|
52
|
+
- ``cancelled`` is ``False`` if the coroutine completed first;
|
|
53
|
+
``result`` is the coroutine's return value. Any waiter on the
|
|
54
|
+
trigger is cancelled before returning.
|
|
55
|
+
|
|
56
|
+
The trigger is cleared at entry so the caller can reuse the same
|
|
57
|
+
event across many turns. If the trigger was already set before this
|
|
58
|
+
call, the coroutine still gets a chance to start and run for at
|
|
59
|
+
least one event-loop tick — clearing-then-checking would otherwise
|
|
60
|
+
race with a key press that arrived just before this turn began.
|
|
61
|
+
"""
|
|
62
|
+
trigger.clear()
|
|
63
|
+
task: asyncio.Task[T] = asyncio.create_task(coro_factory())
|
|
64
|
+
waiter: asyncio.Task[bool] = asyncio.create_task(trigger.wait())
|
|
65
|
+
try:
|
|
66
|
+
done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)
|
|
67
|
+
except asyncio.CancelledError:
|
|
68
|
+
# Outer cancellation — propagate inward so neither child leaks.
|
|
69
|
+
task.cancel()
|
|
70
|
+
waiter.cancel()
|
|
71
|
+
raise
|
|
72
|
+
|
|
73
|
+
if waiter in done and not task.done():
|
|
74
|
+
task.cancel()
|
|
75
|
+
try:
|
|
76
|
+
await task
|
|
77
|
+
except asyncio.CancelledError:
|
|
78
|
+
pass
|
|
79
|
+
except Exception:
|
|
80
|
+
# Cancellation path is best-effort; the caller has already
|
|
81
|
+
# observed "user wanted to stop" — don't shadow that with a
|
|
82
|
+
# late exception from the cancelled task.
|
|
83
|
+
pass
|
|
84
|
+
return True, None
|
|
85
|
+
|
|
86
|
+
# Task completed (or errored) first; stop the trigger waiter.
|
|
87
|
+
waiter.cancel()
|
|
88
|
+
try:
|
|
89
|
+
await waiter
|
|
90
|
+
except asyncio.CancelledError:
|
|
91
|
+
pass
|
|
92
|
+
return False, task.result()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@asynccontextmanager
|
|
96
|
+
async def escape_listener(trigger: asyncio.Event) -> AsyncIterator[None]:
|
|
97
|
+
"""Set ``trigger`` when the user presses Escape on stdin.
|
|
98
|
+
|
|
99
|
+
Active only for the duration of the ``async with`` block. Uses
|
|
100
|
+
prompt_toolkit's input abstraction so terminal mode handling stays
|
|
101
|
+
correct across platforms and so it composes cleanly with
|
|
102
|
+
``PromptSession`` used elsewhere in the same process.
|
|
103
|
+
|
|
104
|
+
No-ops (yields immediately, never sets ``trigger``) when:
|
|
105
|
+
|
|
106
|
+
- ``stdin`` is not a TTY (pipe / file / no terminal) — keypress
|
|
107
|
+
capture doesn't apply.
|
|
108
|
+
- prompt_toolkit's input cannot be created on this platform / shell
|
|
109
|
+
configuration — surfacing a startup error here would mask the
|
|
110
|
+
user's actual workload. The trigger simply stays unset, matching
|
|
111
|
+
the pre-Esc-feature behavior.
|
|
112
|
+
"""
|
|
113
|
+
if not sys.stdin.isatty():
|
|
114
|
+
yield
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
# Local import so consumers that don't need ESC handling (e.g. unit
|
|
118
|
+
# tests that exercise ``run_until_cancelled`` alone) don't pay the
|
|
119
|
+
# prompt_toolkit import cost or its terminal capability probing.
|
|
120
|
+
try:
|
|
121
|
+
from prompt_toolkit.input import create_input
|
|
122
|
+
from prompt_toolkit.keys import Keys
|
|
123
|
+
except Exception: # noqa: BLE001 — best-effort UI feature
|
|
124
|
+
yield
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
input_obj = create_input()
|
|
129
|
+
except Exception: # noqa: BLE001 — terminal config refused; degrade silently
|
|
130
|
+
yield
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
def _on_input_ready() -> None:
|
|
134
|
+
# Read all currently-available key presses; trigger on the first
|
|
135
|
+
# Escape seen. Other keys are deliberately dropped — this is a
|
|
136
|
+
# cancel listener, not an input layer, and the active
|
|
137
|
+
# ``async for`` over chat events doesn't expect any user input.
|
|
138
|
+
try:
|
|
139
|
+
for key_press in input_obj.read_keys():
|
|
140
|
+
if key_press.key == Keys.Escape:
|
|
141
|
+
trigger.set()
|
|
142
|
+
return
|
|
143
|
+
except Exception: # noqa: BLE001 — listener must not raise into the loop
|
|
144
|
+
return
|
|
145
|
+
|
|
146
|
+
# ``raw_mode()`` disables canonical line buffering + echo so we
|
|
147
|
+
# actually see Escape as a keypress rather than after the user hits
|
|
148
|
+
# Enter. ``attach()`` registers ``_on_input_ready`` with the running
|
|
149
|
+
# event loop's reader for ``input_obj``'s file descriptor.
|
|
150
|
+
try:
|
|
151
|
+
with input_obj.raw_mode():
|
|
152
|
+
with input_obj.attach(_on_input_ready):
|
|
153
|
+
yield
|
|
154
|
+
except Exception: # noqa: BLE001 — terminal manipulation failed mid-flight
|
|
155
|
+
yield
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
async def consume_with_cancel(
|
|
159
|
+
events: AsyncIterator[BusEvent],
|
|
160
|
+
*,
|
|
161
|
+
on_event: Callable[[BusEvent], None],
|
|
162
|
+
) -> bool:
|
|
163
|
+
"""Consume a ``BusEvent`` async iterator until completion or user Esc.
|
|
164
|
+
|
|
165
|
+
Returns ``True`` if the user pressed Escape (the stream was
|
|
166
|
+
cancelled mid-flight); ``False`` if the stream completed naturally.
|
|
167
|
+
The caller's ``on_event`` callback runs for every event up to the
|
|
168
|
+
cancel point — rendering, final-result extraction, parent-agent
|
|
169
|
+
filtering all live in the callback so this helper stays
|
|
170
|
+
UI-agnostic.
|
|
171
|
+
|
|
172
|
+
Most consumers should use ``ConsoleRenderer.render_stream`` instead;
|
|
173
|
+
this lower-level helper is for renderers that aren't
|
|
174
|
+
``ConsoleRenderer`` (web UI, JSON-stream output, custom orchestrator
|
|
175
|
+
demos that render a bespoke report on DONE) or that need
|
|
176
|
+
per-event logic the renderer method doesn't expose.
|
|
177
|
+
"""
|
|
178
|
+
cancel_event = asyncio.Event()
|
|
179
|
+
|
|
180
|
+
async def _drain() -> None:
|
|
181
|
+
async for event in events:
|
|
182
|
+
on_event(event)
|
|
183
|
+
|
|
184
|
+
async with escape_listener(cancel_event):
|
|
185
|
+
cancelled, _ = await run_until_cancelled(_drain, trigger=cancel_event)
|
|
186
|
+
return cancelled
|
|
@@ -204,14 +204,17 @@ def _policy_clear(path: Path) -> int:
|
|
|
204
204
|
|
|
205
205
|
|
|
206
206
|
async def _trace_replay(path: str, *, realtime: bool, speed: float) -> int:
|
|
207
|
-
"""Read a JSONL trace and render it via ConsoleRenderer.
|
|
208
|
-
|
|
209
|
-
|
|
207
|
+
"""Read a JSONL trace and render it via ConsoleRenderer.
|
|
208
|
+
|
|
209
|
+
Esc cancels the replay — useful when ``--realtime`` is in effect and
|
|
210
|
+
the original run was long.
|
|
211
|
+
"""
|
|
212
|
+
from harness.console import ConsoleRenderer # noqa: PLC0415
|
|
213
|
+
from harness.trace import replay # noqa: PLC0415
|
|
210
214
|
|
|
211
215
|
renderer = ConsoleRenderer()
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
return 0
|
|
216
|
+
cancelled, _ = await renderer.render_stream(replay(path, realtime=realtime, speed=speed))
|
|
217
|
+
return 130 if cancelled else 0
|
|
215
218
|
|
|
216
219
|
|
|
217
220
|
if __name__ == "__main__":
|