The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into feat/hermes-relay-shared-metrics
Alex Fournier4fe4b0dca737
diff --cc agent/tool_executor.pyindex 4815f80db44,74092b90ee9..7c9fea12329--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@@ -703,13 -431,22 +703,20 @@@ def execute_tool_calls_concurrent(agent_underlying, _underlying_args, _err = _ts.resolve_underlying_call(function_args)if not _err and _underlying:if _underlying in _tool_search_scoped_names(agent):- function_name = _underlying- function_args = _underlying_args+ # Probe-validate before unwrapping (ironclaw#5149):+ # missing required args return the parameter schema+ # instead of dispatching into an opaque failure.+ _probe_err = _ts.validate_deferred_call_args(_underlying, _underlying_args)+ if _probe_err is not None:+ _ts_scope_block = _probe_err+ else:+ function_name = _underlying+ function_args = _underlying_argselse:- _ts_scope_block = json.dumps({- "error": (- f"'{_underlying}' is not available in this session. "- "Use tool_search to find tools you can call."- ),- }, ensure_ascii=False)+ _ts_scope_block = (+ f"'{_underlying}' is not available in this session. "+ "Use tool_search to find tools you can call."+ )except Exception:passdiff --cc run_agent.pyindex 0563216154d,703759d8ea6..f10a29d3946--- a/run_agent.py+++ b/run_agent.py@@@ -6740,72 -6822,30 +6824,74 @@@ class AIAgentreset_conversation_context,set_conversation_context,)+ from hermes_cli.observability.relay_shared_metrics import (+ finish_task_run,+ start_task_run,+ )+ from agent.subagent_lifecycle import bind_subagent_parent-- # Publish the conversation id for ambient Nous Portal tagging. Every- # LLM call made inside this turn — main loop, compression, vision,- # web_extract, session_search, MoA slots, background-review forks- # (which copy this Context into their thread) — inherits the- # ``conversation=<root>`` tag with zero per-call-site plumbing.- token = set_conversation_context(self._conversation_root_id())- # Publish the session accounting handles the same way so auxiliary- # calls record their token usage into session_model_usage (task- # dimension) — the fix for aux spend being invisible in analytics- # (issue #23270).- acct_token = set_accounting_context(- getattr(self, "_session_db", None), getattr(self, "session_id", None)+ effective_task_id = task_id or str(uuid.uuid4())++ session_id = str(getattr(self, "session_id", None) or "")+ task_context = {- "session_id": self.session_id or "",++ "session_id": session_id,+ "task_id": effective_task_id,+ "platform": getattr(self, "platform", None) or "",+ }+ relay_turn_id = (- f"{self.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}"++ f"{session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}")- from agent.auxiliary_client import scoped_runtime_main-- # The outer token restores the caller's Context even though turn setup- # replaces the value with the live runtime after fallback restoration.- # Keep the scope local instead of storing ContextVar tokens on the agent,- # which may be observed from another thread.- with bind_subagent_parent(self), scoped_runtime_main({}):- try:- return run_conversation(+ self._relay_pending_turn_id = relay_turn_id+ relay_parent_session_id = (+ str(getattr(self, "_parent_session_id", None) or "")+ if task_context["platform"] == "subagent"+ else ""+ )+ relay_lease = None+ relay_turn = None+ token = None+ acct_token = None+ task_started = False+ task_finished = False+ relay_outcome = "failed"+ try:+ relay_lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(+ profile_key=relay_runtime.current_profile_key(),+ session_id=task_context["session_id"],+ platform=task_context["platform"],+ parent_session_id=relay_parent_session_id,+ model=str(getattr(self, "model", None) or ""),+ )+ relay_turn = relay_runtime.SESSION_COORDINATOR.begin_turn(+ relay_lease,+ turn_id=relay_turn_id,+ task_id=effective_task_id,+ )+ start_task_run(+ **task_context,+ parent_session_id=getattr(self, "_parent_session_id", None) or "",+ )+ task_started = True+ # Publish the conversation id for ambient Nous Portal tagging. Every+ # LLM call made inside this turn — main loop, compression, vision,+ # web_extract, session_search, MoA slots, background-review forks+ # (which copy this Context into their thread) — inherits the+ # ``conversation=<root>`` tag with zero per-call-site plumbing.+ token = set_conversation_context(self._conversation_root_id())+ # Publish the session accounting handles the same way so auxiliary+ # calls record their token usage into session_model_usage (task+ # dimension) — the fix for aux spend being invisible in analytics+ # (issue #23270).+ acct_token = set_accounting_context(+ getattr(self, "_session_db", None),+ getattr(self, "session_id", None),+ )+ from agent.auxiliary_client import scoped_runtime_main++ # The outer token restores the caller's Context even though turn setup+ # replaces the value with the live runtime after fallback restoration.+ # Keep the scope local instead of storing ContextVar tokens on the agent,+ # which may be observed from another thread.- with scoped_runtime_main({}):++ with bind_subagent_parent(self), scoped_runtime_main({}):+ result = run_conversation(self,user_message,system_message,diff --cc tools/delegate_tool.pyindex 67ff2caab53,32726446aab..d4f22bf5165--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@@ -2420,24 -2575,151 +2580,168 @@@ def _run_single_childexcept Exception:logger.debug("Failed to close child agent after delegation")+ # The AIAgent turn boundary normally closes the child scope itself. This+ # fallback covers failures before that boundary starts, but must not pop+ # a scope while a timed-out child worker is still unwinding.+ try:+ from agent import relay_runtime++ runtime = relay_runtime.get_runtime(create=False)+ child_session_id = str(getattr(child, "session_id", "") or "")+ child_turn_is_active = relay_runtime.SESSION_COORDINATOR.has_active_turn(+ profile_key=relay_runtime.current_profile_key(),+ session_id=child_session_id,+ )+ if runtime is not None and child_session_id and not child_turn_is_active:+ runtime.unregister_subagent({"child_session_id": child_session_id})+ except Exception:+ logger.debug("Failed to close child Relay session after delegation")++ _PARENT_FINALIZATION_LOCK_GUARD = threading.Lock()+ _PARENT_FINALIZATION_FALLBACK_LOCK = threading.RLock()+ _CHILD_CONSTRUCTION_LOCK = threading.RLock()+++ def _build_child_preserving_parent_tools(**kwargs):+ """Build a child without leaking its resolved toolset into the parent."""+ import model_tools++ with _CHILD_CONSTRUCTION_LOCK:+ parent_tool_names = list(model_tools._last_resolved_tool_names)+ try:+ child = _build_child_agent(**kwargs)+ finally:+ model_tools._last_resolved_tool_names = parent_tool_names+ child._delegate_saved_tool_names = parent_tool_names+ return child+++ def _parent_finalization_lock(parent_agent) -> threading.RLock:+ """Return the per-parent lock that serializes lifecycle side effects."""+ if parent_agent is None:+ return _PARENT_FINALIZATION_FALLBACK_LOCK+ lock = getattr(parent_agent, "_subagent_finalization_lock", None)+ if lock is not None:+ return lock+ with _PARENT_FINALIZATION_LOCK_GUARD:+ lock = getattr(parent_agent, "_subagent_finalization_lock", None)+ if lock is None:+ lock = threading.RLock()+ try:+ setattr(parent_agent, "_subagent_finalization_lock", lock)+ except Exception:+ return _PARENT_FINALIZATION_FALLBACK_LOCK+ return lock+++ def _finalize_child_results(+ results: List[Dict[str, Any]],+ task_list: List[Dict[str, Any]],+ children: List[tuple[int, Dict[str, Any], Any]],+ parent_agent,+ ) -> None:+ """Apply host-owned summary, memory, hook, and cost contracts once."""+ with _parent_finalization_lock(parent_agent):+ _apply_summary_budget(results, parent_agent)+ child_by_index = {index: child for index, _task, child in children}++ if parent_agent and getattr(parent_agent, "_memory_manager", None):+ for entry in results:+ try:+ task_index = entry.get("task_index", -1)+ task_goal = (+ task_list[task_index]["goal"]+ if isinstance(task_index, int)+ and 0 <= task_index < len(task_list)+ else ""+ )+ child = child_by_index.get(task_index)+ parent_agent._memory_manager.on_delegation(+ task=task_goal,+ result=entry.get("summary", "") or "",+ child_session_id=getattr(child, "session_id", ""),+ )+ except Exception:+ pass++ parent_session_id = getattr(parent_agent, "session_id", None)+ try:+ from hermes_cli.plugins import invoke_hook as invoke_hook+ except Exception:+ invoke_hook = None++ children_cost_total = 0.0+ for entry in results:+ child_role = entry.pop("_child_role", None)+ child_cost = entry.pop("_child_cost_usd", 0.0)+ try:+ if child_cost:+ children_cost_total += float(child_cost)+ except (TypeError, ValueError):+ pass+ if invoke_hook is None:+ continue+ try:+ child_index = entry.get("task_index", -1)+ child = child_by_index.get(child_index)+ invoke_hook(+ "subagent_stop",+ parent_session_id=parent_session_id,+ parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "",+ child_session_id=getattr(child, "session_id", None),+ child_role=child_role,+ child_summary=entry.get("summary"),+ child_status=entry.get("status"),+ tool_call_history=_subagent_stop_tool_call_history(+ entry.get("tool_trace")+ ),+ duration_ms=int((entry.get("duration_seconds") or 0) * 1000),+ )+ except Exception:+ logger.debug("subagent_stop hook invocation failed", exc_info=True)++ if children_cost_total > 0.0:+ try:+ current = float(+ getattr(parent_agent, "session_estimated_cost_usd", 0.0) or 0.0+ )+ parent_agent.session_estimated_cost_usd = current + children_cost_total+ if getattr(parent_agent, "session_cost_source", "none") in {+ None,+ "",+ "none",+ }:+ parent_agent.session_cost_source = "subagent"+ if getattr(parent_agent, "session_cost_status", "unknown") in {+ None,+ "",+ "unknown",+ }:+ parent_agent.session_cost_status = "estimated"+ except Exception:+ logger.debug("Subagent cost rollup failed", exc_info=True)+++ def _run_child_lifecycle(+ task_index: int,+ goal: str,+ child=None,+ parent_agent=None,+ ) -> Dict[str, Any]:+ """Run one child and apply the same host lifecycle used by delegate_task."""+ result = _run_single_child(task_index, goal, child, parent_agent)+ result.setdefault("task_index", task_index)+ task = {"goal": goal}+ _finalize_child_results(+ [result],+ [{"goal": ""} for _ in range(task_index)] + [task],+ [(task_index, task, child)],+ parent_agent,+ )+ return result++def _recover_tasks_from_json_string(tasks: Any,) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: