"""Truth ledger built from actual tool-step envelopes. A ledger entry is evidence: tool, outcome, error code, tab id, timestamp and a short detail. Summaries describe only what those entries prove. In particular, an HTTP fetch and a browser-tab action remain distinct facts, so the system never implies that a browser saw content that only an HTTP request obtained. """ from __future__ import annotations from dataclasses import dataclass from datetime import UTC, datetime from typing import Any @dataclass(frozen=True) class LedgerEntry: """One actual per-step result.""" tool: str ok: bool error_code: str | None = None tab_id: str | None = None at: str = "" detail: str | None = None @classmethod def from_envelope(cls, envelope: dict[str, Any]) -> LedgerEntry: """Project an executor envelope into a ledger entry.""" error = envelope.get("error") error_code = error.get("code") if isinstance(error, dict) else None detail = envelope.get("detail") if detail is None: data = envelope.get("data") if isinstance(data, dict): detail = data.get("detail") if detail is None: detail = error.get("message") if isinstance(error, dict) else None return cls( tool=str(envelope.get("tool", "unknown")), ok=bool(envelope.get("ok", False)), error_code=str(error_code) if error_code else None, tab_id=str(envelope["tab_id"]) if envelope.get("tab_id") else None, at=datetime.now(UTC).isoformat(), detail=str(detail) if detail else None, ) def _is_http_tool(tool: str) -> bool: return tool in {"http_fetch", "web_search"} def _is_tab_open_tool(tool: str) -> bool: """Only ``tab_open`` OPENS a tab. ``tab_select`` and ``tab_close`` act on a tab that already exists, so a successful one is evidence about that tab - not evidence that a tab was opened. Deriving "a tab was opened" from a tab id overclaims. """ return tool == "tab_open" def _is_navigation_tool(tool: str) -> bool: """A successful navigate proves the browser LOADED a page.""" return tool == "navigate" def _is_content_observation_tool(tool: str) -> bool: """Tools that actually RETURN page content. Navigating proves a page was loaded, but the browser did not read the page body; clicking and scrolling do not observe content either. Only these tools prove that the browser saw the content. """ return tool in {"observe", "extract_text", "screenshot"} def render_ledger(entries: list[LedgerEntry]) -> str: """Render a compact human-readable timeline.""" if not entries: return "No tool steps were recorded." lines: list[str] = [] for entry in entries: outcome = "OK" if entry.ok else "FAIL" parts = [f"{entry.at} {outcome} {entry.tool}"] if entry.error_code: parts.append(f"code={entry.error_code}") if entry.tab_id: parts.append(f"tab={entry.tab_id}") if entry.detail: parts.append(entry.detail) lines.append(" | ".join(parts)) return "\n".join(lines) def summarize(entries: list[LedgerEntry]) -> dict[str, Any]: """Return only the facts proven by the supplied step envelopes.""" tools_succeeded = sorted({entry.tool for entry in entries if entry.ok}) tools_failed = sorted({entry.tool for entry in entries if not entry.ok}) failed_error_codes = { entry.tool: entry.error_code for entry in entries if not entry.ok and entry.error_code } http_succeeded = any(entry.ok and _is_http_tool(entry.tool) for entry in entries) browser_tab_opened = any( entry.ok and _is_tab_open_tool(entry.tool) for entry in entries ) browser_navigated = any( entry.ok and _is_navigation_tool(entry.tool) for entry in entries ) browser_saw_content = any( entry.ok and _is_content_observation_tool(entry.tool) for entry in entries ) return { "tools_succeeded": tools_succeeded, "tools_failed": tools_failed, "failed_error_codes": failed_error_codes, "http_succeeded": http_succeeded, "browser_tab_opened": browser_tab_opened, "browser_navigated": browser_navigated, "browser_saw_content": browser_saw_content, "all_succeeded": bool(entries) and not tools_failed, "step_count": len(entries), } def honest_mixed_result_sentence(entries: list[LedgerEntry]) -> str: """Describe the common HTTP/browser mixed case without overclaiming.""" summary = summarize(entries) http_tools = sorted( {entry.tool for entry in entries if entry.ok and _is_http_tool(entry.tool)} ) failed_codes = summary["failed_error_codes"] if summary["http_succeeded"] and not summary["browser_tab_opened"]: source = ", ".join(http_tools) if http_tools else "an HTTP source" code_text = "" if failed_codes: code_text = " (error: " + ", ".join( f"{tool}: {code}" for tool, code in sorted(failed_codes.items()) ) + ")" return ( f"The content was fetched over HTTP using {source}{code_text}, but the " "browser did not open a tab and the browser did not see the content." ) if summary["http_succeeded"] and summary["browser_saw_content"]: source = ", ".join(http_tools) if http_tools else "an HTTP source" return ( f"The content was fetched over HTTP using {source}, and the browser " "successfully opened a tab and saw the content." ) if summary["browser_saw_content"]: return "The browser successfully opened a tab and saw the content." if summary["http_succeeded"]: source = ", ".join(http_tools) if http_tools else "an HTTP source" return f"The content was fetched over HTTP using {source}; no browser content was observed." return "No successful HTTP fetch or browser observation was recorded."