Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(agent-core): typed interfaces for the Avibe Agent engine

cyhc6796be44cea
diff --git a/core/agent_core/__init__.py b/core/agent_core/__init__.py
new file mode 100644
index 000000000..df3a8068c
--- /dev/null
+++ b/core/agent_core/__init__.py
@@ -0,0 +1,8 @@
+"""The Avibe Agent engine (``docs/plans/avibe-agent-core.md``).
+
+Layers: ``ai`` (provider adapters), ``agent`` (loop), ``harness`` (transcript and
+context management), ``tools`` (coding tools). This package knows nothing about
+IM platforms, the controller, Watch, or Model Hub's HTTP surface; the backend
+adapter in ``modules/agents/avibe/`` supplies those through the interfaces here.
+Shapes follow ``docs/plans/agent-core-contracts/``.
+"""
diff --git a/core/agent_core/agent/__init__.py b/core/agent_core/agent/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/agent_core/agent/events.py b/core/agent_core/agent/events.py
new file mode 100644
index 000000000..54320578a
--- /dev/null
+++ b/core/agent_core/agent/events.py
@@ -0,0 +1,135 @@
+"""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).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal, Optional, Union
+
+RunEndReason = Literal["completed", "aborted", "error", "ended_by_hook", "context_exhausted"]
+CompactionReason = Literal["manual", "threshold", "overflow"]
+
+
+@dataclass(frozen=True)
+class RunStarted:
+ run_id: str
+ seq: int
+
+
+@dataclass(frozen=True)
+class AssistantTextDelta:
+ run_id: str
+ seq: int
+ delta: str
+
+
+@dataclass(frozen=True)
+class AssistantThinkingDelta:
+ run_id: str
+ seq: int
+ delta: str
+
+
+@dataclass(frozen=True)
+class MessageCommitted:
+ run_id: str
+ seq: int
+ message_id: str
+ context_seq: int
+ final: bool
+
+
+@dataclass(frozen=True)
+class ToolStarted:
+ run_id: str
+ seq: int
+ tool_call_id: str
+ name: str
+ preview: str
+ job_id: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class ToolProgress:
+ run_id: str
+ seq: int
+ tool_call_id: str
+ tail: str
+
+
+@dataclass(frozen=True)
+class ToolFinished:
+ run_id: str
+ seq: int
+ tool_call_id: str
+ event_id: str
+ is_error: bool
+ watch_id: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class SteerApplied:
+ run_id: str
+ seq: int
+ message_id: str
+
+
+@dataclass(frozen=True)
+class CompactionStarted:
+ run_id: str
+ seq: int
+ reason: CompactionReason
+
+
+@dataclass(frozen=True)
+class CompactionFinished:
+ run_id: str
+ seq: int
+ event_id: str
+ reason: CompactionReason
+ tokens_before: int
+ tokens_after_estimate: int
+
+
+@dataclass(frozen=True)
+class CompactionFailed:
+ run_id: str
+ seq: int
+ reason: CompactionReason
+ error: str
+
+
+@dataclass(frozen=True)
+class RunEnded:
+ run_id: str
+ seq: int
+ reason: RunEndReason
+
+
+@dataclass(frozen=True)
+class AgentError:
+ run_id: str
+ seq: int
+ kind: str
+ message: str
+
+
+AgentEvent = Union[
+ RunStarted,
+ AssistantTextDelta,
+ AssistantThinkingDelta,
+ MessageCommitted,
+ ToolStarted,
+ ToolProgress,
+ ToolFinished,
+ SteerApplied,
+ CompactionStarted,
+ CompactionFinished,
+ CompactionFailed,
+ RunEnded,
+ AgentError,
+]
diff --git a/core/agent_core/ai/__init__.py b/core/agent_core/ai/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.py
new file mode 100644
index 000000000..e6584ec74
--- /dev/null
+++ b/core/agent_core/ai/provider.py
@@ -0,0 +1,96 @@
+"""C-2 provider adapter interface (``agent-core-contracts/provider.md``).
+
+One adapter per wire protocol. An adapter speaks HTTP to the endpoint it is
+given, converts canonical messages with the cross-provider rules, and yields
+``ProviderEvent``s ending in exactly one ``Done`` or ``ProviderError``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import AsyncIterator, Literal, Mapping, Optional, Protocol, Union
+
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import AssistantMessage, Message, ProtocolName
+from core.agent_core.tools.base import ToolSpec
+
+ErrorKind = Literal[
+ "overflow", "rate_limit", "overloaded", "network", "server", "auth", "invalid_request", "aborted", "unknown"
+]
+RETRYABLE_ERROR_KINDS: frozenset[str] = frozenset({"rate_limit", "overloaded", "network", "server"})
+
+
+@dataclass(frozen=True)
+class ModelEndpoint:
+ protocol: ProtocolName
+ base_url: str
+ model_id: str
+ token: str = field(repr=False)
+ request_headers: Mapping[str, str] = field(default_factory=dict)
+ provider: str = ""
+
+
+@dataclass(frozen=True)
+class ModelRequest:
+ endpoint: ModelEndpoint
+ system: str
+ messages: tuple[Message, ...]
+ tools: tuple[ToolSpec, ...]
+ max_tokens: int
+ reasoning_effort: Optional[str] = None
+ cache: Literal["default", "none"] = "default"
+ supports_images: bool = True
+
+
+@dataclass(frozen=True)
+class TextDelta:
+ index: int
+ delta: str
+
+
+@dataclass(frozen=True)
+class ThinkingDelta:
+ index: int
+ delta: str
+
+
+@dataclass(frozen=True)
+class ToolCallStart:
+ index: int
+ id: str
+ name: str
+
+
+@dataclass(frozen=True)
+class ToolCallDelta:
+ index: int
+ arguments_delta: str
+
+
+@dataclass(frozen=True)
+class BlockEnd:
+ index: int
+
+
+@dataclass(frozen=True)
+class Done:
+ message: AssistantMessage
+
+
+@dataclass(frozen=True)
+class ProviderError:
+ kind: ErrorKind
+ message: str
+ retryable: bool
+ retry_after_s: Optional[float] = None
+ status: Optional[int] = None
+ partial: Optional[AssistantMessage] = None
+
+
+ProviderEvent = Union[TextDelta, ThinkingDelta, ToolCallStart, ToolCallDelta, BlockEnd, Done, ProviderError]
+
+
+class ProviderAdapter(Protocol):
+ protocol: ProtocolName
+
+ def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[ProviderEvent]: ...
diff --git a/core/agent_core/cancel.py b/core/agent_core/cancel.py
new file mode 100644
index 000000000..5979f79bc
--- /dev/null
+++ b/core/agent_core/cancel.py
@@ -0,0 +1,30 @@
+"""Cancellation shared by provider streams, the loop, and tools."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Optional
+
+
+class CancelToken:
+ """A one-way cancellation flag that async code can poll or await."""
+
+ def __init__(self) -> None:
+ self._event = asyncio.Event()
+ self._reason: Optional[str] = None
+
+ @property
+ def cancelled(self) -> bool:
+ return self._event.is_set()
+
+ @property
+ def reason(self) -> Optional[str]:
+ return self._reason
+
+ def cancel(self, reason: str = "aborted") -> None:
+ if not self._event.is_set():
+ self._reason = reason
+ self._event.set()
+
+ async def wait(self) -> None:
+ await self._event.wait()
diff --git a/core/agent_core/harness/__init__.py b/core/agent_core/harness/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/agent_core/harness/store.py b/core/agent_core/harness/store.py
new file mode 100644
index 000000000..d02ec5b74
--- /dev/null
+++ b/core/agent_core/harness/store.py
@@ -0,0 +1,52 @@
+"""C-5 transcript store interface (``agent-core-contracts/transcript.md``).
+
+The loop is the single writer of a Session's context. Each method commits one
+context entry and returns it with its ``context_seq``; the adapter implements
+this over the ``messages`` and ``agent_events`` tables.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Literal, Mapping, Optional, Protocol, Sequence
+
+from core.agent_core.messages import AssistantMessage, Message, ToolResultMessage, UserMessage
+
+EntryKind = Literal["input", "response", "tool_result", "compaction", "context_edit", "agent_state"]
+
+
+@dataclass(frozen=True)
+class ContextEntry:
+ """One committed context row.
+
+ ``row_id`` is ``messages.id`` for inputs and responses, ``agent_events.id``
+ otherwise. ``message`` is set for inputs, responses, and tool results;
+ ``payload`` carries the versioned shape of the other kinds.
+ """
+
+ session_id: str
+ context_seq: int
+ kind: EntryKind
+ row_id: str
+ message: Optional[Message] = None
+ payload: Mapping[str, Any] = field(default_factory=dict)
+
+
+class TranscriptStore(Protocol):
+ async def load(self, session_id: str) -> Sequence[ContextEntry]:
+ """Context entries of the Session and its fork ancestry, ordered by ``context_seq``."""
+ ...
+
+ async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:
+ """Admit an already stored input row into the context as rendered for the model."""
+ ...
+
+ async def append_response(self, session_id: str, message: AssistantMessage, *, final: bool) -> ContextEntry: ...
+
+ async def append_tool_result(
+ self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]
+ ) -> ContextEntry: ...
+
+ async def append_payload(
+ self, session_id: str, kind: Literal["compaction", "context_edit", "agent_state"], payload: Mapping[str, Any]
+ ) -> ContextEntry: ...
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
new file mode 100644
index 000000000..f7db67b5a
--- /dev/null
+++ b/core/agent_core/messages.py
@@ -0,0 +1,299 @@
+"""C-1 canonical message model (``agent-core-contracts/message.schema.json``).
+
+Vendor-neutral messages exchanged by the provider adapters, the loop, and the
+transcript store. ``message_to_dict`` / ``message_from_dict`` produce and read
+the persisted form stored in ``messages.content_json.model`` and in tool-result
+rows, so the field names here are a shipped surface.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any, Literal, Mapping, Optional, Union
+
+ProtocolName = Literal["anthropic", "openai_chat", "openai_responses", "google"]
+PROTOCOLS: tuple[str, ...] = ("anthropic", "openai_chat", "openai_responses", "google")
+
+StopReason = Literal["stop", "length", "tool_use", "refusal", "safety", "aborted", "error"]
+STOP_REASONS: tuple[str, ...] = ("stop", "length", "tool_use", "refusal", "safety", "aborted", "error")
+
+IMAGE_MIME_TYPES: tuple[str, ...] = ("image/png", "image/jpeg", "image/gif", "image/webp")
+
+_LARGE_REF_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
+
+
+@dataclass(frozen=True)
+class LargeRef:
+ """Reserved reference to content stored outside the row; v1 never writes it."""
+
+ ref: str
+ bytes: int
+
+ def __post_init__(self) -> None:
+ if not _LARGE_REF_RE.match(self.ref) or self.bytes < 0:
+ raise ValueError(f"invalid large-content reference: {self.ref!r}")
+
+
+@dataclass(frozen=True)
+class TextBlock:
+ text: Optional[str] = None
+ ref: Optional[LargeRef] = None
+
+ def __post_init__(self) -> None:
+ if (self.text is None) == (self.ref is None):
+ raise ValueError("a text block holds exactly one of text or ref")
+
+
+@dataclass(frozen=True)
+class ImageBlock:
+ mime_type: str
+ media_token: str
+ name: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if self.mime_type not in IMAGE_MIME_TYPES:
+ raise ValueError(f"unsupported image type: {self.mime_type}")
+ if not self.media_token:
+ raise ValueError("an image block needs a media token")
+
+
+@dataclass(frozen=True)
+class ThinkingBlock:
+ text: str
+ signature: Optional[str] = None
+ redacted: bool = False
+
+
+@dataclass(frozen=True)
+class ToolCallBlock:
+ id: str
+ name: str
+ arguments: Mapping[str, Any] = field(default_factory=dict)
+ native_id: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if not self.id or not self.name:
+ raise ValueError("a tool call needs an id and a name")
+
+
+UserContent = Union[TextBlock, ImageBlock]
+AssistantContent = Union[TextBlock, ThinkingBlock, ToolCallBlock]
+
+
+@dataclass(frozen=True)
+class Origin:
+ """Who served an assistant message; equal only when all three fields are equal."""
+
+ provider: str
+ api: str
+ model: str
+
+ def __post_init__(self) -> None:
+ if not self.provider or not self.model:
+ raise ValueError("an origin needs a provider and a model")
+ if self.api not in PROTOCOLS:
+ raise ValueError(f"unknown protocol: {self.api}")
+
+
+@dataclass(frozen=True)
+class Usage:
+ input_tokens: int = 0
+ output_tokens: int = 0
+ cache_read_tokens: int = 0
+ cache_write_tokens: int = 0
+ reasoning_tokens: Optional[int] = None
+
+
+@dataclass(frozen=True)
+class UserMessage:
+ content: tuple[UserContent, ...]
+
+ def __post_init__(self) -> None:
+ if not self.content:
+ raise ValueError("a user message needs content")
+
+ @property
+ def role(self) -> Literal["user"]:
+ return "user"
+
+
+@dataclass(frozen=True)
+class AssistantMessage:
+ content: tuple[AssistantContent, ...]
+ origin: Origin
+ stop_reason: StopReason
+ usage: Optional[Usage] = None
+ error_message: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if self.stop_reason not in STOP_REASONS:
+ raise ValueError(f"unknown stop reason: {self.stop_reason}")
+
+ @property
+ def role(self) -> Literal["assistant"]:
+ return "assistant"
+
+ @property
+ def tool_calls(self) -> tuple[ToolCallBlock, ...]:
+ return tuple(block for block in self.content if isinstance(block, ToolCallBlock))
+
+
+@dataclass(frozen=True)
+class ToolResultMessage:
+ tool_call_id: str
+ tool_name: str
+ content: tuple[UserContent, ...]
+ is_error: bool = False
+
+ @property
+ def role(self) -> Literal["tool_result"]:
+ return "tool_result"
+
+
+Message = Union[UserMessage, AssistantMessage, ToolResultMessage]
+
+
+def text(value: str) -> TextBlock:
+ return TextBlock(text=value)
+
+
+# --- persisted form ---------------------------------------------------------
+
+
+def _strict(data: Mapping[str, Any], allowed: set[str], what: str) -> None:
+ unknown = set(data) - allowed
+ if unknown:
+ raise ValueError(f"unknown {what} field(s): {', '.join(sorted(unknown))}")
+
+
+def _block_to_dict(block: Any) -> dict[str, Any]:
+ if isinstance(block, TextBlock):
+ if block.ref is not None:
+ return {"type": "text", "ref": {"ref": block.ref.ref, "bytes": block.ref.bytes}}
+ 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
+ return out
+ if isinstance(block, ThinkingBlock):
+ out = {"type": "thinking", "text": block.text, "signature": block.signature}
+ if block.redacted:
+ out["redacted"] = True
+ return out
+ if 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
+ return out
+ raise TypeError(f"not a content block: {type(block).__name__}")
+
+
+def _block_from_dict(data: Mapping[str, Any], allowed_types: tuple[str, ...]) -> Any:
+ kind = data.get("type")
+ if 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")
+ return TextBlock(
+ text=data.get("text"),
+ ref=LargeRef(ref=ref["ref"], bytes=ref["bytes"]) if ref is not None else None,
+ )
+ if kind == "image":
+ _strict(data, {"type", "mime_type", "media_token", "name"}, "image block")
+ return ImageBlock(mime_type=data["mime_type"], media_token=data["media_token"], name=data.get("name"))
+ if kind == "thinking":
+ _strict(data, {"type", "text", "signature", "redacted"}, "thinking block")
+ return ThinkingBlock(
+ text=data["text"], signature=data.get("signature"), redacted=bool(data.get("redacted", False))
+ )
+ _strict(data, {"type", "id", "name", "arguments", "native_id"}, "tool call block")
+ return ToolCallBlock(
+ id=data["id"], name=data["name"], arguments=dict(data["arguments"]), native_id=data.get("native_id")
+ )
+
+
+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
+ return out
+
+
+def usage_from_dict(data: Mapping[str, Any]) -> Usage:
+ _strict(
+ data,
+ {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens"},
+ "usage",
+ )
+ return Usage(
+ input_tokens=data["input_tokens"],
+ output_tokens=data["output_tokens"],
+ cache_read_tokens=data["cache_read_tokens"],
+ cache_write_tokens=data["cache_write_tokens"],
+ reasoning_tokens=data.get("reasoning_tokens"),
+ )
+
+
+def origin_from_dict(data: Mapping[str, Any]) -> Origin:
+ _strict(data, {"provider", "api", "model"}, "origin")
+ return Origin(provider=data["provider"], api=data["api"], model=data["model"])
+
+
+def message_to_dict(message: Message) -> dict[str, Any]:
+ if isinstance(message, UserMessage):
+ return {"role": "user", "content": [_block_to_dict(b) for b in message.content]}
+ if isinstance(message, AssistantMessage):
+ out: dict[str, Any] = {
+ "role": "assistant",
+ "content": [_block_to_dict(b) for b in message.content],
+ "origin": {"provider": message.origin.provider, "api": message.origin.api, "model": message.origin.model},
+ "stop_reason": message.stop_reason,
+ }
+ 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
+ return out
+ if isinstance(message, ToolResultMessage):
+ return {
+ "role": "tool_result",
+ "tool_call_id": message.tool_call_id,
+ "tool_name": message.tool_name,
+ "content": [_block_to_dict(b) for b in message.content],
+ "is_error": message.is_error,
+ }
+ raise TypeError(f"not a message: {type(message).__name__}")
+
+
+def message_from_dict(data: Mapping[str, Any]) -> Message:
+ role = data.get("role")
+ if role == "user":
+ _strict(data, {"role", "content"}, "user message")
+ return UserMessage(content=tuple(_block_from_dict(b, ("text", "image")) for b in data["content"]))
+ if role == "assistant":
+ _strict(data, {"role", "content", "origin", "usage", "stop_reason", "error_message"}, "assistant message")
+ usage = data.get("usage")
+ return AssistantMessage(
+ content=tuple(_block_from_dict(b, ("text", "thinking", "tool_call")) for b in data["content"]),
+ origin=origin_from_dict(data["origin"]),
+ stop_reason=data["stop_reason"],
+ usage=usage_from_dict(usage) if usage is not None else None,
+ error_message=data.get("error_message"),
+ )
+ if role == "tool_result":
+ _strict(data, {"role", "tool_call_id", "tool_name", "content", "is_error"}, "tool result message")
+ return ToolResultMessage(
+ tool_call_id=data["tool_call_id"],
+ tool_name=data["tool_name"],
+ content=tuple(_block_from_dict(b, ("text", "image")) for b in data["content"]),
+ is_error=bool(data["is_error"]),
+ )
+ raise ValueError(f"unknown message role: {role!r}")
diff --git a/core/agent_core/tools/__init__.py b/core/agent_core/tools/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/agent_core/tools/base.py b/core/agent_core/tools/base.py
new file mode 100644
index 000000000..02fb26fc8
--- /dev/null
+++ b/core/agent_core/tools/base.py
@@ -0,0 +1,93 @@
+"""C-7 tool interface and job handle (``agent-core-contracts/tools.md``).
+
+``Tool`` is what the loop executes; ``JobHost`` is how ``bash`` runs commands
+through a portable handle so a running command can be handed to Watch without
+restarting it. The adapter supplies the Watch-backed ``JobHost``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Callable, Literal, Mapping, Optional, Protocol
+
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import UserContent
+
+MAX_LINES = 2000
+MAX_BYTES = 50 * 1024
+
+
+@dataclass(frozen=True)
+class ToolSpec:
+ """What the model sees: the name, description, and JSON Schema of the parameters."""
+
+ name: str
+ description: str
+ input_schema: Mapping[str, Any]
+
+
+@dataclass(frozen=True)
+class ToolContext:
+ session_id: str
+ tool_call_id: str
+ cwd: str
+ env: Mapping[str, str]
+ cancel: CancelToken
+ on_progress: Optional[Callable[[str], None]] = None
+
+
+@dataclass(frozen=True)
+class ToolResult:
+ """``content`` is exactly what the model sees; ``details`` is for display and the transcript only."""
+
+ content: tuple[UserContent, ...]
+ is_error: bool = False
+ details: Mapping[str, Any] = field(default_factory=dict)
+ terminate: bool = False
+
+
+class Tool(Protocol):
+ @property
+ def spec(self) -> ToolSpec: ...
+
+ async def execute(self, arguments: Mapping[str, Any], ctx: ToolContext) -> ToolResult: ...
+
+
+JobState = Literal["running", "exited", "gone"]
+
+
+@dataclass(frozen=True)
+class JobStatus:
+ """``exited`` carries the exit code; ``gone`` means the job ended without writing one."""
+
+ state: JobState
+ exit_code: Optional[int] = None
+
+
+class JobHost(Protocol):
+ """Portable command handles (tools.md section 7). The v1 backend is ``pipe``."""
+
+ async def start(
+ self,
+ command: str,
+ *,
+ cwd: str,
+ env: Mapping[str, str],
+ timeout_s: Optional[float],
+ session_id: str,
+ tool_call_id: str,
+ ) -> str: ...
+
+ def status(self, job_id: str) -> JobStatus: ...
+
+ async def wait(self, job_id: str, *, deadline_s: Optional[float]) -> JobStatus: ...
+
+ def output(self, job_id: str, since: int = 0) -> tuple[bytes, int]:
+ """Raw output bytes after ``since`` and the new offset; callers normalize."""
+ ...
+
+ async def kill(self, job_id: str) -> None: ...
+
+ async def hand_over(self, job_id: str) -> str:
+ """Give the running job to a once Watch and return the Watch id."""
+ ...
diff --git a/tests/agent_core/__init__.py b/tests/agent_core/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/agent_core/test_messages.py b/tests/agent_core/test_messages.py
new file mode 100644
index 000000000..fe694af88
--- /dev/null
+++ b/tests/agent_core/test_messages.py
@@ -0,0 +1,84 @@
+"""C-1 persisted message shape.
+
+Rows written by one release are read by the next, so the dict form must round
+trip exactly and must refuse fields it does not know rather than drop them.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.agent_core.messages import (
+ AssistantMessage,
+ TextBlock,
+ message_from_dict,
+ message_to_dict,
+)
+
+ASSISTANT = {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "text": "The failing test imports a renamed helper.", "signature": "EqQBCkYIBxgCKkD"},
+ {"type": "text", "text": "运行测试看看。"},
+ {"type": "tool_call", "id": "toolu_01AbC", "name": "bash", "arguments": {"command": "pytest -q"}},
+ ],
+ "origin": {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5"},
+ "usage": {"input_tokens": 1834, "output_tokens": 212, "cache_read_tokens": 40210, "cache_write_tokens": 0},
+ "stop_reason": "tool_use",
+}
+TOOL_RESULT = {
+ "role": "tool_result",
+ "tool_call_id": "toolu_01AbC",
+ "tool_name": "read",
+ "content": [
+ {"type": "text", "text": "Read image file [image/png]"},
+ {"type": "image", "mime_type": "image/png", "media_token": "W8YdX9o4", "name": "shot.png"},
+ ],
+ "is_error": False,
+}
+USER_WITH_REF = {
+ "role": "user",
+ "content": [{"type": "text", "ref": {"ref": "sha256:" + "a" * 64, "bytes": 81920}}],
+}
+REDACTED = {
+ "role": "assistant",
+ "content": [{"type": "thinking", "text": "", "signature": "opaque", "redacted": True}],
+ "origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-5.6"},
+ "stop_reason": "error",
+ "error_message": "stream reset",
+}
+
+
[email protected]("payload", [ASSISTANT, TOOL_RESULT, USER_WITH_REF, REDACTED])
+def test_persisted_shape_round_trips_exactly(payload):
+ assert message_to_dict(message_from_dict(payload)) == payload
+
+
+def test_assistant_message_exposes_tool_calls_in_order():
+ message = message_from_dict(ASSISTANT)
+ assert isinstance(message, AssistantMessage)
+ assert [call.id for call in message.tool_calls] == ["toolu_01AbC"]
+
+
+ "payload",
+ [
+ {**ASSISTANT, "cost": 1},
+ {**TOOL_RESULT, "content": [{"type": "text", "text": "x", "lang": "en"}]},
+ {**TOOL_RESULT, "content": [{"type": "thinking", "text": "x"}]},
+ {**ASSISTANT, "stop_reason": "end_turn"},
+ {**ASSISTANT, "origin": {"provider": "anthropic", "api": "anthropic-messages", "model": "m"}},
+ {"role": "system", "content": []},
+ ],
+ ids=["unknown-field", "unknown-block-field", "block-not-allowed", "stop-reason", "protocol", "role"],
+)
+def test_reader_refuses_shapes_it_does_not_know(payload):
+ with pytest.raises(ValueError):
+ message_from_dict(payload)
+
+
+def test_text_block_holds_exactly_one_form():
+ with pytest.raises(ValueError):
+ TextBlock()
+ with pytest.raises(ValueError):
+ message_from_dict({"role": "user", "content": [{"type": "text", "text": "a", "ref": USER_WITH_REF["content"][0]["ref"]}]})