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): one owner for persisted shape checks; contract updates
cyh507efd59877d
diff --git a/core/agent_core/agent/events.py b/core/agent_core/agent/events.pyindex 54320578a..c2b7843ff 100644--- a/core/agent_core/agent/events.py+++ b/core/agent_core/agent/events.py@@ -1,8 +1,9 @@"""C-4 agent events (``agent-core-contracts/agent-event.schema.json``).Yielded by ``Agent.run`` in process; committed context lives in transcript rows,-which these events reference by id. The adapter maps them onto existing Avibe-outputs (``loop-control.md`` section 6).+which these events reference by id. ``turn_id`` is ``session_turns.id``, the same+identity as ``agent_events.turn_id``; the Harness Run id stays with the adapter.+The adapter maps events onto existing Avibe outputs (``loop-control.md`` section 6)."""from __future__ import annotations@@ -16,27 +17,27 @@ CompactionReason = Literal["manual", "threshold", "overflow"]@dataclass(frozen=True)class RunStarted:- run_id: str+ turn_id: strseq: int@dataclass(frozen=True)class AssistantTextDelta:- run_id: str+ turn_id: strseq: intdelta: str@dataclass(frozen=True)class AssistantThinkingDelta:- run_id: str+ turn_id: strseq: intdelta: str@dataclass(frozen=True)class MessageCommitted:- run_id: str+ turn_id: strseq: intmessage_id: strcontext_seq: int@@ -45,7 +46,7 @@ class MessageCommitted:@dataclass(frozen=True)class ToolStarted:- run_id: str+ turn_id: strseq: inttool_call_id: strname: str@@ -55,7 +56,7 @@ class ToolStarted:@dataclass(frozen=True)class ToolProgress:- run_id: str+ turn_id: strseq: inttool_call_id: strtail: str@@ -63,7 +64,7 @@ class ToolProgress:@dataclass(frozen=True)class ToolFinished:- run_id: str+ turn_id: strseq: inttool_call_id: strevent_id: str@@ -73,21 +74,21 @@ class ToolFinished:@dataclass(frozen=True)class SteerApplied:- run_id: str+ turn_id: strseq: intmessage_id: str@dataclass(frozen=True)class CompactionStarted:- run_id: str+ turn_id: strseq: intreason: CompactionReason@dataclass(frozen=True)class CompactionFinished:- run_id: str+ turn_id: strseq: intevent_id: strreason: CompactionReason@@ -97,7 +98,7 @@ class CompactionFinished:@dataclass(frozen=True)class CompactionFailed:- run_id: str+ turn_id: strseq: intreason: CompactionReasonerror: str@@ -105,14 +106,14 @@ class CompactionFailed:@dataclass(frozen=True)class RunEnded:- run_id: str+ turn_id: strseq: intreason: RunEndReason@dataclass(frozen=True)class AgentError:- run_id: str+ turn_id: strseq: intkind: strmessage: strdiff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex e6584ec74..5b62c5e01 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -30,6 +30,27 @@ class ModelEndpoint:provider: str = ""+@dataclass(frozen=True)+class ModelCapabilities:+ """From C-6 hop resolution. ``None`` means Model Hub does not know; callers treat it conservatively."""++ context_window: Optional[int] = None+ input_limit: Optional[int] = None+ max_output_tokens: Optional[int] = None+ supports_tools: Optional[bool] = None+ supports_images: Optional[bool] = None+ supports_reasoning: Optional[bool] = None+ reasoning_efforts: tuple[str, ...] = ()+++class MediaLoader(Protocol):+ """Supplied by the adapter layer; resolves an ``ImageBlock.media_token`` to its bytes at request time."""++ async def load(self, media_token: str) -> tuple[bytes, str]:+ """Return the bytes and their mime type."""+ ...++@dataclass(frozen=True)class ModelRequest:endpoint: ModelEndpoint@@ -39,7 +60,8 @@ class ModelRequest:max_tokens: intreasoning_effort: Optional[str] = Nonecache: Literal["default", "none"] = "default"- supports_images: bool = True+ supports_images: bool = False+ """Resolved by the loop from ``ModelCapabilities``; an unknown capability counts as False."""@dataclass(frozen=True)diff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex b1bde3205..b001e60c4 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -31,7 +31,7 @@ class LargeRef:bytes: intdef __post_init__(self) -> None:- if not _LARGE_REF_RE.match(self.ref) or self.bytes < 0:+ if not _LARGE_REF_RE.fullmatch(self.ref) or self.bytes < 0:raise ValueError(f"invalid large-content reference: {self.ref!r}")@@ -56,6 +56,8 @@ class ImageBlock:raise ValueError(f"unsupported image type: {self.mime_type}")if not self.media_token:raise ValueError("an image block needs a media token")+ if self.name is not None and not self.name:+ raise ValueError("an image name, when present, must not be empty")@dataclass(frozen=True)@@ -64,6 +66,10 @@ class ThinkingBlock:signature: Optional[str] = Noneredacted: bool = False+ def __post_init__(self) -> None:+ if self.signature is not None and not self.signature:+ raise ValueError("a signature, when present, must not be empty")+@dataclass(frozen=True)class ToolCallBlock:@@ -71,10 +77,16 @@ class ToolCallBlock:name: strarguments: Mapping[str, Any] = field(default_factory=dict)native_id: Optional[str] = None+ signature: Optional[str] = None+ """Opaque provider payload on the call itself (Gemini ``thoughtSignature``); same rules as a thinking signature."""def __post_init__(self) -> None:if not self.id or not self.name:raise ValueError("a tool call needs an id and a name")+ if self.native_id is not None and not self.native_id:+ raise ValueError("a native id, when present, must not be empty")+ if self.signature is not None and not self.signature:+ raise ValueError("a signature, when present, must not be empty")UserContent = Union[TextBlock, ImageBlock]@@ -104,6 +116,11 @@ class Usage:cache_write_tokens: int = 0reasoning_tokens: Optional[int] = None+ def __post_init__(self) -> None:+ counts = (self.input_tokens, self.output_tokens, self.cache_read_tokens, self.cache_write_tokens)+ if any(c < 0 for c in counts) or (self.reasoning_tokens is not None and self.reasoning_tokens < 0):+ raise ValueError("token counts must not be negative")+@dataclass(frozen=True)class UserMessage:@@ -127,6 +144,8 @@ class AssistantMessage:error_message: Optional[str] = Nonedef __post_init__(self) -> None:+ if self.error_message is not None and not self.error_message:+ raise ValueError("an error message, when present, must not be empty")if self.stop_reason not in STOP_REASONS:raise ValueError(f"unknown stop reason: {self.stop_reason}")@@ -146,6 +165,10 @@ class ToolResultMessage:content: tuple[UserContent, ...]is_error: bool = False+ def __post_init__(self) -> None:+ if not self.tool_call_id or not self.tool_name:+ raise ValueError("a tool result needs its call id and tool name")+@propertydef role(self) -> Literal["tool_result"]:return "tool_result"@@ -159,32 +182,39 @@ def text(value: str) -> TextBlock:# --- persisted form ---------------------------------------------------------+#+# Two owners, so no field can be checked differently from another:+# * the dataclasses above own value invariants (non-empty ids, non-negative+# counts, enumerations, the large-reference pattern);+# * ``_read`` owns the wire shape of every object: it must be a JSON object,+# unknown keys are refused, required keys must be present, an optional key is+# either absent or holds a value (an explicit null is refused, because the+# writer never produces one), and every value has exactly its JSON type.-def _strict(data: Any, allowed: set[str], what: str) -> None:+def _read(data: Any, what: str, required: Mapping[str, type], optional: Mapping[str, type] = {}) -> dict[str, Any]:if not isinstance(data, Mapping):raise ValueError(f"{what} must be an object")- unknown = set(data) - allowed+ unknown = set(data) - set(required) - set(optional)if unknown:raise ValueError(f"unknown {what} field(s): {', '.join(sorted(unknown))}")+ out: dict[str, Any] = {}+ for name, kind in {**required, **optional}.items():+ if name not in data:+ if name in required:+ raise ValueError(f"{what} needs {name}")+ continue+ value = data[name]+ # bool is an int subclass in Python; a JSON boolean is never accepted as a number.+ if value is None or not isinstance(value, kind) or (isinstance(value, bool) and kind is not bool):+ raise ValueError(f"{what}.{name} must be {kind.__name__}")+ out[name] = value+ return out-def _typed(value: Any, kind: type, what: str, *, optional: bool = False) -> Any:- """Return ``value`` if it has exactly the JSON type ``kind``; never coerce."""- if value is None and optional:- return None- # bool is an int subclass in Python; a JSON boolean is never an integer here.- if isinstance(value, bool) and kind is not bool:- raise ValueError(f"{what} must be {kind.__name__}")- if not isinstance(value, kind):- raise ValueError(f"{what} must be {kind.__name__}")- return value---def _list(value: Any, what: str) -> list:- if not isinstance(value, list):- raise ValueError(f"{what} must be an array")- return value+def _put(out: dict[str, Any], name: str, value: Any) -> None:+ if value is not None:+ out[name] = valuedef _block_to_dict(block: Any) -> dict[str, Any]:@@ -194,94 +224,67 @@ def _block_to_dict(block: Any) -> dict[str, Any]:return {"type": "text", "text": block.text}if isinstance(block, ImageBlock):out: dict[str, Any] = {"type": "image", "mime_type": block.mime_type, "media_token": block.media_token}- if block.name is not None:- out["name"] = block.name+ _put(out, "name", block.name)return outif isinstance(block, ThinkingBlock):out = {"type": "thinking", "text": block.text}- if block.signature is not None:- out["signature"] = block.signature+ _put(out, "signature", block.signature)if block.redacted:out["redacted"] = Truereturn outif isinstance(block, ToolCallBlock):out = {"type": "tool_call", "id": block.id, "name": block.name, "arguments": dict(block.arguments)}- if block.native_id is not None:- out["native_id"] = block.native_id+ _put(out, "native_id", block.native_id)+ _put(out, "signature", block.signature)return outraise TypeError(f"not a content block: {type(block).__name__}")def _block_from_dict(data: Any, allowed_types: tuple[str, ...]) -> Any:- if not isinstance(data, Mapping):- raise ValueError("a content block must be an object")- kind = data.get("type")+ 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")if kind == "text":- _strict(data, {"type", "text", "ref"}, "text block")- ref = data.get("ref")- if ref is not None:- _strict(ref, {"ref", "bytes"}, "large-content reference")- ref = LargeRef(ref=_typed(ref.get("ref"), str, "ref.ref"), bytes=_typed(ref.get("bytes"), int, "ref.bytes"))- return TextBlock(text=_typed(data.get("text"), str, "text", optional=True), ref=ref)+ f = _read(data, "text block", {"type": str}, {"text": str, "ref": dict})+ ref = None+ if "ref" in f:+ r = _read(f["ref"], "large-content reference", {"ref": str, "bytes": int})+ ref = LargeRef(ref=r["ref"], bytes=r["bytes"])+ return TextBlock(text=f.get("text"), ref=ref)if kind == "image":- _strict(data, {"type", "mime_type", "media_token", "name"}, "image block")- return ImageBlock(- mime_type=_typed(data.get("mime_type"), str, "mime_type"),- media_token=_typed(data.get("media_token"), str, "media_token"),- name=_typed(data.get("name"), str, "name", optional=True),- )+ f = _read(data, "image block", {"type": str, "mime_type": str, "media_token": str}, {"name": str})+ return ImageBlock(mime_type=f["mime_type"], media_token=f["media_token"], name=f.get("name"))if kind == "thinking":- _strict(data, {"type", "text", "signature", "redacted"}, "thinking block")- return ThinkingBlock(- text=_typed(data.get("text"), str, "thinking text"),- signature=_typed(data.get("signature"), str, "signature", optional=True),- redacted=_typed(data.get("redacted", False), bool, "redacted"),- )- _strict(data, {"type", "id", "name", "arguments", "native_id"}, "tool call block")+ f = _read(data, "thinking block", {"type": str, "text": str}, {"signature": str, "redacted": bool})+ if f.get("redacted") is False:+ raise ValueError("thinking block.redacted is written only when true")+ return ThinkingBlock(text=f["text"], signature=f.get("signature"), redacted=bool(f.get("redacted")))+ f = _read(+ data,+ "tool call block",+ {"type": str, "id": str, "name": str, "arguments": dict},+ {"native_id": str, "signature": str},+ )return ToolCallBlock(- id=_typed(data.get("id"), str, "tool call id"),- name=_typed(data.get("name"), str, "tool name"),- arguments=dict(_typed(data.get("arguments"), dict, "arguments")),- native_id=_typed(data.get("native_id"), str, "native_id", optional=True),+ id=f["id"], name=f["name"], arguments=dict(f["arguments"]), native_id=f.get("native_id"), signature=f.get("signature"))+_USAGE_REQUIRED = {"input_tokens": int, "output_tokens": int, "cache_read_tokens": int, "cache_write_tokens": int}++def _usage_to_dict(usage: Usage) -> dict[str, Any]:- out: dict[str, Any] = {- "input_tokens": usage.input_tokens,- "output_tokens": usage.output_tokens,- "cache_read_tokens": usage.cache_read_tokens,- "cache_write_tokens": usage.cache_write_tokens,- }- if usage.reasoning_tokens is not None:- out["reasoning_tokens"] = usage.reasoning_tokens+ out: dict[str, Any] = {name: getattr(usage, name) for name in _USAGE_REQUIRED}+ _put(out, "reasoning_tokens", usage.reasoning_tokens)return outdef usage_from_dict(data: Any) -> Usage:- _strict(- data,- {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens"},- "usage",- )- return Usage(- input_tokens=_typed(data.get("input_tokens"), int, "input_tokens"),- output_tokens=_typed(data.get("output_tokens"), int, "output_tokens"),- cache_read_tokens=_typed(data.get("cache_read_tokens"), int, "cache_read_tokens"),- cache_write_tokens=_typed(data.get("cache_write_tokens"), int, "cache_write_tokens"),- reasoning_tokens=_typed(data.get("reasoning_tokens"), int, "reasoning_tokens", optional=True),- )+ return Usage(**_read(data, "usage", _USAGE_REQUIRED, {"reasoning_tokens": int}))def origin_from_dict(data: Any) -> Origin:- _strict(data, {"provider", "api", "model"}, "origin")- return Origin(- provider=_typed(data.get("provider"), str, "origin.provider"),- api=_typed(data.get("api"), str, "origin.api"),- model=_typed(data.get("model"), str, "origin.model"),- )+ return Origin(**_read(data, "origin", {"provider": str, "api": str, "model": str}))def message_to_dict(message: Message) -> dict[str, Any]:@@ -296,8 +299,7 @@ def message_to_dict(message: Message) -> dict[str, Any]:}if message.usage is not None:out["usage"] = _usage_to_dict(message.usage)- if message.error_message is not None:- out["error_message"] = message.error_message+ _put(out, "error_message", message.error_message)return outif isinstance(message, ToolResultMessage):return {@@ -311,32 +313,34 @@ def message_to_dict(message: Message) -> dict[str, Any]:def message_from_dict(data: Mapping[str, Any]) -> Message:- if not isinstance(data, Mapping):- raise ValueError("a message must be an object")- role = data.get("role")+ role = data.get("role") if isinstance(data, Mapping) else Noneif role == "user":- _strict(data, {"role", "content"}, "user message")- return UserMessage(- content=tuple(_block_from_dict(b, ("text", "image")) for b in _list(data.get("content"), "content"))- )+ f = _read(data, "user message", {"role": str, "content": list})+ return UserMessage(content=tuple(_block_from_dict(b, ("text", "image")) for b in f["content"]))if role == "assistant":- _strict(data, {"role", "content", "origin", "usage", "stop_reason", "error_message"}, "assistant message")- usage = data.get("usage")+ f = _read(+ data,+ "assistant message",+ {"role": str, "content": list, "origin": dict, "stop_reason": str},+ {"usage": dict, "error_message": str},+ )return AssistantMessage(- content=tuple(- _block_from_dict(b, ("text", "thinking", "tool_call")) for b in _list(data.get("content"), "content")- ),- origin=origin_from_dict(data.get("origin")),- stop_reason=_typed(data.get("stop_reason"), str, "stop_reason"),- usage=usage_from_dict(usage) if usage is not None else None,- error_message=_typed(data.get("error_message"), str, "error_message", optional=True),+ content=tuple(_block_from_dict(b, ("text", "thinking", "tool_call")) for b in f["content"]),+ origin=origin_from_dict(f["origin"]),+ stop_reason=f["stop_reason"],+ usage=usage_from_dict(f["usage"]) if "usage" in f else None,+ error_message=f.get("error_message"),)if role == "tool_result":- _strict(data, {"role", "tool_call_id", "tool_name", "content", "is_error"}, "tool result message")+ f = _read(+ data,+ "tool result message",+ {"role": str, "tool_call_id": str, "tool_name": str, "content": list, "is_error": bool},+ )return ToolResultMessage(- tool_call_id=_typed(data.get("tool_call_id"), str, "tool_call_id"),- tool_name=_typed(data.get("tool_name"), str, "tool_name"),- content=tuple(_block_from_dict(b, ("text", "image")) for b in _list(data.get("content"), "content")),- is_error=_typed(data.get("is_error"), bool, "is_error"),+ tool_call_id=f["tool_call_id"],+ tool_name=f["tool_name"],+ content=tuple(_block_from_dict(b, ("text", "image")) for b in f["content"]),+ is_error=f["is_error"],)raise ValueError(f"unknown message role: {role!r}")diff --git a/core/agent_core/tools/base.py b/core/agent_core/tools/base.pyindex 02fb26fc8..d17c23a73 100644--- a/core/agent_core/tools/base.py+++ b/core/agent_core/tools/base.py@@ -80,7 +80,13 @@ class JobHost(Protocol):def status(self, job_id: str) -> JobStatus: ...- async def wait(self, job_id: str, *, deadline_s: Optional[float]) -> JobStatus: ...+ async def wait(self, job_id: str, *, deadline_s: Optional[float]) -> JobStatus:+ """Wait until exit, or at most ``deadline_s`` seconds from now (``None``: until exit)."""+ ...++ def output_path(self, job_id: str) -> str:+ """Absolute path of the job's full output (``output.log``), named in truncated and handover results."""+ ...def output(self, job_id: str, since: int = 0) -> tuple[bytes, int]:"""Raw output bytes after ``since`` and the new offset; callers normalize."""diff --git a/tests/agent_core/test_messages.py b/tests/agent_core/test_messages.pyindex 4adaa44bc..010058588 100644--- a/tests/agent_core/test_messages.py+++ b/tests/agent_core/test_messages.py@@ -49,6 +49,12 @@ REDACTED = {}+GEMINI_CALL = {+ "role": "assistant",+ "content": [{"type": "tool_call", "id": "call_1", "name": "read", "arguments": {"path": "a.py"}, "signature": "CiQB"}],+ "origin": {"provider": "google", "api": "google", "model": "gemini-3-pro"},+ "stop_reason": "tool_use",+}UNSIGNED = {"role": "assistant","content": [{"type": "thinking", "text": "Summary only."}, {"type": "text", "text": "done"}],@@ -57,7 +63,7 @@ UNSIGNED = {}[email protected]("payload", [ASSISTANT, TOOL_RESULT, USER_WITH_REF, REDACTED, UNSIGNED])[email protected]("payload", [ASSISTANT, TOOL_RESULT, USER_WITH_REF, REDACTED, UNSIGNED, GEMINI_CALL])def test_persisted_shape_round_trips_exactly(payload):assert message_to_dict(message_from_dict(payload)) == payload@@ -86,11 +92,23 @@ def test_assistant_message_exposes_tool_calls_in_order():{**ASSISTANT, "content": [{"type": "tool_call", "id": "t", "name": "bash", "arguments": "[]"}]},{**ASSISTANT, "content": [{"type": "text", "text": 5}]},{**ASSISTANT, "content": "text"},+ {**UNSIGNED, "content": [{"type": "thinking", "text": "x", "signature": None}]},+ {**TOOL_RESULT, "content": [{"type": "image", "mime_type": "image/png", "media_token": "t", "name": None}]},+ {**REDACTED, "error_message": None},+ {**ASSISTANT, "usage": None},+ {**UNSIGNED, "content": [{"type": "thinking", "text": "x", "redacted": False}]},+ {"role": "user", "content": [{"type": "text", "ref": {"ref": "sha256:" + "a" * 64 + "\n", "bytes": 1}}]},+ {**TOOL_RESULT, "tool_call_id": ""},+ {**TOOL_RESULT, "tool_name": ""},+ {**ASSISTANT, "usage": {**ASSISTANT["usage"], "cache_read_tokens": -1}},+ {**ASSISTANT, "content": [{"type": "tool_call", "id": "t", "name": "bash", "arguments": {}, "signature": ""}]},],ids=["unknown-field", "unknown-block-field", "block-not-allowed", "stop-reason", "protocol", "role","unknown-ref-field", "string-flag", "integer-flag", "string-redacted", "string-count", "boolean-count",- "string-arguments", "number-text", "content-not-list",+ "string-arguments", "number-text", "content-not-list", "null-signature", "null-name", "null-error",+ "null-usage", "explicit-not-redacted", "digest-newline", "empty-call-id", "empty-tool-name", "negative-count",+ "empty-call-signature",],)def test_reader_refuses_shapes_it_does_not_know(payload):