Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(agent-core): load stored hosted results for tools this build does not know (#2920)
Call White8072b510b3ef
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex c0cfdd43d..fb721c6e1 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -9,11 +9,14 @@ rows, so the field names here are a shipped surface.from __future__ import annotationsimport copy+import loggingimport osimport refrom dataclasses import dataclass, fieldfrom typing import Any, Literal, Mapping, Optional, Union+logger = logging.getLogger(__name__)+ProtocolName = Literal["anthropic", "openai_chat", "openai_responses", "google"]PROTOCOLS: tuple[str, ...] = ("anthropic", "openai_chat", "openai_responses", "google")@@ -1032,7 +1035,55 @@ def _block_to_dict(block: Any) -> dict[str, Any]:raise TypeError(f"not a content block: {type(block).__name__}")-def _block_from_dict(data: Any, allowed_types: tuple[str, ...]) -> Any:+def _unknown_hosted_text(data: Mapping[str, Any]) -> str:+ """Render an unknown native hosted block without validating its future shape."""++ tool = data.get("tool")+ tool_name = tool if isinstance(tool, str) and tool else "hosted tool"+ action = data.get("action") if isinstance(data.get("action"), Mapping) else {}+ record = data.get("record") if isinstance(data.get("record"), Mapping) else {}+ queries: list[str] = []+ raw_queries = action.get("queries")+ if isinstance(raw_queries, list):+ queries.extend(query for query in raw_queries if isinstance(query, str) and query)+ for name in ("query", "url"):+ value = action.get(name)+ if isinstance(value, str) and value and value not in queries:+ queries.append(value)+ lines: list[str] = []+ status = record.get("status")+ if isinstance(status, str) and status and status != "completed":+ suffix = ": no result" if status == "pending" else ""+ lines.append(f"[{tool_name} {status}{suffix}]")+ error = record.get("error")+ if isinstance(error, str) and error:+ lines.append(f"Error: {error}")+ if queries:+ lines.append(f"[{tool_name}: {'; '.join(queries)}]")+ raw_sources = record.get("sources")+ if isinstance(raw_sources, list):+ for number, source in enumerate(raw_sources, 1):+ if not isinstance(source, Mapping):+ continue+ url = source.get("url") if isinstance(source.get("url"), str) else None+ title = source.get("title") if isinstance(source.get("title"), str) else None+ snippet = source.get("snippet") if isinstance(source.get("snippet"), str) else None+ page_age = source.get("page_age") if isinstance(source.get("page_age"), str) else None+ if not any((url, title, snippet, page_age)):+ continue+ lines.append(f"{number}. {title or url or snippet or page_age}")+ if title and url:+ lines.append(f" {url}")+ if snippet:+ lines.append(f" {snippet}")+ if page_age:+ lines.append(f" Published: {page_age}")+ return "\n".join(lines) if lines else f"[{tool_name} result unavailable in this version]"+++def _block_from_dict(+ data: Any, allowed_types: tuple[str, ...], *, unknown_hosted_tools: list[str] | None = None+) -> Any:kind = data.get("type") if isinstance(data, Mapping) else Noneif kind not in allowed_types:raise ValueError(f"block type {kind!r} is not allowed here")@@ -1052,6 +1103,11 @@ def _block_from_dict(data: Any, allowed_types: tuple[str, ...]) -> Any:)return TextBlock(text=f.get("text"), ref=ref, citations=citations)if kind == "hosted_tool":+ raw_tool = data.get("tool") if isinstance(data, Mapping) else None+ if isinstance(raw_tool, str) and raw_tool not in HOSTED_TOOLS:+ if unknown_hosted_tools is not None:+ unknown_hosted_tools.append(raw_tool)+ return TextBlock(text=_unknown_hosted_text(data))f = _read(data,"hosted tool block",@@ -1186,8 +1242,22 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:{"role": str, "content": list, "origin": dict, "stop_reason": str},{"usage": dict, "error_message": str, "hosted_summary": dict, "source_identity": str},)+ # Decode calls before their aggregate: unknown calls make response-wide facts unusable.+ unknown_hosted_tools: list[str] = []+ content = tuple(+ _block_from_dict(+ b, ("text", "thinking", "tool_call", "hosted_tool"), unknown_hosted_tools=unknown_hosted_tools+ )+ for b in f["content"]+ )summary = None- if "hosted_summary" in f:+ if unknown_hosted_tools:+ logger.warning("stored message contains an unrecognized hosted tool; loading it portably")+ # Do not interpret a discarded aggregate's future shape. Keep an empty envelope for known blocks,+ # but do not invent a missing summary; retained blocks and the message envelope remain strict.+ if "hosted_summary" in f and any(isinstance(block, HostedToolBlock) for block in content):+ summary = HostedSummary()+ elif "hosted_summary" in f:h = _read(f["hosted_summary"], "hosted summary", {"counts": dict, "cited_sources": list}, {"cost": dict})summary = HostedSummary(# A release before the bound may have stored a count past it: that counter is dropped, not refused,@@ -1201,7 +1271,7 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:cost=_cost_from_dict(h["cost"]) if "cost" in h else None,)return AssistantMessage(- content=tuple(_block_from_dict(b, ("text", "thinking", "tool_call", "hosted_tool")) for b in f["content"]),+ content=content,origin=origin_from_dict(f["origin"]),stop_reason=f["stop_reason"],usage=usage_from_dict(f["usage"]) if "usage" in f else None,@@ -1217,7 +1287,8 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:{"hosted": dict},)hosted_result = None- if "hosted" in f:+ unknown_hosted_tool = "hosted" in f and f["tool_name"] not in HOSTED_RESULT_TOOLS+ if "hosted" in f and not unknown_hosted_tool:h = _read(f["hosted"], "hosted result", {"record": dict}, {"execution": dict, "action": dict, "fallback_from": dict})@@ -1261,6 +1332,8 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:action=_action_from_dict(h["action"]) if "action" in h else None,fallback_from=fallback,)+ if unknown_hosted_tool:+ logger.warning("stored message contains an unrecognized hosted tool; loading it portably")return ToolResultMessage(tool_call_id=f["tool_call_id"],tool_name=f["tool_name"],diff --git a/docs/plans/agent-core-contracts/cross-provider.md b/docs/plans/agent-core-contracts/cross-provider.mdindex 952b3f505..66881d687 100644--- a/docs/plans/agent-core-contracts/cross-provider.md+++ b/docs/plans/agent-core-contracts/cross-provider.md@@ -17,6 +17,22 @@ cross-provider history tests (MIT).| Text block `citations` | not sent | not sent || Tool result with `hosted` (a proxied hosted call) | kept, as any tool result | kept, as any tool result |+**Reader compatibility.** Deserialization does not require the current hosted-tool registry to read stored history.++- A native `HostedToolBlock` whose `tool` this build does not recognize becomes one portable `TextBlock` with any+ query or URL and its sources, or a one-line unavailable placeholder. Readable non-completed status and error are+ kept; a pending call explicitly has no result, never an implied success.+- Whenever any native block is degraded, response-wide counts, cited sources and cost are discarded because they+ cannot be partitioned between unknown and known calls. Decode the calls first and do not validate the discarded+ aggregate's contents against this build's summary/source schema. An existing summary becomes empty if recognized+ hosted blocks remain, and is omitted otherwise; a missing summary for a recognized block remains invalid.+- A proxied `ToolResultMessage.hosted` whose `tool_name` is unknown becomes an ordinary tool result with its stored+ `content` and `is_error`, and `hosted` is dropped.++This degradation applies only to unrecognized tool names: the message envelope and known tools remain strictly+validated, new writes remain strict, stored rows are not rewritten, and each degraded row logs one warning without+content.+Invariants:- Thinking never goes to a different origin, in any form (owner decision, 2026-10-21; Pi converts it to text). It isdiff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 6650cbc73..820e79d1b 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -426,10 +426,19 @@ never dropped.from receiving it), so an `image_generation_call` is ignored like any undeclared item, and a line over 8 MiB failsthe stream like any oversized line. The #2589 codes `image_not_streamed` and `provider_no_image` lose theirproducers and stay in `HOSTED_ERROR_CODES` for records already written.-- **rc-era transcripts are not migrated.** An rc session may hold an assistant row with a native `image_generation`- `HostedToolBlock`. No reader branch keeps that removed shape alive (owner directive; AGENTS.md forbids reintroducing- a removed optional-feature artifact through a compatibility shim), so such a session no longer loads its context- (§15).+- **Stored history survives hosted-tool registry changes.** An unrecognized native `HostedToolBlock` loads as+ portable text with its query or URL and sources when renderable, otherwise a one-line unavailable placeholder.+ The projection keeps a readable non-completed status and error, including an explicit no-result marker for pending+ calls, so a failed or interrupted call is never presented as a successful result.+ This includes an rc-era `image_generation` block without restoring its removed native shape or replay path.+ A proxied result for an unrecognized tool keeps its `content` and `is_error`, with `hosted` dropped. New writes+ and known-tool rows remain strict; no migration or stored-row rewrite is performed, and each degraded row logs+ one warning without content.+ If any native block is degraded, response-wide counts, cited sources and cost are discarded: they cannot be+ partitioned between the unknown call and the remaining calls. Calls are decoded before that aggregate, and its+ discarded contents are not validated against this build's summary/source schema. A known block still requires a+ summary; an existing summary becomes empty when known blocks remain and is omitted when none remain (§15).+ The message envelope and retained known blocks remain strictly validated.- **Per adapter notes.** xAI's X-search `reasoning` items (`tco_…`) stay ThinkingBlocks. The `custom_tool_call`becomes the HostedToolBlock, never a local tool call. Anthropic's `encrypted_content` is kept only in`native.payload`. Hosted payloads count against the 32 MiB `StreamAssembler` budget; search events measured at@@ -826,8 +835,8 @@ under the freeze protocol (`model-hub-contracts/README.md`).### 10.1 C-1 (`agent-core-contracts/message.schema.json`, `cross-provider.md`, `conversion-tables.md`)-- A `HostedToolBlock` has `tool` `web_search` | `x_search`, written and read; an rc-era `image_generation` block is not- accepted (§4.2, §15).+- A new `HostedToolBlock` has `tool` `web_search` | `x_search`, and known-tool rows are read strictly. Stored+ unrecognized tools, including rc-era `image_generation`, load as portable text rather than native blocks (§4.2, §15).- `ToolResultMessage.hosted` keeps `{record, execution?, action?}`. `record.images[]` and `action: generate` occuronly for `image_generate`; `generate` gains the `model` used, with `prompt` required for a `completed` record.- `ProxyExecution` becomes the result's `execution` with `mode: "proxy" | "direct"` (direct for an image endpoint)@@ -970,6 +979,11 @@ and no real credentials.unless enabled.7. **rc-era state is not migrated** (owner directive): probe evidence carries `basis: probe`, which v2's loader does notaccept, so those records are pruned; an rc-era `hosted_tools` section keeps each tool's `enabled`, and its unknown- keys and fields are ignored (§3.3); an rc session holding a native `image_generation` block no longer loads its- context (§4.2), and its turn ends with the existing localized context-load error ("this session's history can't- be loaded; start a new session"), never a raw traceback: ordinary error handling, not a compatibility path.+ keys and fields are ignored (§3.3). An rc session holding a removed native `image_generation` block is not restored+ as a native image tool: the current reader degrades any unrecognized native hosted block to portable text, as it does+ for a future hosted tool this build does not know.+8. **History is readable across hosted-tool registry changes.** A stored hosted result for a tool added by a newer build+ loads as an ordinary tool result, and a native call loads as portable text with its query or URL and sources when+ available, otherwise a one-line unavailable placeholder. A degraded native block also clears unpartitionable+ response-wide facts (§4.2). The row is not rewritten, new writes stay strict, and known tools retain strict+ validation; this is the intentional downgrade path before a new hosted tool ships.diff --git a/tests/agent_core/test_hosted_messages.py b/tests/agent_core/test_hosted_messages.pyindex cba111461..ce8a9173e 100644--- a/tests/agent_core/test_hosted_messages.py+++ b/tests/agent_core/test_hosted_messages.py@@ -1,8 +1,9 @@"""C-1 hosted-tool shapes (``vibey-hosted-tools.md`` §4.2 and §12 items 1-6, 22, 28).The dataclasses in ``core.agent_core.messages`` are the producer; ``message.schema.json``-is the contract other components read. Every invariant is checked twice: the schema and-the reader must refuse the same shapes, and what the producer writes must validate.+is the contract other components read. Known-tool shapes are checked by both the+schema and the reader, and what the producer writes must validate. Stored unknown+tools have a reader-only portable fallback; new writes remain strict."""from __future__ import annotations@@ -272,20 +273,25 @@ VIOLATIONS = {"generate-on-web-search": _set(NATIVE, ("content", 0, "action"), {"type": "generate", "prompt": "p"}),"generate-on-proxied-search": _set(PROXIED, ("hosted", "action"), {"type": "generate", "prompt": "p"}),"search-on-x-search": _set(NATIVE, ("content", 2, "action"), {"type": "search", "queries": ["q"]}),- # v2 has no native image tool, and an rc-era block is not read (§4.2, §15).- "native-image-block": _set(NATIVE, ("content", 0, "tool"), "image_generation"),"unknown-action": _set(NATIVE, ("content", 0, "action"), {"type": "browse", "url": "https://a"}),"field-of-another-action": _set(NATIVE, ("content", 0, "action", "url"), "https://a"),"empty-queries": _set(NATIVE, ("content", 0, "action", "queries"), []),"x-search-limit-zero": _set(NATIVE, ("content", 2, "action", "limit"), 0),"x-search-mode": _set(NATIVE, ("content", 2, "action", "mode"), "latest"),- "unknown-tool": _set(NATIVE, ("content", 0, "tool"), "code_interpreter"),"empty-payload": _set(NATIVE, ("content", 0, "native", "payload"), []),"payload-not-objects": _set(NATIVE, ("content", 0, "native", "payload"), ["web_search_call"]),"native-replay-flag": _set(NATIVE, ("content", 0, "native", "replay"), True),"bad-source-id": _set(NATIVE, ("content", 0, "native", "source_id"), "xai-key"),"summary-without-hosted-block": _set(message_to_dict(_produced()[1]), ("hosted_summary",), {"counts": {}, "cited_sources": []}),"hosted-block-without-summary": _without(NATIVE, (), "hosted_summary"),+ "mixed-hosted-block-without-summary": _without(+ _set(NATIVE, ("content", 0, "tool"), "web_fetch"), (), "hosted_summary"+ ),+ "mixed-known-tool-with-invalid-action": _set(+ _set(NATIVE, ("content", 0, "tool"), "web_fetch"), ("content", 1, "action"), {"type": "fetch"}+ ),+ "unknown-summary-field": _set(NATIVE, ("hosted_summary", "future_total"), 3),+ "unknown-summary-source-field": _set(NATIVE, ("hosted_summary", "cited_sources", 0, "confidence"), 0.9),"included-with-usd": _set(NATIVE, ("hosted_summary", "cost"), {"basis": "included", "usd": 0.1}),"list-without-usd": _set(NATIVE, ("hosted_summary", "cost"), {"basis": "list"}),"negative-usd": _set(NATIVE, ("hosted_summary", "cost", "usd"), -0.01),@@ -305,7 +311,6 @@ VIOLATIONS = {_set(PROXIED, ("hosted", "record"), {"status": "failed", "error": "upstream 500", "sources": []}), ("is_error",), False),"completed-result-flagged": _set(PROXIED, ("is_error",), True),- "hosted-on-local-tool": _set(PROXIED, ("tool_name",), "bash"),"execution-mode": _set(PROXIED, ("hosted", "execution", "mode"), "native"),"proxy-billing": _set(PROXIED, ("hosted", "execution", "executor_billing"), "free"),"failed-attempt-billing": _set(PROXIED, ("hosted", "execution", "failed_attempts", 0, "billing"), "free"),@@ -324,6 +329,108 @@ def test_schema_and_reader_refuse_the_same_hosted_violations(payload):message_from_dict(payload)+def test_a_stored_proxied_result_for_an_unknown_tool_loads_as_a_plain_result(caplog):+ stored = _set(_set(PROXIED, ("tool_name",), "web_fetch"), ("is_error",), True)++ loaded = message_from_dict(stored)++ assert isinstance(loaded, ToolResultMessage)+ assert loaded.tool_name == "web_fetch"+ assert loaded.hosted is None+ assert loaded.is_error is True+ assert message_to_dict(loaded) == {key: value for key, value in stored.items() if key != "hosted"}+ assert [record.levelname for record in caplog.records] == ["WARNING"]++[email protected]("keep_known", [False, True], ids=["all-unknown", "mixed"])+ ("action", "record", "summary_extension", "expected"),+ [+ (+ {"type": "open_page", "url": "https://example.com/docs"},+ {"status": "completed", "sources": [{"url": "https://example.com/docs", "title": "Example Docs"}]},+ {},+ ("https://example.com/docs", "Example Docs"),+ ),+ ({"type": "fetch"}, {"status": "completed", "sources": []}, {}, ("result unavailable in this version",)),+ (+ {"type": "fetch", "query": "a failed query"},+ {"status": "failed", "error": "permission denied", "sources": []},+ {},+ ("failed", "permission denied", "a failed query"),+ ),+ (+ {"type": "open_page", "url": "https://example.com/docs"},+ {"status": "incomplete", "error": "timed out", "sources": [{"url": "https://example.com/partial"}]},+ {},+ ("incomplete", "timed out", "https://example.com/docs", "https://example.com/partial"),+ ),+ (+ {"type": "fetch", "queries": ["pending query"]},+ {"status": "pending", "sources": []},+ {},+ ("pending", "no result", "pending query"),+ ),+ (+ {"type": "fetch"},+ {"status": "failed", "error": "fetch refused", "sources": []},+ {},+ ("failed", "fetch refused"),+ ),+ (+ {"type": "fetch"},+ {"status": "completed", "sources": []},+ {"future_total": 3},+ ("result unavailable in this version",),+ ),+ (+ {"type": "fetch"},+ {"status": "completed", "sources": []},+ {"cited_sources": [{"url": "https://example.com/future", "confidence": 0.9}]},+ ("result unavailable in this version",),+ ),+ ],+ ids=["query-and-source", "placeholder", "failed", "incomplete", "pending", "error-only", "future-summary", "future-source"],+)+def test_a_native_unknown_hosted_block_loads_as_portable_text(+ action, record, summary_extension, expected, keep_known, caplog+):+ stored = copy.deepcopy(NATIVE)+ if not keep_known:+ stored["content"] = stored["content"][:1]+ stored["content"][0].update(tool="web_fetch", action=action, record=record)+ stored["hosted_summary"].update(summary_extension)+ original = copy.deepcopy(stored)++ loaded = message_from_dict(stored)++ assert isinstance(loaded, AssistantMessage)+ if keep_known:+ assert loaded.hosted_summary is not None+ assert loaded.hosted_summary.counts == {}+ assert loaded.hosted_summary.cited_sources == ()+ assert loaded.hosted_summary.cost is None+ else:+ assert loaded.hosted_summary is None+ portable = message_to_dict(loaded)+ assert portable["content"][1:] == stored["content"][1:]+ assert isinstance(loaded.content[0], TextBlock)+ assert all(fragment in loaded.content[0].text for fragment in expected)+ VALIDATOR.validate(portable)+ assert stored == original+ assert [record.levelname for record in caplog.records] == ["WARNING"]+++def test_new_hosted_result_for_an_unknown_tool_stays_strict():+ with pytest.raises(ValueError, match="web_fetch is not a hosted tool"):+ ToolResultMessage(+ tool_call_id="call_unknown",+ tool_name="web_fetch",+ content=(TextBlock(text="result"),),+ hosted=_produced()[4].hosted,+ )++def test_a_count_past_the_bound_is_never_written_and_a_stored_one_is_dropped_on_read():"""#2572: a count is at most 2^53 - 1, the largest integer every JSON reader holds exactly. A release before thebound may have stored a larger one: that counter alone is dropped, so its transcript still loads."""diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.pyindex 60c427dd2..aa31e9d50 100644--- a/tests/test_agent_transcript.py+++ b/tests/test_agent_transcript.py@@ -258,6 +258,73 @@ async def test_every_kind_round_trips_in_one_order_attributed_to_the_turn(engine]+async def test_a_stored_unknown_native_hosted_row_loads_through_the_transcript_owner(engine):+ with engine.begin() as conn:+ home = _scope(conn, "C-hosted-history")+ _session(conn, "ses_hosted_history", home)+ consumed = _row(conn, "ses_hosted_history", home, "go")+ store = SQLiteTranscriptStore(engine)+ await store.consume_input("ses_hosted_history", consumed, _user("go"))+ response = await store.append_response("ses_hosted_history", _assistant("stored"), final=True)+ tool_result = await store.append_tool_result(+ "ses_hosted_history", _tool_result("call_unknown", "stored tool result"), details={}+ )++ unknown = {+ "role": "assistant",+ "content": [+ {+ "type": "hosted_tool",+ "id": "fetch_1",+ "tool": "web_fetch",+ "action": {"type": "open_page", "url": "https://example.com/docs"},+ "record": {+ "status": "completed",+ "sources": [{"url": "https://example.com/docs", "title": "Example Docs"}],+ },+ "native": {"source_id": "src_x1a2b3c4d5", "payload": []},+ }+ ],+ "origin": {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5"},+ "stop_reason": "stop",+ "hosted_summary": {"counts": {}, "cited_sources": []},+ }+ unknown_tool_result = {+ "role": "tool_result",+ "tool_call_id": "call_unknown",+ "tool_name": "web_fetch",+ "content": [{"type": "text", "text": "stored tool result"}],+ "is_error": True,+ "hosted": {"record": {"status": "completed", "sources": []}},+ }+ with engine.begin() as conn:+ row = conn.execute(select(messages.c.content_json).where(messages.c.id == response.row_id)).scalar_one()+ payload = json.loads(row)+ payload["model"]["message"] = unknown+ conn.execute(messages.update().where(messages.c.id == response.row_id).values(content_json=json.dumps(payload)))+ event_payload = conn.execute(+ select(agent_events.c.content_json).where(agent_events.c.id == tool_result.row_id)+ ).scalar_one()+ event = json.loads(event_payload)+ event["message"] = unknown_tool_result+ conn.execute(+ agent_events.update().where(agent_events.c.id == tool_result.row_id).values(content_json=json.dumps(event))+ )++ loaded = list(await store.load("ses_hosted_history"))++ assert len(loaded) == 3+ restored = loaded[1].message+ assert isinstance(restored, AssistantMessage)+ assert restored.hosted_summary is None+ assert isinstance(restored.content[0], TextBlock)+ assert "https://example.com/docs" in restored.content[0].text+ assert "Example Docs" in restored.content[0].text+ result = loaded[2].message+ assert isinstance(result, ToolResultMessage)+ assert result.hosted is None and result.is_error is True++async def test_rows_outside_the_context_never_load(engine) -> None:with engine.begin() as conn:home = _scope(conn, "C-home")