Personal AI, On Personal Devices
Python
fix(agents): recover opencode tool-results from the full turn, not just the final message
krypticmouse20f90f3ca06a
diff --git a/src/openjarvis/agents/opencode.py b/src/openjarvis/agents/opencode.pyindex a53cce11..c0f429d5 100644--- a/src/openjarvis/agents/opencode.py+++ b/src/openjarvis/agents/opencode.py@@ -76,12 +76,13 @@ def _extract_tool_results(parts: List[dict]) -> List[ToolResult]:status = state.get("status", "")output = state.get("output")if output is None:- output = state.get("title", "") or json.dumps(state) if state else ""+ output = state.get("title", "") or (json.dumps(state) if state else "")results.append(ToolResult(tool_name=p.get("tool", p.get("name", "unknown")),content=str(output),- success=status not in ("error", "failed"),+ # opencode tool state: completed | error | running | pending+ success=status == "completed",))return results@@ -277,6 +278,8 @@ class OpenCodeAgent(BaseAgent):content=str(exc), turns=1, metadata={"error": True})+ data: dict = {}+ turn_parts: List[dict] = []try:with self._client() as c:ses = c.post("/session", json={"title": input[:80]})@@ -299,6 +302,23 @@ class OpenCodeAgent(BaseAgent):resp = c.post(f"/session/{session_id}/message", json=body)resp.raise_for_status()data = resp.json()++ # The prompt POST returns only the final assistant message;+ # tool executions live in intermediate messages of the turn, so+ # pull the whole session to recover them (verified against a+ # live opencode session). Falls back to the final message.+ turn_parts = list(data.get("parts", []))+ try:+ msgs = c.get(f"/session/{session_id}/message").json()+ if isinstance(msgs, list):+ turn_parts = [+ part+ for mm in msgs+ if isinstance(mm, dict)+ for part in mm.get("parts", [])+ ]+ except Exception as get_exc:+ logger.debug("opencode message fetch failed: %s", get_exc)except Exception as exc:logger.error("opencode run failed: %s", exc, exc_info=True)self._emit_turn_end(turns=1, error=True)@@ -308,10 +328,9 @@ class OpenCodeAgent(BaseAgent):metadata={"error": True},)- parts = data.get("parts", []) if isinstance(data, dict) else []info = data.get("info", {}) if isinstance(data, dict) else {}- content = _extract_text(parts)- tool_results = _extract_tool_results(parts)+ content = _extract_text(data.get("parts", []))+ tool_results = _extract_tool_results(turn_parts)self._emit_turn_end(turns=1)return AgentResult(diff --git a/tests/agents/test_opencode_agent.py b/tests/agents/test_opencode_agent.pyindex 27c2b21c..75d5c76f 100644--- a/tests/agents/test_opencode_agent.py+++ b/tests/agents/test_opencode_agent.py@@ -138,6 +138,22 @@ class _FakeResp:return self._d+# Full-turn message list as returned by GET /session/{id}/message: the tool+# executes in an intermediate assistant message, not the final one (this shape+# was captured from a live opencode session).+TURN_MESSAGES = [+ {"info": {"role": "user"}, "parts": [{"type": "text", "text": "..."}]},+ {"info": {"role": "assistant"}, "parts": [+ {"type": "step-start"},+ {"type": "tool", "tool": "write", "callID": "c1",+ "state": {"status": "completed", "output": "Wrote file successfully.",+ "input": {"filePath": "greet.py", "content": "x"}}},+ {"type": "step-finish", "reason": "tool"},+ ]},+ SPIKE_RESPONSE, # final assistant message (text only)+]++class _FakeClient:def __enter__(self):return self@@ -153,9 +169,12 @@ class _FakeClient:return _FakeResp(SPIKE_RESPONSE)return _FakeResp({})+ def get(self, path, **kw):+ return _FakeResp(TURN_MESSAGES)+class TestRunParsing:- def test_run_parses_message(self, monkeypatch, tmp_path):+ def test_run_parses_message_and_tools(self, monkeypatch, tmp_path):agent = OpenCodeAgent(SimpleNamespace(_host="http://h:1"), "local-model",workspace=str(tmp_path), agent="build")monkeypatch.setattr(agent, "_ensure_server", lambda: "http://127.0.0.1:7654")@@ -171,4 +190,8 @@ class TestRunParsing:assert _FakeClient.last_body["model"] == {"providerID": "openjarvis", "modelID": "local-model"}- assert _FakeClient.last_body["agent"] == "build"+ # tool-results recovered from the intermediate message (not the final one)+ assert len(res.tool_results) == 1+ assert res.tool_results[0].tool_name == "write"+ assert res.tool_results[0].success is True+ assert "Wrote file" in res.tool_results[0].content