Skip to content

Transcript streaming

octomate_protocol.stream

The transcript stream's wire protocol — what a client-side tail exchanges with the server's stream endpoint when a native session's transcript lives on another machine.

The payload is raw transcript lines plus the byte offsets they occupy in the client's own file. Turn assembly stays server-side. Codex clients additionally recognize explicit visualization references to attach bounded HTML snapshots; raw transcript lines and their offsets are unchanged. The same frames carry a Claude session file or a Codex rollout; the mounting endpoint selects its assembler.

The server is the only cursor authority. A connect opens with hello/welcome: the client claims a session, the server answers where each of its files resumes (recomputed from the committed runs), and the client holds no durable state — a crash anywhere costs a re-stream, never a loss. Lines then flow contiguously per file; finalize (server → client, relaying SessionEnd from the hook pipe) and eof (client → server, "drained, commit the trailing turns") close a session out.

STREAM_PROTOCOL module-attribute

STREAM_PROTOCOL = 3

StreamClientMessage module-attribute

StreamClientMessage = Annotated[
    StreamHello
    | StreamOpenSubagent
    | StreamLine
    | StreamSnapshotStart
    | StreamEof,
    Field(discriminator="type"),
]

StreamServerMessage module-attribute

StreamServerMessage = Annotated[
    StreamWelcome
    | StreamSubagentOpened
    | StreamFinalize
    | StreamSnapshotStored,
    Field(discriminator="type"),
]

client_message_adapter module-attribute

client_message_adapter: TypeAdapter[StreamClientMessage] = (
    TypeAdapter(StreamClientMessage)
)

server_message_adapter module-attribute

server_message_adapter: TypeAdapter[StreamServerMessage] = (
    TypeAdapter(StreamServerMessage)
)

StreamHello pydantic-model

Bases: BaseModel

