Personal AI, On Personal Devices
Python
fix(agents): repair continuous monitor_operative agent (parrot loop, tool calling, traces) (#407)
Robby Manihania86d022947db
diff --git a/src/openjarvis/agents/executor.py b/src/openjarvis/agents/executor.pyindex 3feed1d3..6e7f42f6 100644--- a/src/openjarvis/agents/executor.py+++ b/src/openjarvis/agents/executor.py@@ -23,6 +23,15 @@ logger = logging.getLogger(__name__)_MAX_RETRIES = 3+# Default model for monitor_operative / long-horizon agent ticks. qwen3:8b+# emits tool_calls but, when given the full MonitorOperative system prompt+# alongside a `think` no-op tool, reliably picks `think` instead of the real+# action tools — producing tickless prose from training-data memory.+# gemma4:31b follows the function-calling protocol with the same prompt and+# actually invokes web_search / memory_retrieve. Explicit ``config["model"]``+# on an agent still wins.+_AGENT_TICK_DEFAULT_MODEL = "gemma4:31b"+class AgentExecutor:"""Executes a single tick for a managed agent.@@ -257,7 +266,11 @@ class AgentExecutor:engine = self._system.engine if self._system else Noneif engine is None:raise FatalError("No engine available in JarvisSystem")- model = config.get("model") or (self._system.model if self._system else "")+ model = (+ config.get("model")+ or _AGENT_TICK_DEFAULT_MODEL+ or (self._system.model if self._system else "")+ )if not model:raise FatalError("No model configured for agent")@@ -350,29 +363,109 @@ class AgentExecutor:agent_kwargs["system_prompt"] = sys_promptif getattr(agent_cls, "accepts_tools", False) and tool_instances:agent_kwargs["tools"] = tool_instances+ # Hand the agent our EventBus so its ToolExecutor can publish+ # TOOL_CALL_START/END — without this, ToolExecutor's ``self._bus``+ # is None and every tool call executes silently, which is why+ # traces previously reported "0 steps" even when the model was+ # actively invoking web_search/memory_*/etc.+ if self._bus is not None:+ agent_kwargs["bus"] = self._bus# Propagate confirmation policy from the AgentExecutor down to the# agent's own ToolExecutor. Set by CLI paths like `jarvis agents ask`# so non-interactive runs can auto-approve tool execution.if getattr(self, "_confirm_callback", None) is not None:agent_kwargs["interactive"] = Trueagent_kwargs["confirm_callback"] = self._confirm_callback++ # Wire cross-tick state plumbing into agent classes that accept it.+ # Without this, MonitorOperative/Operative agents have no working+ # session_store or memory_backend and silently no-op their state+ # recall / persistence paths.+ import inspect++ init_sig = inspect.signature(agent_cls.__init__)+ accepts_var_kw = any(+ p.kind == inspect.Parameter.VAR_KEYWORD+ for p in init_sig.parameters.values()+ )++ def _accepts(name: str) -> bool:+ return accepts_var_kw or name in init_sig.parameters++ state_kwargs: dict[str, Any] = {}+ if _accepts("operator_id"):+ state_kwargs["operator_id"] = agent["id"]+ if self._system is not None:+ if _accepts("session_store"):+ state_kwargs["session_store"] = getattr(+ self._system, "session_store", None+ )+ if _accepts("memory_backend"):+ state_kwargs["memory_backend"] = getattr(+ self._system, "memory_backend", None+ )+try:- agent_instance = agent_cls(engine, model, **agent_kwargs)+ agent_instance = agent_cls(+ engine, model, **agent_kwargs, **state_kwargs+ )except TypeError:- agent_instance = agent_cls(engine, model)+ try:+ agent_instance = agent_cls(engine, model, **agent_kwargs)+ except TypeError:+ agent_instance = agent_cls(engine, model)++ # Inject the managed-agent UUID into the agent's ToolExecutor so+ # emitted TOOL_CALL_START/END events carry it; the trace subscriber+ # below filters by ``event.data["agent"] == agent_id`` and would+ # otherwise drop every tool call (the class-level agent_id like+ # "monitor_operative" doesn't match the runtime UUID).+ inner_executor = getattr(agent_instance, "_executor", None)+ if inner_executor is not None and hasattr(inner_executor, "_agent_id"):+ inner_executor._agent_id = agent["id"]- # Build input from instruction + summary_memory + pending messages+ logger.info(+ "Agent %s: tool wiring — %d tools resolved (%s), agent class %s",+ agent["name"],+ len(tool_instances),+ ", ".join(t.spec.name for t in tool_instances) or "none",+ agent_cls.__name__,+ )++ # Build input from instruction + summary_memory + pending messages.+ # NB: we deliberately do NOT inject the full previous response back+ # in as "Previous context" — that caused the model to parrot its+ # own prior output verbatim. Cross-tick continuity now lives in the+ # agent's session_store / memory_backend; here we only surface a+ # short tick-boundary marker so the model knows time has passed.import datetime+ import retoday = datetime.date.today().strftime("%A, %B %d, %Y")instruction = config.get("instruction", "")- memory = agent.get("summary_memory", "")+ memory = (agent.get("summary_memory") or "").strip()+ last_run_at = agent.get("last_run_at")++ tick_note = ""+ if memory:+ first_sentence = re.split(r"(?<=[.!?])\s+", memory, maxsplit=1)[0]+ first_sentence = first_sentence.strip()[:200]+ if last_run_at:+ ts = datetime.datetime.fromtimestamp(last_run_at).strftime(+ "%Y-%m-%d %H:%M"+ )+ tick_note = f"Last tick at {ts}: {first_sentence}"+ else:+ tick_note = f"Previous tick: {first_sentence}"+if instruction:- input_text = f"Current date: {today}\n\nStanding instruction: {instruction}"- if memory:- input_text += f"\n\nPrevious context: {memory}"+ input_text = (+ f"Current date: {today}\n\nStanding instruction: {instruction}"+ )+ if tick_note:+ input_text += f"\n\n{tick_note}"else:- base = memory or "Continue your assigned task."+ base = tick_note or "Continue your assigned task."input_text = f"Current date: {today}\n\n{base}"pending = self._manager.get_pending_messages(agent["id"])if pending:diff --git a/src/openjarvis/agents/monitor_operative.py b/src/openjarvis/agents/monitor_operative.pyindex a26116bb..aaa918dd 100644--- a/src/openjarvis/agents/monitor_operative.py+++ b/src/openjarvis/agents/monitor_operative.py@@ -49,18 +49,18 @@ MONITOR_OPERATIVE_SYSTEM_PROMPT = """\You are a Monitor Operative Agent designed for long-horizon tasks.## Capabilities-1. TOOLS: Call any available tool via function calling-2. STATE: Your previous findings and state are automatically restored-3. MEMORY: Store important findings for future recall--## How to use tools--To call a tool, write on its own lines:--Action: <tool_name>-Action Input: <json_arguments>--You will receive the result, then continue your response.+1. TOOLS: You have access to tools via native function calling. The list+ below shows what is available — invoke them through the function-calling+ API, not by writing tool names into your text response.+2. STATE: Your previous findings and state are automatically restored from memory.+3. MEMORY: Store important findings via memory_store; recall via memory_retrieve.++## Critical Operating Rule+Your training data is frozen and out of date. For ANY question about recent,+current, or evolving information, you MUST call a substantive retrieval tool+(web_search, memory_retrieve, or an equivalent) BEFORE composing a response.+Writing fact claims about recent events from memory alone produces+hallucinations and is a failure mode.## Strategy- Memory extraction: {memory_extraction}@@ -70,6 +70,9 @@ You will receive the result, then continue your response.## Protocol- Break complex tasks into phases and track progress+- Prefer substantive tools (web_search, memory_retrieve) over reasoning-only+ tools (think) — `think` does not gather new information, only reorganises+ what you already have- Store causal relationships and key findings in memory- Compress long tool outputs before adding to context- Self-evaluate retrieved context for relevancediff --git a/src/openjarvis/tools/_stubs.py b/src/openjarvis/tools/_stubs.pyindex e2a722b3..4eb2bea6 100644--- a/src/openjarvis/tools/_stubs.py+++ b/src/openjarvis/tools/_stubs.py@@ -225,11 +225,18 @@ class ToolExecutor:success=False,)- # Emit start event+ # Emit start event. ``agent`` carries the managed-agent UUID so the+ # AgentExecutor's trace subscriber (which filters by agent_id) can+ # actually match this event — without it, every tool call is silently+ # dropped from traces.if self._bus:self._bus.publish(EventType.TOOL_CALL_START,- {"tool": tool_call.name, "arguments": params},+ {+ "tool": tool_call.name,+ "arguments": params,+ "agent": self._agent_id,+ },)# Execute with timeout@@ -289,6 +296,7 @@ class ToolExecutor:"latency": latency,"result": result_text,"metadata": event_metadata,+ "agent": self._agent_id,},)