The client's opening claim: which session it tails, where the transcript lives on the client's machine (a label in the client's namespace — the server never opens it), and the directory the session runs in, which files the session's thread under its project exactly as the http hooks' cwd does.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamHello(BaseModel):
    """The client's opening claim: which session it tails, where the transcript lives
    on the client's machine (a label in the *client's* namespace — the server never
    opens it), and the directory the session runs in, which files the session's thread
    under its project exactly as the http hooks' `cwd` does."""

    type: Literal["hello"] = "hello"
    protocol: int
    session_id: str
    transcript_path: str
    cwd: str = ""
    # The shipping client's own version (the octomate-cli package), logged at attach for
    # skew diagnosis. The Claude Code version is not carried here: it rides every
    # transcript line, which the server parses anyway.
    client_version: str = ""
    catchup_end: NonNegativeInt = Field(
        default=0,
        description="Transcript byte length at connection time; earlier lines restore history.",
    )

type pydantic-field

type: Literal['hello'] = 'hello'

protocol pydantic-field

protocol: int

session_id pydantic-field

session_id: str

transcript_path pydantic-field

transcript_path: str

cwd pydantic-field

cwd: str = ''

client_version pydantic-field

client_version: str = ''

catchup_end pydantic-field

catchup_end: NonNegativeInt = 0

Transcript byte length at connection time; earlier lines restore history.

StreamLine pydantic-model

Bases: BaseModel

One complete transcript line and the byte range it occupies in its file.

start/end are the client file's own offsets, end past the newline the line was framed on — the same range the assembled run's start_offset/end_offset records. Lines arrive contiguously per file, blank ones included (skipping one would read as a gap); the server closes on a gap and the reconnect re-asks where to resume.

Fields:

Validators:

Source code in protocol/octomate_protocol/stream.py
class StreamLine(BaseModel):
    """One complete transcript line and the byte range it occupies in its file.

    `start`/`end` are the client file's own offsets, `end` past the newline the line
    was framed on — the same range the assembled run's `start_offset`/`end_offset`
    records. Lines arrive contiguously per file, blank ones included (skipping one
    would read as a gap); the server closes on a gap and the reconnect re-asks where
    to resume.
    """

    type: Literal["line"] = "line"
    conversation_id: UUID7
    start: int
    end: int
    line: str
    visualizations: list[HtmlSnapshot] = Field(
        default_factory=list,
        description="HTML snapshots explicitly referenced by this Codex assistant line, read on the client.",
    )

    @model_validator(mode="after")
    def snapshots_match_references(self) -> Self:
        if self.visualizations and (
            [snapshot.reference for snapshot in self.visualizations]
            != codex_html_references(self.line)
        ):
            raise ValueError("HTML snapshots must match the root assistant references")
        return self

type pydantic-field

type: Literal['line'] = 'line'

conversation_id pydantic-field

conversation_id: UUID7

start pydantic-field

start: int

end pydantic-field

end: int

line pydantic-field

line: str

visualizations pydantic-field

visualizations: list[HtmlSnapshot]

HTML snapshots explicitly referenced by this Codex assistant line, read on the client.

snapshots_match_references pydantic-validator

snapshots_match_references() -> Self
Source code in protocol/octomate_protocol/stream.py
@model_validator(mode="after")
def snapshots_match_references(self) -> Self:
    if self.visualizations and (
        [snapshot.reference for snapshot in self.visualizations]
        != codex_html_references(self.line)
    ):
        raise ValueError("HTML snapshots must match the root assistant references")
    return self

StreamEof pydantic-model

Bases: BaseModel

The client drained its files to EOF and is done — answering a finalize, or on its own idle give-up. The server commits the trailing turns on this; a connection that drops without it leaves them uncommitted for the next connect to re-stream.

Fields:

  • type (Literal['eof'])
Source code in protocol/octomate_protocol/stream.py
class StreamEof(BaseModel):
    """The client drained its files to EOF and is done — answering a `finalize`, or on
    its own idle give-up. The server commits the trailing turns on this; a connection
    that drops without it leaves them uncommitted for the next connect to re-stream."""

    type: Literal["eof"] = "eof"

type pydantic-field

type: Literal['eof'] = 'eof'

StreamSnapshotCursor pydantic-model

Bases: BaseModel

The durable transcript prefix the client must verify before appending.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamSnapshotCursor(BaseModel):
    """The durable transcript prefix the client must verify before appending."""

    offset: int = Field(ge=0, description="Number of transcript bytes already stored.")
    sha256: str = Field(
        pattern=r"^[0-9a-f]{64}$", description="SHA-256 of that prefix."
    )

offset pydantic-field

offset: int

Number of transcript bytes already stored.

sha256 pydantic-field

sha256: str

SHA-256 of that prefix.

TranscriptOffsets pydantic-model

Bases: BaseModel

Resume positions keyed by Octomate conversation UUID.

Fields:

Source code in protocol/octomate_protocol/stream.py
class TranscriptOffsets(BaseModel):
    """Resume positions keyed by Octomate conversation UUID."""

    offsets: dict[UUID7, NonNegativeInt]
    subagents: dict[UUID7, str] = Field(
        default_factory=dict, description="Local child file identifiers for discovery."
    )

offsets pydantic-field

offsets: dict[UUID7, NonNegativeInt]

subagents pydantic-field

subagents: dict[UUID7, str]

Local child file identifiers for discovery.

StreamWelcome pydantic-model

Bases: TranscriptOffsets

The session's conversation UUID and the resume positions for its files.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamWelcome(TranscriptOffsets):
    """The session's conversation UUID and the resume positions for its files."""

    type: Literal["welcome"] = "welcome"
    conversation_id: UUID7
    transcript: StreamSnapshotCursor | None = Field(
        default=None,
        description="Continuously upload bytes after this verified prefix; None disables upload.",
    )

type pydantic-field

type: Literal['welcome'] = 'welcome'

conversation_id pydantic-field

conversation_id: UUID7

transcript pydantic-field

transcript: StreamSnapshotCursor | None = None

Continuously upload bytes after this verified prefix; None disables upload.

StreamOpenSubagent pydantic-model

Bases: BaseModel

Resolve a newly discovered child before sending its transcript.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamOpenSubagent(BaseModel):
    """Resolve a newly discovered child before sending its transcript."""

    type: Literal["open_subagent"] = "open_subagent"
    name: str = Field(min_length=1)
    first_line: str | None = Field(
        default=None, description="Codex rollout metadata for parent verification."
    )
    catchup_end: NonNegativeInt = Field(
        default=0, description="Child transcript byte length at registration time."
    )
    tool_call_id: str | None = Field(
        default=None,
        description="The parent's call a Claude child answers, from the meta file "
        "beside its transcript. An interrupted call's result names no child.",
    )
    description: str | None = Field(
        default=None,
        description="What the parent called a Claude child's task, from the same file.",
    )

type pydantic-field

type: Literal['open_subagent'] = 'open_subagent'

name pydantic-field

name: str

first_line pydantic-field

first_line: str | None = None

Codex rollout metadata for parent verification.

catchup_end pydantic-field

catchup_end: NonNegativeInt = 0

Child transcript byte length at registration time.

tool_call_id pydantic-field

tool_call_id: str | None = None

The parent's call a Claude child answers, from the meta file beside its transcript. An interrupted call's result names no child.

description pydantic-field

description: str | None = None

What the parent called a Claude child's task, from the same file.

StreamSubagentOpened pydantic-model

Bases: BaseModel

Registration result. A Codex rollout belonging to another session is skipped.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamSubagentOpened(BaseModel):
    """Registration result. A Codex rollout belonging to another session is skipped."""

    type: Literal["subagent_opened"] = "subagent_opened"
    conversation_id: UUID7 | None
    offset: NonNegativeInt

type pydantic-field

type: Literal['subagent_opened'] = 'subagent_opened'

conversation_id pydantic-field

conversation_id: UUID7 | None

offset pydantic-field

offset: NonNegativeInt

StreamSnapshotStart pydantic-model

Bases: BaseModel

Client announces the next transcript range before sending its bytes.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamSnapshotStart(BaseModel):
    """Client announces the next transcript range before sending its bytes."""

    type: Literal["snapshot_start"] = "snapshot_start"
    conversation_id: UUID7
    transfer_id: UUID
    start: int = Field(
        ge=0, description="Exclusive end of the previously stored prefix."
    )
    end: int = Field(
        gt=0, description="Exclusive byte offset at a complete-line boundary."
    )

type pydantic-field

type: Literal['snapshot_start'] = 'snapshot_start'

conversation_id pydantic-field

conversation_id: UUID7

transfer_id pydantic-field

transfer_id: UUID

start pydantic-field

start: int

Exclusive end of the previously stored prefix.

end pydantic-field

end: int

Exclusive byte offset at a complete-line boundary.

StreamSnapshotStored pydantic-model

Bases: BaseModel

Server acknowledgment after the uploaded snapshot is durably stored.

Fields:

Source code in protocol/octomate_protocol/stream.py
class StreamSnapshotStored(BaseModel):
    """Server acknowledgment after the uploaded snapshot is durably stored."""

    type: Literal["snapshot_stored"] = "snapshot_stored"
    transfer_id: UUID

type pydantic-field

type: Literal['snapshot_stored'] = 'snapshot_stored'

transfer_id pydantic-field

transfer_id: UUID

StreamFinalize pydantic-model

Bases: BaseModel

Server → client: the session ended (SessionEnd arrived on the hook pipe) — drain the remaining bytes, answer with eof, and exit.

A snapshot starts with snapshot_start, followed by binary messages totaling end - start bytes. The client waits for snapshot_stored before sending eof. Each batch's transcript lines precede its binary messages; they never interleave. Batches may upload throughout a turn, before finalization.

Fields:

  • type (Literal['finalize'])
Source code in protocol/octomate_protocol/stream.py
class StreamFinalize(BaseModel):
    """Server → client: the session ended (`SessionEnd` arrived on the hook pipe) —
    drain the remaining bytes, answer with `eof`, and exit.

    A snapshot starts with `snapshot_start`, followed by binary messages totaling
    `end - start` bytes. The client waits for `snapshot_stored` before sending `eof`.
    Each batch's transcript lines precede its binary messages; they never interleave.
    Batches may upload throughout a turn, before finalization.
    """

    type: Literal["finalize"] = "finalize"

type pydantic-field

type: Literal['finalize'] = 'finalize'

TranscriptKept pydantic-model

Bases: BaseModel

How much of a driven session's transcript the server holds. It answers an upload: stored, or refused because the bytes did not start where these end.

Fields:

Source code in protocol/octomate_protocol/stream.py
class TranscriptKept(BaseModel):
    """How much of a driven session's transcript the server holds. It answers an
    upload: stored, or refused because the bytes did not start where these end."""

    size: int = Field(ge=0, description="Bytes kept; where the next upload starts.")

size pydantic-field

size: int

Bytes kept; where the next upload starts.

octomate_protocol.visualizations

Explicit Codex HTML references shared by driven capture and native clients.

Files must be regular UTF-8 HTML beneath the session workspace, without symlinks, and at most 1 MB. Native clients send snapshots alongside the original rollout line; the server never opens a path supplied by a remote client.

VISUALIZATION_START module-attribute

VISUALIZATION_START = '\ue200visualize\ue202'

VISUALIZATION_REFERENCE module-attribute

VISUALIZATION_REFERENCE = re.compile(
    "\\ue200visualize\\ue202([^\\ue201]*)\\ue201"
)

rollout_object_adapter module-attribute

rollout_object_adapter = TypeAdapter(dict[str, JsonValue])

HtmlReference pydantic-model

Bases: BaseModel

An explicit file reference with an optional layout hint retained on capture.

Fields:

Source code in protocol/octomate_protocol/visualizations.py
class HtmlReference(BaseModel):
    """An explicit file reference with an optional layout hint retained on capture."""

    path: Path = Field(description="Absolute HTML path in this run's workspace.")
    title: str | None = Field(default=None, min_length=1, max_length=200)
    mode: Literal["wide"] | None = Field(
        default=None,
        description="Native layout hint requesting a wider inline visualization.",
    )

    def read(self, workspace: Path) -> str:
        """Read a bounded snapshot through directory descriptors without following links."""
        relative = self.path.relative_to(workspace)
        if ".." in relative.parts or relative.suffix.lower() != ".html":
            raise ValueError("Visualization must be an HTML file inside the workspace")
        with ExitStack() as stack:
            directory = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY)
            stack.callback(os.close, directory)
            for part in relative.parts[:-1]:
                directory = os.open(
                    part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory
                )
                stack.callback(os.close, directory)
            descriptor = os.open(
                relative.name,
                os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
                dir_fd=directory,
            )
            source = stack.enter_context(os.fdopen(descriptor, "rb"))
            if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
                raise ValueError("Visualization must be a regular file")
            data = source.read(1_000_001)
        if len(data) > 1_000_000:
            raise ValueError("Visualization exceeds 1 MB")
        html = data.decode("utf-8")
        if not html.strip():
            raise ValueError("Visualization must be nonempty")
        return html

path pydantic-field

path: Path

Absolute HTML path in this run's workspace.

title pydantic-field

title: str | None = None

mode pydantic-field

mode: Literal['wide'] | None = None

Native layout hint requesting a wider inline visualization.

read

read(workspace: Path) -> str

Read a bounded snapshot through directory descriptors without following links.

Source code in protocol/octomate_protocol/visualizations.py
def read(self, workspace: Path) -> str:
    """Read a bounded snapshot through directory descriptors without following links."""
    relative = self.path.relative_to(workspace)
    if ".." in relative.parts or relative.suffix.lower() != ".html":
        raise ValueError("Visualization must be an HTML file inside the workspace")
    with ExitStack() as stack:
        directory = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY)
        stack.callback(os.close, directory)
        for part in relative.parts[:-1]:
            directory = os.open(
                part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory
            )
            stack.callback(os.close, directory)
        descriptor = os.open(
            relative.name,
            os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
            dir_fd=directory,
        )
        source = stack.enter_context(os.fdopen(descriptor, "rb"))
        if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
            raise ValueError("Visualization must be a regular file")
        data = source.read(1_000_001)
    if len(data) > 1_000_000:
        raise ValueError("Visualization exceeds 1 MB")
    html = data.decode("utf-8")
    if not html.strip():
        raise ValueError("Visualization must be nonempty")
    return html

HtmlSnapshot pydantic-model

Bases: BaseModel

An explicit visualization and the UTF-8 HTML read on its owning machine.

Fields:

Validators:

Source code in protocol/octomate_protocol/visualizations.py
class HtmlSnapshot(BaseModel):
    """An explicit visualization and the UTF-8 HTML read on its owning machine."""

    reference: HtmlReference = Field(
        description="The assistant's visualization reference."
    )
    html: str = Field(
        min_length=1,
        max_length=1_000_000,
        description="Captured HTML, at most 1 MB encoded as UTF-8.",
    )

    @field_validator("html")
    @classmethod
    def bounded_html(cls, value: str) -> str:
        if not value.strip() or len(value.encode("utf-8")) > 1_000_000:
            raise ValueError("Visualization must be nonempty UTF-8 HTML at most 1 MB")
        return value

reference pydantic-field

reference: HtmlReference

The assistant's visualization reference.

html pydantic-field

html: str

Captured HTML, at most 1 MB encoded as UTF-8.

bounded_html pydantic-validator

bounded_html(value: str) -> str
Source code in protocol/octomate_protocol/visualizations.py
@field_validator("html")
@classmethod
def bounded_html(cls, value: str) -> str:
    if not value.strip() or len(value.encode("utf-8")) > 1_000_000:
        raise ValueError("Visualization must be nonempty UTF-8 HTML at most 1 MB")
    return value

codex_html_references

codex_html_references(raw: str) -> list[HtmlReference]

Read explicit references from assistant response items only.

Unmodeled lines remain the server tailer's concern. A recognized visualization must validate before its client opens any file. Prompts and tool output never authorize file capture.

Source code in protocol/octomate_protocol/visualizations.py
def codex_html_references(raw: str) -> list[HtmlReference]:
    """Read explicit references from assistant response items only.

    Unmodeled lines remain the server tailer's concern. A recognized visualization
    must validate before its client opens any file. Prompts and tool output never
    authorize file capture.
    """
    try:
        line = rollout_object_adapter.validate_json(raw)
    except ValidationError:
        return []
    payload = line.get("payload")
    if line.get("type") != "response_item" or not isinstance(payload, dict):
        return []
    if payload.get("type") != "message" or payload.get("role") != "assistant":
        return []
    content = payload.get("content")
    if not isinstance(content, list):
        return []
    texts = [part.get("text") for part in content if isinstance(part, dict)]
    references = [
        HtmlReference.model_validate_json(match[1])
        for text in texts
        if isinstance(text, str)
        for match in VISUALIZATION_REFERENCE.finditer(text)
    ]
    unique: dict[Path, HtmlReference] = {}
    for reference in references:
        unique.setdefault(reference.path, reference)
    return list(unique.values())