Skip to content

Native session hooks and tailers

octomate.tentacles.hooks

FastAPI dependencies that authenticate a runtime's hook request and resolve its sender.

verify_hook_key async

verify_hook_key(
    auth: Annotated[AuthManager, Depends(auth_manager)],
    authorization: Annotated[str | None, Header()] = None,
) -> ApiKey

Require a hooks-scoped API key before accessing the owner's resources.

Source code in octomate/tentacles/hooks.py
async def verify_hook_key(
    auth: Annotated[AuthManager, Depends(auth_manager)],
    authorization: Annotated[str | None, Header()] = None,
) -> ApiKey:
    """Require a hooks-scoped API key before accessing the owner's resources."""
    key = (
        await auth.authenticate_api_key(
            SecretStr(authorization.removeprefix("Bearer ")), scope="hooks"
        )
        if authorization is not None and authorization.startswith("Bearer ")
        else None
    )
    if key is None:
        raise HTTPException(401, "Invalid API key")
    return key

hook_guard

hook_guard(
    bearers: KnownBearers,
) -> Callable[[str | None], Awaitable[str]]

Authenticate a hook request with a hooks-scoped API key or OAuth token.

The dependency yields the owner's username for ledger attribution.

Source code in octomate/tentacles/hooks.py
def hook_guard(
    bearers: KnownBearers,
) -> Callable[[str | None], Awaitable[str]]:
    """Authenticate a hook request with a hooks-scoped API key or OAuth token.

    The dependency yields the owner's username for ledger attribution.
    """

    async def verify(
        authorization: Annotated[str | None, Header()] = None,
    ) -> str:
        username = (
            await bearers.owner(authorization.removeprefix("Bearer "), scope="hooks")
            if authorization is not None and authorization.startswith("Bearer ")
            else None
        )
        if username is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="invalid hook credentials",
            )
        return username

    return verify

hook_sender

hook_sender(
    users: UserManager,
    runtime: str,
    verify: Callable[[str | None], Awaitable[str]],
) -> Callable[[str], Awaitable[UserProfile]]

The guard's second half, as a FastAPI dependency: the verified principal resolved to their own profile on runtime's pseudo-channel — who every ledger row this request writes is attributed to.

Composes over verify rather than re-reading the header: FastAPI caches a dependency's value per request, so a router-level guard and this one share a single bearer check.

Source code in octomate/tentacles/hooks.py
def hook_sender(
    users: UserManager,
    runtime: str,
    verify: Callable[[str | None], Awaitable[str]],
) -> Callable[[str], Awaitable[UserProfile]]:
    """The guard's second half, as a FastAPI dependency: the verified principal
    resolved to their own profile on `runtime`'s pseudo-channel — who every
    ledger row this request writes is attributed to.

    Composes over `verify` rather than re-reading the header: FastAPI caches a
    dependency's value per request, so a router-level guard and this one share a
    single bearer check."""

    async def sender(username: str = Depends(verify)) -> UserProfile:
        profile = await users.native_profile(runtime, username)
        if profile is None:
            # The guard already proved the username names a registered user, so
            # a miss is a wiring bug worth an error, never a row written to nobody.
            raise RuntimeError(
                f"verified bearer names {username!r}, but the registry holds no "
                "such user"
            )
        return profile

    return sender

octomate.tentacles.claude.ingest

Hook-driven ingest of a native Claude Code session.

Hooks establish session and run identities and signal transcript boundaries. Only the transcript tail writes messages.

logger module-attribute

logger = logging.getLogger(__name__)

ClaudeHookIngest

Establish native session/run identities and relay transcript boundaries.

Hooks may arrive before or after their transcript. They ensure empty runs under the same native turn keys, but never write messages or replace a run's contents. The tail alone creates model messages and their ledger bindings. Its authenticated stream supplies the sender. A hook's transcript path is client context, never a server-local file to open.

Source code in octomate/tentacles/claude/ingest.py
class ClaudeHookIngest:
    """Establish native session/run identities and relay transcript boundaries.

    Hooks may arrive before or after their transcript. They ensure empty runs
    under the same native turn keys, but never write messages or replace a run's
    contents. The tail alone creates model messages and their ledger bindings.
    Its authenticated stream supplies the sender. A hook's transcript path is
    client context, never a server-local file to open.
    """

    conversations: ConversationManager
    threads: ThreadManager
    tailer: ClaudeTranscriptTailer
    locks: SessionLocks

    def __init__(
        self,
        tailer: ClaudeTranscriptTailer,
        locks: SessionLocks | None = None,
        *,
        conversations: ConversationManager,
        threads: ThreadManager,
    ) -> None:
        self.conversations = conversations
        self.threads = threads
        self.tailer = tailer
        # Serialize a session's events so the existence check and the write can't race
        # (Claude fires the next event without waiting for our commit). Shared with the
        # tailer so its run/ledger commits serialize against these writes too; the
        # registry reclaims a session's lock on its own once no one holds it.
        self.locks = locks if locks is not None else SessionLocks()

    async def handle(self, event: ClaudeHookInput) -> None:
        """Handle an authenticated hook; message attribution belongs to the stream."""
        if (
            event.agent_id is None
            and event.prompt_id
            and await self.conversations.driven_run(
                self.tailer.agent_tentacle_id, event.session_id, event.prompt_id
            )
            is not None
        ):
            if event.hook_event_name == "Stop":
                await self.tailer.stop_turn(event.session_id, event.prompt_id)
            return
        match event.hook_event_name:
            case "SubagentStart":
                await self.on_subagent_start(event)
            case "SubagentStop":
                await self.on_subagent_stop(event)
            case _ if event.agent_id is not None:
                # Any other event carrying agent_id fired *inside* a subagent (its
                # own Stop, a PreToolUse, …) and is never a parent-turn event.
                # A child's Stop must never drain the parent turn.
                return
            case "UserPromptSubmit":
                await self.on_user_prompt_submit(event)
            case "Stop":
                await self.on_stop(event)
            case "SessionEnd":
                await self.on_session_end(event)

    @claude_logfire.instrument(
        "claude.hook UserPromptSubmit [{event.session_id}]", extract_args=["event"]
    )
    async def on_user_prompt_submit(self, event: ClaudeHookInput) -> None:
        self.tailer.ended.discard(event.session_id)
        async with self.locks.hold(event.session_id):
            await self.start_session(event)
            await self.ensure_run(event)

    @claude_logfire.instrument(
        "claude.hook Stop [{event.session_id}]", extract_args=["event"]
    )
    async def on_stop(self, event: ClaudeHookInput) -> None:
        async with self.locks.hold(event.session_id):
            await self.start_session(event)
            await self.ensure_run(event)
        # The turn is over and its transcript flushed: let the tail commit it now
        # rather than at the next prompt — a remote one drains out and exits. Outside
        # the lock, because a local close takes the same session lock to commit.
        # A background child can outlive the parent turn. Its stream must stay
        # attached; the parent's stop_hook_summary still closes that turn.
        if not any(task.type == "subagent" for task in event.background_tasks):
            await self.tailer.stop_turn(event.session_id, event.prompt_id)

    @claude_logfire.instrument(
        "claude.hook SessionEnd [{event.session_id}]", extract_args=["event"]
    )
    async def on_session_end(self, event: ClaudeHookInput) -> None:
        logger.info("session %s: ended", event.session_id)
        # The thread first: for a session whose earlier hooks never arrived this is
        # the last event carrying a cwd, and a thread's project is frozen at creation
        # — a backfill tail attaching later would create it unfiled. Already-created
        # sessions resolve to their existing row.
        await self.session_thread(event)
        # Finalize outside any lock: it awaits the stream's drain commits, which take
        # the session lock — holding it here would deadlock.
        await self.tailer.finalize(event.session_id)

    @claude_logfire.instrument(
        "claude.hook SubagentStart [{event.session_id}/{event.agent_id}]",
        extract_args=["event"],
    )
    async def on_subagent_start(self, event: ClaudeHookInput) -> None:
        if not event.agent_id:
            return
        async with self.locks.hold(event.session_id):
            await self.start_session(event)
            if event.prompt_id:
                await self.ensure_subagent_run(event)
        logger.info("session %s: subagent %s started", event.session_id, event.agent_id)

    @claude_logfire.instrument(
        "claude.hook SubagentStop [{event.session_id}/{event.agent_id}]",
        extract_args=["event"],
    )
    async def on_subagent_stop(self, event: ClaudeHookInput) -> None:
        if not event.agent_id:
            return
        # The subagent has written its last line by the time this synchronous hook
        # fires — and a Claude child's own file never closes its last turn — so wait
        # for the streamed answer and commit the open turn now. A session no stream
        # covers has nothing to settle.
        answer = await self.tailer.finish_subagent(
            event.session_id,
            event.agent_id,
            final_answer=event.last_assistant_message,
        )
        # Claude names no answer for a child that handed it back through a tool call.
        if not event.last_assistant_message:
            event.last_assistant_message = answer
        logger.info("session %s: subagent %s stopped", event.session_id, event.agent_id)

    async def ensure_subagent_run(self, event: ClaudeHookInput) -> None:
        """Ensure the child's empty run without copying its hook prompt."""
        # Both guarded by the caller.
        assert event.agent_id
        assert event.prompt_id
        thread = await self.session_thread(event)
        parent = await self.conversations.ensure(
            thread.id,
            agent_tentacle_id=self.tailer.agent_tentacle_id,
            native=True,
        )
        child = await self.conversations.ensure(
            thread.id,
            agent_tentacle_id=self.tailer.agent_tentacle_id,
            native=True,
            subagent_id=event.agent_id,
            parent_conversation_id=parent.id,
        )
        await self.conversations.record_external_run(
            child,
            run_id=f"{event.agent_id}:{event.prompt_id}",
            name=self.tailer.agent_tentacle_id,
            cwd=Path(event.cwd) if event.cwd else None,
            native_session_id=event.agent_id,
            parent_run_id=event.prompt_id,
        )

    async def start_session(self, event: ClaudeHookInput) -> None:
        """Ensure the session's skeleton (thread + conversation), under the session
        lock so the write can't race the hooks' first-sighting create. The transcript
        itself arrives only through the stream; nothing here follows the path a hook
        claims."""
        thread = await self.session_thread(event)
        await self.conversations.ensure(
            thread.id,
            agent_tentacle_id=self.tailer.agent_tentacle_id,
            native=True,
        )

    async def session_thread(self, event: ClaudeHookInput) -> Thread:
        """Reuse the session thread attributed at authenticated entry."""
        return await self.threads.ensure(
            ThreadKey(
                channel_tentacle_id=self.tailer.agent_tentacle_id,
                chat_type="thread",
                chat_id=event.session_id,
                channel_thread_id=None,
            ),
            native=True,
        )

    async def ensure_run(self, event: ClaudeHookInput) -> None:
        """Reserve the turn's foreign-key target; repeated or late hooks change nothing."""
        if not event.prompt_id:
            return
        thread = await self.session_thread(event)
        conversation = await self.conversations.ensure(
            thread.id,
            agent_tentacle_id=self.tailer.agent_tentacle_id,
            native=True,
        )
        await self.conversations.record_external_run(
            conversation,
            run_id=event.prompt_id,
            name=self.tailer.agent_tentacle_id,
            cwd=Path(event.cwd) if event.cwd else None,
            native_session_id=event.session_id,
        )

conversations instance-attribute

conversations: ConversationManager = conversations

threads instance-attribute

threads: ThreadManager = threads

tailer instance-attribute

tailer: ClaudeTranscriptTailer = tailer

locks instance-attribute

locks: SessionLocks = (
    locks if locks is not None else SessionLocks()
)

handle async

handle(event: ClaudeHookInput) -> None

Handle an authenticated hook; message attribution belongs to the stream.

Source code in octomate/tentacles/claude/ingest.py
async def handle(self, event: ClaudeHookInput) -> None:
    """Handle an authenticated hook; message attribution belongs to the stream."""
    if (
        event.agent_id is None
        and event.prompt_id
        and await self.conversations.driven_run(
            self.tailer.agent_tentacle_id, event.session_id, event.prompt_id
        )
        is not None
    ):
        if event.hook_event_name == "Stop":
            await self.tailer.stop_turn(event.session_id, event.prompt_id)
        return
    match event.hook_event_name:
        case "SubagentStart":
            await self.on_subagent_start(event)
        case "SubagentStop":
            await self.on_subagent_stop(event)
        case _ if event.agent_id is not None:
            # Any other event carrying agent_id fired *inside* a subagent (its
            # own Stop, a PreToolUse, …) and is never a parent-turn event.
            # A child's Stop must never drain the parent turn.
            return
        case "UserPromptSubmit":
            await self.on_user_prompt_submit(event)
        case "Stop":
            await self.on_stop(event)
        case "SessionEnd":
            await self.on_session_end(event)

on_user_prompt_submit async

on_user_prompt_submit(event: ClaudeHookInput) -> None
Source code in octomate/tentacles/claude/ingest.py
@claude_logfire.instrument(
    "claude.hook UserPromptSubmit [{event.session_id}]", extract_args=["event"]
)
async def on_user_prompt_submit(self, event: ClaudeHookInput) -> None:
    self.tailer.ended.discard(event.session_id)
    async with self.locks.hold(event.session_id):
        await self.start_session(event)
        await self.ensure_run(event)

on_stop async

on_stop(event: ClaudeHookInput) -> None
Source code in octomate/tentacles/claude/ingest.py
@claude_logfire.instrument(
    "claude.hook Stop [{event.session_id}]", extract_args=["event"]
)
async def on_stop(self, event: ClaudeHookInput) -> None:
    async with self.locks.hold(event.session_id):
        await self.start_session(event)
        await self.ensure_run(event)
    # The turn is over and its transcript flushed: let the tail commit it now
    # rather than at the next prompt — a remote one drains out and exits. Outside
    # the lock, because a local close takes the same session lock to commit.
    # A background child can outlive the parent turn. Its stream must stay
    # attached; the parent's stop_hook_summary still closes that turn.
    if not any(task.type == "subagent" for task in event.background_tasks):
        await self.tailer.stop_turn(event.session_id, event.prompt_id)

on_session_end async

on_session_end(event: ClaudeHookInput) -> None
Source code in octomate/tentacles/claude/ingest.py
@claude_logfire.instrument(
    "claude.hook SessionEnd [{event.session_id}]", extract_args=["event"]
)
async def on_session_end(self, event: ClaudeHookInput) -> None:
    logger.info("session %s: ended", event.session_id)
    # The thread first: for a session whose earlier hooks never arrived this is
    # the last event carrying a cwd, and a thread's project is frozen at creation
    # — a backfill tail attaching later would create it unfiled. Already-created
    # sessions resolve to their existing row.
    await self.session_thread(event)
    # Finalize outside any lock: it awaits the stream's drain commits, which take
    # the session lock — holding it here would deadlock.
    await self.tailer.finalize(event.session_id)

on_subagent_start async

on_subagent_start(event: ClaudeHookInput) -> None
Source code in octomate/tentacles/claude/ingest.py
@claude_logfire.instrument(
    "claude.hook SubagentStart [{event.session_id}/{event.agent_id}]",
    extract_args=["event"],
)
async def on_subagent_start(self, event: ClaudeHookInput) -> None:
    if not event.agent_id:
        return
    async with self.locks.hold(event.session_id):
        await self.start_session(event)
        if event.prompt_id:
            await self.ensure_subagent_run(event)
    logger.info("session %s: subagent %s started", event.session_id, event.agent_id)

on_subagent_stop async

on_subagent_stop(event: ClaudeHookInput) -> None
Source code in octomate/tentacles/claude/ingest.py
@claude_logfire.instrument(
    "claude.hook SubagentStop [{event.session_id}/{event.agent_id}]",
    extract_args=["event"],
)
async def on_subagent_stop(self, event: ClaudeHookInput) -> None:
    if not event.agent_id:
        return
    # The subagent has written its last line by the time this synchronous hook
    # fires — and a Claude child's own file never closes its last turn — so wait
    # for the streamed answer and commit the open turn now. A session no stream
    # covers has nothing to settle.
    answer = await self.tailer.finish_subagent(
        event.session_id,
        event.agent_id,
        final_answer=event.last_assistant_message,
    )
    # Claude names no answer for a child that handed it back through a tool call.
    if not event.last_assistant_message:
        event.last_assistant_message = answer
    logger.info("session %s: subagent %s stopped", event.session_id, event.agent_id)

ensure_subagent_run async

ensure_subagent_run(event: ClaudeHookInput) -> None

Ensure the child's empty run without copying its hook prompt.

Source code in octomate/tentacles/claude/ingest.py
async def ensure_subagent_run(self, event: ClaudeHookInput) -> None:
    """Ensure the child's empty run without copying its hook prompt."""
    # Both guarded by the caller.
    assert event.agent_id
    assert event.prompt_id
    thread = await self.session_thread(event)
    parent = await self.conversations.ensure(
        thread.id,
        agent_tentacle_id=self.tailer.agent_tentacle_id,
        native=True,
    )
    child = await self.conversations.ensure(
        thread.id,
        agent_tentacle_id=self.tailer.agent_tentacle_id,
        native=True,
        subagent_id=event.agent_id,
        parent_conversation_id=parent.id,
    )
    await self.conversations.record_external_run(
        child,
        run_id=f"{event.agent_id}:{event.prompt_id}",
        name=self.tailer.agent_tentacle_id,
        cwd=Path(event.cwd) if event.cwd else None,
        native_session_id=event.agent_id,
        parent_run_id=event.prompt_id,
    )

start_session async

start_session(event: ClaudeHookInput) -> None

Ensure the session's skeleton (thread + conversation), under the session lock so the write can't race the hooks' first-sighting create. The transcript itself arrives only through the stream; nothing here follows the path a hook claims.

Source code in octomate/tentacles/claude/ingest.py
async def start_session(self, event: ClaudeHookInput) -> None:
    """Ensure the session's skeleton (thread + conversation), under the session
    lock so the write can't race the hooks' first-sighting create. The transcript
    itself arrives only through the stream; nothing here follows the path a hook
    claims."""
    thread = await self.session_thread(event)
    await self.conversations.ensure(
        thread.id,
        agent_tentacle_id=self.tailer.agent_tentacle_id,
        native=True,
    )

session_thread async

session_thread(event: ClaudeHookInput) -> Thread

Reuse the session thread attributed at authenticated entry.

Source code in octomate/tentacles/claude/ingest.py
async def session_thread(self, event: ClaudeHookInput) -> Thread:
    """Reuse the session thread attributed at authenticated entry."""
    return await self.threads.ensure(
        ThreadKey(
            channel_tentacle_id=self.tailer.agent_tentacle_id,
            chat_type="thread",
            chat_id=event.session_id,
            channel_thread_id=None,
        ),
        native=True,
    )

ensure_run async

ensure_run(event: ClaudeHookInput) -> None

Reserve the turn's foreign-key target; repeated or late hooks change nothing.

Source code in octomate/tentacles/claude/ingest.py
async def ensure_run(self, event: ClaudeHookInput) -> None:
    """Reserve the turn's foreign-key target; repeated or late hooks change nothing."""
    if not event.prompt_id:
        return
    thread = await self.session_thread(event)
    conversation = await self.conversations.ensure(
        thread.id,
        agent_tentacle_id=self.tailer.agent_tentacle_id,
        native=True,
    )
    await self.conversations.record_external_run(
        conversation,
        run_id=event.prompt_id,
        name=self.tailer.agent_tentacle_id,
        cwd=Path(event.cwd) if event.cwd else None,
        native_session_id=event.session_id,
    )

octomate.tentacles.locks

Per-session asyncio locks that clean up after themselves.

SessionLocks

Per-session asyncio.Locks. Not a lock of its own — a thin registry over the stdlib lock, adding the keying the stdlib has no primitive for, plus self-cleanup: each entry is a weak reference, so once no task holds or waits on a key's lock it is reclaimed and the key leaves nothing behind.

async with locks.hold(key) releases on every exit — return, exception, or cancellation — so an acquire cancelled by its timeout frees the lock automatically, no manual dismissal or force-release.

Source code in octomate/tentacles/locks.py
class SessionLocks:
    """Per-session `asyncio.Lock`s. Not a lock of its own — a thin registry over the
    stdlib lock, adding the keying the stdlib has no primitive for, plus self-cleanup:
    each entry is a weak reference, so once no task holds or waits on a key's lock it is
    reclaimed and the key leaves nothing behind.

    `async with locks.hold(key)` releases on every exit — return, exception, or
    cancellation — so an acquire cancelled by its timeout frees the lock automatically,
    no manual dismissal or force-release.
    """

    def __init__(self) -> None:
        self.by_session: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary()

    @asynccontextmanager
    async def hold(
        self,
        key: str,
        *,
        acquire_timeout: float | None = None,
    ) -> AsyncGenerator[None]:
        """Hold the key's lock for the block. `acquire_timeout` bounds the wait for the
        lock and nothing else: a waiter stuck behind a wedged holder raises
        `TimeoutError` rather than blocking forever, while the block it guards runs
        unbounded once entered. A caller wanting to bound the work too wraps the whole
        `async with` in its own cancel scope; a never-acquired lock is never released."""
        # The local `lock` is a strong reference held for the whole block, so the weak
        # entry stays alive while anyone holds or waits on it — concurrent users share
        # the one live lock — and is reclaimed once the last user leaves.
        lock = self.by_session.get(key)
        if lock is None:
            lock = asyncio.Lock()
            self.by_session[key] = lock
        await asyncio.wait_for(lock.acquire(), acquire_timeout)
        try:
            yield
        finally:
            lock.release()

by_session instance-attribute

by_session: WeakValueDictionary[str, Lock] = (
    WeakValueDictionary()
)

hold async

hold(
    key: str, *, acquire_timeout: float | None = None
) -> AsyncGenerator[None]

Hold the key's lock for the block. acquire_timeout bounds the wait for the lock and nothing else: a waiter stuck behind a wedged holder raises TimeoutError rather than blocking forever, while the block it guards runs unbounded once entered. A caller wanting to bound the work too wraps the whole async with in its own cancel scope; a never-acquired lock is never released.

Source code in octomate/tentacles/locks.py
@asynccontextmanager
async def hold(
    self,
    key: str,
    *,
    acquire_timeout: float | None = None,
) -> AsyncGenerator[None]:
    """Hold the key's lock for the block. `acquire_timeout` bounds the wait for the
    lock and nothing else: a waiter stuck behind a wedged holder raises
    `TimeoutError` rather than blocking forever, while the block it guards runs
    unbounded once entered. A caller wanting to bound the work too wraps the whole
    `async with` in its own cancel scope; a never-acquired lock is never released."""
    # The local `lock` is a strong reference held for the whole block, so the weak
    # entry stays alive while anyone holds or waits on it — concurrent users share
    # the one live lock — and is reclaimed once the last user leaves.
    lock = self.by_session.get(key)
    if lock is None:
        lock = asyncio.Lock()
        self.by_session[key] = lock
    await asyncio.wait_for(lock.acquire(), acquire_timeout)
    try:
        yield
    finally:
        lock.release()

octomate.tentacles.tailer

The shared lifecycle of a native turn published from a transcript.

NativeTurn dataclass

One transcript turn's live events and prompt bindings.

Tailers supply native boundaries, source message identities, and their own accumulator's message list. This owner rejects committed or driven turns, records prompts in that list, publishes the fold, and settles only after the caller commits the run. Subagent transcripts do not publish on this surface.

Source code in octomate/tentacles/tailer.py
@dataclass
class NativeTurn:
    """One transcript turn's live events and prompt bindings.

    Tailers supply native boundaries, source message identities, and their own
    accumulator's message list. This owner rejects committed or driven turns,
    records prompts in that list, publishes the fold, and settles only after the
    caller commits the run. Subagent transcripts do not publish on this surface.
    """

    threads: ThreadManager
    locks: SessionLocks
    address: ChannelAddress
    sender: UserProfile
    impulses: ObjectSendStream[Impulse]
    messages: list[ModelMessage]
    recorded: set[str]
    # Keep the actual requests: list positions can change while folding.
    prompts: dict[UUID7, ModelRequest] = field(default_factory=dict)
    replay: bool = (
        False  # True until the connection's initial transcript offset is reached.
    )

    @classmethod
    async def open(
        cls,
        *,
        run_id: str,
        recorded: set[str],
        conversations: ConversationManager,
        threads: ThreadManager,
        locks: SessionLocks,
        address: ChannelAddress,
        sender: UserProfile,
        impulses: ObjectSendStream[Impulse],
        messages: list[ModelMessage],
        replay: bool = False,
    ) -> NativeTurn | None:
        """Publish the opening bracket unless this turn already has an owner."""
        if run_id in recorded:
            return None
        if (
            await conversations.driven_run(
                address.channel_tentacle_id, address.chat_id, run_id
            )
            is not None
        ):
            recorded.add(run_id)
            return None
        turn = cls(
            threads, locks, address, sender, impulses, messages, recorded, replay=replay
        )
        await impulses.send(
            Impulse(
                RunStartedEvent(address=address, sender=sender), address, replay=replay
            )
        )
        return turn

    async def caught_up(self) -> None:
        """Resume activity for an open turn after restoring its historical prefix."""
        self.replay = False
        await self.impulses.send(
            Impulse(RunActivityChangedEvent(activity="working"), self.address)
        )

    async def prompt(
        self,
        *,
        message_id: str,
        text: str | TextContent,
        timestamp: datetime,
        metadata: JsonObject | None = None,
        actor_kind: ChannelActorKind = "human",
    ) -> None:
        """Record a source prompt once and deliver its request at this point.

        The ledger row grants access before the run is complete. Its id is also
        the enqueue id, so the console reconciles the live prompt with that row.
        A line the harness wrote in the person's place is a `system` row: it joins
        the history and the ledger, and a reader is told the harness said it.
        A prompt whose annotations name an agent is that agent's message.
        """
        agent = (
            MessageAnnotations.model_validate(text.metadata["annotations"]).agent
            if isinstance(text, TextContent)
            else None
        )
        async with self.locks.hold(self.address.chat_id):
            inbound = await self.threads.record_native_prompt(
                self.address,
                message_id=message_id,
                text=text,
                sender=self.sender,
                timestamp=timestamp,
                actor_kind="agent" if agent is not None else actor_kind,
            )
        request = ModelRequest(
            parts=[
                UserPromptPart(
                    content=[text] if isinstance(text, TextContent) else text,
                    timestamp=timestamp,
                )
            ],
            timestamp=timestamp,
            metadata=metadata,
        )
        self.messages.append(request)
        self.prompts[inbound.id] = request
        if agent is not None:
            await self.impulses.send(
                Impulse(
                    AgentMessageEvent(
                        message_id=inbound.id,
                        agent=agent,
                        text=inbound.message_text or "",
                    ),
                    self.address,
                    replay=self.replay,
                )
            )
        elif actor_kind == "human":
            await self.impulses.send(
                Impulse(
                    EnqueuedMessagesEvent(
                        enqueue_id=str(inbound.id), messages=(request,)
                    ),
                    self.address,
                    replay=self.replay,
                )
            )
        elif actor_kind == "system":
            await self.impulses.send(
                Impulse(
                    SystemMessageEvent(
                        message_id=inbound.id, text=inbound.message_text or ""
                    ),
                    self.address,
                    replay=self.replay,
                )
            )

    async def fold(self, events: Iterable[StreamEvents[str]]) -> None:
        """Consume and publish the accumulator's events on the native thread."""
        for event in events:
            if (wire := to_wire(event)) is not None:
                await self.impulses.send(
                    Impulse(wire, self.address, replay=self.replay)
                )

    async def close(
        self,
        run: ExternalAgentRun | None,
        *,
        run_id: str,
        answer: str,
        interrupted: bool = False,
    ) -> None:
        """Bind the committed history before publishing the closing bracket.

        The caller holds the session lock through its commit and this binding.
        `record_external_run` preserves input order; resolve the request objects
        against that committed list here instead of tracking indices in tailers.
        A failed commit or binding propagates without publishing `run_ended`.
        """
        if run is None:
            self.recorded.add(run_id)
            return
        sources = {id(request): row_id for row_id, request in self.prompts.items()}
        prompts = {
            sources[id(message)]: stored.id
            for message, stored in zip(self.messages, run.messages, strict=True)
            if id(message) in sources
        }
        if len(prompts) != len(self.prompts):
            raise ValueError("A native prompt disappeared from the committed history")
        reply_id = await self.threads.bind_native_run(
            self.address, run, prompts=prompts, answer=answer, sender=self.sender
        )
        await self.settle(run_id, thread_message_id=reply_id, interrupted=interrupted)

    async def settle(
        self,
        run_id: str,
        *,
        thread_message_id: UUID7 | None = None,
        interrupted: bool = False,
    ) -> None:
        """Publish the closing bracket after the native task's durable writes finish."""
        self.recorded.add(run_id)
        await self.impulses.send(
            Impulse(
                RunEndedEvent(
                    thread_message_id=thread_message_id,
                    outcome="cancelled" if interrupted else None,
                ),
                self.address,
                replay=self.replay,
            )
        )

threads instance-attribute

threads: ThreadManager

locks instance-attribute

locks: SessionLocks

address instance-attribute

address: ChannelAddress

sender instance-attribute

sender: UserProfile

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

messages instance-attribute

messages: list[ModelMessage]

recorded instance-attribute

recorded: set[str]

prompts class-attribute instance-attribute

prompts: dict[UUID7, ModelRequest] = field(
    default_factory=dict
)

replay class-attribute instance-attribute

replay: bool = False

open async classmethod

open(
    *,
    run_id: str,
    recorded: set[str],
    conversations: ConversationManager,
    threads: ThreadManager,
    locks: SessionLocks,
    address: ChannelAddress,
    sender: UserProfile,
    impulses: ObjectSendStream[Impulse],
    messages: list[ModelMessage],
    replay: bool = False,
) -> NativeTurn | None

Publish the opening bracket unless this turn already has an owner.

Source code in octomate/tentacles/tailer.py
@classmethod
async def open(
    cls,
    *,
    run_id: str,
    recorded: set[str],
    conversations: ConversationManager,
    threads: ThreadManager,
    locks: SessionLocks,
    address: ChannelAddress,
    sender: UserProfile,
    impulses: ObjectSendStream[Impulse],
    messages: list[ModelMessage],
    replay: bool = False,
) -> NativeTurn | None:
    """Publish the opening bracket unless this turn already has an owner."""
    if run_id in recorded:
        return None
    if (
        await conversations.driven_run(
            address.channel_tentacle_id, address.chat_id, run_id
        )
        is not None
    ):
        recorded.add(run_id)
        return None
    turn = cls(
        threads, locks, address, sender, impulses, messages, recorded, replay=replay
    )
    await impulses.send(
        Impulse(
            RunStartedEvent(address=address, sender=sender), address, replay=replay
        )
    )
    return turn

caught_up async

caught_up() -> None

Resume activity for an open turn after restoring its historical prefix.

Source code in octomate/tentacles/tailer.py
async def caught_up(self) -> None:
    """Resume activity for an open turn after restoring its historical prefix."""
    self.replay = False
    await self.impulses.send(
        Impulse(RunActivityChangedEvent(activity="working"), self.address)
    )

prompt async

prompt(
    *,
    message_id: str,
    text: str | TextContent,
    timestamp: datetime,
    metadata: JsonObject | None = None,
    actor_kind: ChannelActorKind = "human",
) -> None

Record a source prompt once and deliver its request at this point.

The ledger row grants access before the run is complete. Its id is also the enqueue id, so the console reconciles the live prompt with that row. A line the harness wrote in the person's place is a system row: it joins the history and the ledger, and a reader is told the harness said it. A prompt whose annotations name an agent is that agent's message.

Source code in octomate/tentacles/tailer.py
async def prompt(
    self,
    *,
    message_id: str,
    text: str | TextContent,
    timestamp: datetime,
    metadata: JsonObject | None = None,
    actor_kind: ChannelActorKind = "human",
) -> None:
    """Record a source prompt once and deliver its request at this point.

    The ledger row grants access before the run is complete. Its id is also
    the enqueue id, so the console reconciles the live prompt with that row.
    A line the harness wrote in the person's place is a `system` row: it joins
    the history and the ledger, and a reader is told the harness said it.
    A prompt whose annotations name an agent is that agent's message.
    """
    agent = (
        MessageAnnotations.model_validate(text.metadata["annotations"]).agent
        if isinstance(text, TextContent)
        else None
    )
    async with self.locks.hold(self.address.chat_id):
        inbound = await self.threads.record_native_prompt(
            self.address,
            message_id=message_id,
            text=text,
            sender=self.sender,
            timestamp=timestamp,
            actor_kind="agent" if agent is not None else actor_kind,
        )
    request = ModelRequest(
        parts=[
            UserPromptPart(
                content=[text] if isinstance(text, TextContent) else text,
                timestamp=timestamp,
            )
        ],
        timestamp=timestamp,
        metadata=metadata,
    )
    self.messages.append(request)
    self.prompts[inbound.id] = request
    if agent is not None:
        await self.impulses.send(
            Impulse(
                AgentMessageEvent(
                    message_id=inbound.id,
                    agent=agent,
                    text=inbound.message_text or "",
                ),
                self.address,
                replay=self.replay,
            )
        )
    elif actor_kind == "human":
        await self.impulses.send(
            Impulse(
                EnqueuedMessagesEvent(
                    enqueue_id=str(inbound.id), messages=(request,)
                ),
                self.address,
                replay=self.replay,
            )
        )
    elif actor_kind == "system":
        await self.impulses.send(
            Impulse(
                SystemMessageEvent(
                    message_id=inbound.id, text=inbound.message_text or ""
                ),
                self.address,
                replay=self.replay,
            )
        )

fold async

fold(events: Iterable[StreamEvents[str]]) -> None

Consume and publish the accumulator's events on the native thread.

Source code in octomate/tentacles/tailer.py
async def fold(self, events: Iterable[StreamEvents[str]]) -> None:
    """Consume and publish the accumulator's events on the native thread."""
    for event in events:
        if (wire := to_wire(event)) is not None:
            await self.impulses.send(
                Impulse(wire, self.address, replay=self.replay)
            )

close async

close(
    run: ExternalAgentRun | None,
    *,
    run_id: str,
    answer: str,
    interrupted: bool = False,
) -> None

Bind the committed history before publishing the closing bracket.

The caller holds the session lock through its commit and this binding. record_external_run preserves input order; resolve the request objects against that committed list here instead of tracking indices in tailers. A failed commit or binding propagates without publishing run_ended.

Source code in octomate/tentacles/tailer.py
async def close(
    self,
    run: ExternalAgentRun | None,
    *,
    run_id: str,
    answer: str,
    interrupted: bool = False,
) -> None:
    """Bind the committed history before publishing the closing bracket.

    The caller holds the session lock through its commit and this binding.
    `record_external_run` preserves input order; resolve the request objects
    against that committed list here instead of tracking indices in tailers.
    A failed commit or binding propagates without publishing `run_ended`.
    """
    if run is None:
        self.recorded.add(run_id)
        return
    sources = {id(request): row_id for row_id, request in self.prompts.items()}
    prompts = {
        sources[id(message)]: stored.id
        for message, stored in zip(self.messages, run.messages, strict=True)
        if id(message) in sources
    }
    if len(prompts) != len(self.prompts):
        raise ValueError("A native prompt disappeared from the committed history")
    reply_id = await self.threads.bind_native_run(
        self.address, run, prompts=prompts, answer=answer, sender=self.sender
    )
    await self.settle(run_id, thread_message_id=reply_id, interrupted=interrupted)

settle async

settle(
    run_id: str,
    *,
    thread_message_id: UUID7 | None = None,
    interrupted: bool = False,
) -> None

Publish the closing bracket after the native task's durable writes finish.

Source code in octomate/tentacles/tailer.py
async def settle(
    self,
    run_id: str,
    *,
    thread_message_id: UUID7 | None = None,
    interrupted: bool = False,
) -> None:
    """Publish the closing bracket after the native task's durable writes finish."""
    self.recorded.add(run_id)
    await self.impulses.send(
        Impulse(
            RunEndedEvent(
                thread_message_id=thread_message_id,
                outcome="cancelled" if interrupted else None,
            ),
            self.address,
            replay=self.replay,
        )
    )

octomate.tentacles.claude.tailer

Assembly of native Claude Code turns from a streamed transcript.

Lines streamed in by octomate claude tail feed ClaudeTranscriptTailer, which commits each completed turn as an ExternalAgentRun.

logger module-attribute

logger = logging.getLogger(__name__)

COMMIT_LOCK_TIMEOUT module-attribute

COMMIT_LOCK_TIMEOUT = 30.0

SUBAGENT_SETTLE_TIMEOUT module-attribute

SUBAGENT_SETTLE_TIMEOUT = 2.0

SUBAGENT_SETTLE_POLL module-attribute

SUBAGENT_SETTLE_POLL = 0.2

REMOTE_DRAIN_TIMEOUT module-attribute

REMOTE_DRAIN_TIMEOUT = 5.0

INTERRUPTED module-attribute

INTERRUPTED = '[Request interrupted by user'

OpenTurn dataclass

The turn currently being assembled off the live tail — its accumulator fed line by line, its byte range advancing to cover the last transcript line folded in. It commits as an ExternalAgentRun when the next prompt line or its Stop hooks' summary line closes it, when its own Stop hook reaches stop_turn, or at finalize.

Source code in octomate/tentacles/claude/tailer.py
@dataclass
class OpenTurn:
    """The turn currently being assembled off the live tail — its accumulator fed line
    by line, its byte range advancing to cover the last transcript line folded in. It
    commits as an `ExternalAgentRun` when the next prompt line or its `Stop` hooks'
    summary line closes it, when its own `Stop` hook reaches `stop_turn`, or at
    `finalize`."""

    prompt_id: str
    source: str | None  # the transcript `entrypoint` (claude-vscode / cli / …)
    # Where the turn's opening prompt line says it ran — the opening line specifically,
    # because a transcript carries a `cwd` on every line and a turn's tools wander into
    # scratchpads and site-packages, so the last line folded in is not where the run
    # happened. Per turn rather than per session, because a session resumed from another
    # directory carries on in that one.
    cwd: str
    start_offset: int  # byte offset of this turn's opening prompt line
    end_offset: int  # byte offset past the last line folded in
    accumulator: ClaudeRunAccumulator
    last_line_uuid: str | None
    permission_mode: str | None  # Permission mode on the turn's opening prompt.
    native: NativeTurn | None = None
    interrupted: bool = False  # The person stopped it; Claude fires no `Stop` then.
    # A child's assistant lines, by uuid: a result line names the one it answers.
    calls: set[str] = field(default_factory=set)

prompt_id instance-attribute

prompt_id: str

source instance-attribute

source: str | None

cwd instance-attribute

cwd: str

start_offset instance-attribute

start_offset: int

end_offset instance-attribute

end_offset: int

accumulator instance-attribute

accumulator: ClaudeRunAccumulator

last_line_uuid instance-attribute

last_line_uuid: str | None

permission_mode instance-attribute

permission_mode: str | None

native class-attribute instance-attribute

native: NativeTurn | None = None

interrupted class-attribute instance-attribute

interrupted: bool = False

calls class-attribute instance-attribute

calls: set[str] = field(default_factory=set)

SubagentTail dataclass

One subagent transcript's cursor within a session's tail. A subagent writes its own file (<session>/subagents/agent-<agentId>.jsonl), so it gets its own byte cursor, conversation, and open turn. Its turns frame on promptId change: subagent files carry no promptSource, and a resumed subagent's next turn may open on a tool-result line, not a prompt. A result that answers a call of the open turn stays in it whatever id it carries.

Source code in octomate/tentacles/claude/tailer.py
@dataclass
class SubagentTail:
    """One subagent transcript's cursor within a session's tail. A subagent writes its
    own file (`<session>/subagents/agent-<agentId>.jsonl`), so it gets its own byte
    cursor, conversation, and open turn. Its turns frame on `promptId` change: subagent files
    carry no `promptSource`, and a resumed subagent's next turn may open on a
    tool-result line, not a prompt. A result that answers a call of the open turn
    stays in it whatever id it carries."""

    agent_id: str
    path: Path
    catchup_end: int = 0  # Child transcript length at registration.
    offset: int = 0
    # The parent's call this child answers, when the client's meta file names it.
    call_id: str | None = None
    conversation: Conversation | None = None
    recorded: set[str] = field(default_factory=set)  # child run ids already committed
    open_turn: OpenTurn | None = None
    last_item_id: str | None = None
    compact_metadata: CompactMetadata | None = None
    compactions_pending: bool = False
    omitted_uuids: set[str] = field(default_factory=set)

agent_id instance-attribute

agent_id: str

path instance-attribute

path: Path

catchup_end class-attribute instance-attribute

catchup_end: int = 0

offset class-attribute instance-attribute

offset: int = 0

call_id class-attribute instance-attribute

call_id: str | None = None

conversation class-attribute instance-attribute

conversation: Conversation | None = None

recorded class-attribute instance-attribute

recorded: set[str] = field(default_factory=set)

open_turn class-attribute instance-attribute

open_turn: OpenTurn | None = None

last_item_id class-attribute instance-attribute

last_item_id: str | None = None

compact_metadata class-attribute instance-attribute

compact_metadata: CompactMetadata | None = None

compactions_pending class-attribute instance-attribute

compactions_pending: bool = False

omitted_uuids class-attribute instance-attribute

omitted_uuids: set[str] = field(default_factory=set)

TailState dataclass

One streamed session: its transcript lives on the client machine that streams it (octomate claude tail); the stream route feeds feed_remote, which drives the per-line assembly. transcript_path is the client's claim in the client's own namespace, a label never opened here — as are the subagent tails' paths.

Source code in octomate/tentacles/claude/tailer.py
@dataclass
class TailState:
    """One streamed session: its transcript lives on the client machine that streams
    it (`octomate claude tail`); the stream route feeds `feed_remote`, which drives
    the per-line assembly. `transcript_path` is the client's claim in the client's
    own namespace, a label never opened here — as are the subagent tails' paths."""

    session_id: str
    transcript_path: Path
    stop_event: asyncio.Event
    # The verified bearer's own profile — who every ledger row this stream
    # writes is attributed to.
    sender: UserProfile
    address: ChannelAddress  # The native surface resolved by the tentacle.
    impulses: ObjectSendStream[Impulse]  # The publisher open for this connection.
    catchup_end: int = (
        0  # Initial root transcript length advertised by this connection.
    )
    offset: int = 0
    conversation: Conversation | None = None
    recorded: set[str] = field(default_factory=set)  # prompt_ids already committed
    open_turn: OpenTurn | None = None
    last_item_id: str | None = None
    compact_metadata: CompactMetadata | None = None
    compactions_pending: bool = False
    omitted_uuids: set[str] = field(default_factory=set)
    subagents: dict[str, SubagentTail] = field(default_factory=dict)
    # Claude can repeat the same Agent tool result under a later prompt ID.
    spawn_agents: dict[str, str] = field(default_factory=dict)
    # Task names waiting for the result or child metadata to identify the conversation.
    spawn_names: dict[str, str] = field(default_factory=dict)
    # The children already recorded when this connection attached, by spawning
    # call: their hooks fired on an earlier one, so a re-streamed turn says so.
    known_spawns: dict[str, str] = field(default_factory=dict)
    # The prompt id of a turn whose `Stop` hook fired (`stop_turn`): commit it without
    # waiting for the next prompt line — but commit nothing newer, so a prompt queued
    # into the drain window is left open for the next connect to re-stream.
    drain_turn: str | None = None
    # Set once the session's trailing turns are committed (`finish_remote`), so
    # `finalize` can bound its wait for the client's drain.
    drained: asyncio.Event = field(default_factory=asyncio.Event)

    @property
    def subagents_dir(self) -> Path:
        # `<slug>/<session-id>.jsonl` keeps its subagents at `<slug>/<session-id>/subagents`.
        return self.transcript_path.with_suffix("") / "subagents"

session_id instance-attribute

session_id: str

transcript_path instance-attribute

transcript_path: Path

stop_event instance-attribute

stop_event: Event

sender instance-attribute

sender: UserProfile

address instance-attribute

address: ChannelAddress

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

catchup_end class-attribute instance-attribute

catchup_end: int = 0

offset class-attribute instance-attribute

offset: int = 0

conversation class-attribute instance-attribute

conversation: Conversation | None = None

recorded class-attribute instance-attribute

recorded: set[str] = field(default_factory=set)

open_turn class-attribute instance-attribute

open_turn: OpenTurn | None = None

last_item_id class-attribute instance-attribute

last_item_id: str | None = None

compact_metadata class-attribute instance-attribute

compact_metadata: CompactMetadata | None = None

compactions_pending class-attribute instance-attribute

compactions_pending: bool = False

omitted_uuids class-attribute instance-attribute

omitted_uuids: set[str] = field(default_factory=set)

subagents class-attribute instance-attribute

subagents: dict[str, SubagentTail] = field(
    default_factory=dict
)

spawn_agents class-attribute instance-attribute

spawn_agents: dict[str, str] = field(default_factory=dict)

spawn_names class-attribute instance-attribute

spawn_names: dict[str, str] = field(default_factory=dict)

known_spawns class-attribute instance-attribute

known_spawns: dict[str, str] = field(default_factory=dict)

drain_turn class-attribute instance-attribute

drain_turn: str | None = None

drained class-attribute instance-attribute

drained: Event = field(default_factory=asyncio.Event)

subagents_dir property

subagents_dir: Path

ClaudeTranscriptTailer

Assembles Claude turns from transcript lines streamed in by octomate claude tail — the only assembler: the server never opens a transcript, even for a session on this machine. Hooks can reserve empty runs, but only the transcript produces model messages and ledger rows.

Each framed line feeds a ClaudeRunAccumulator — the same translation the live tentacle and the whole-file restore use — driving two decoupled sinks:

  • durable — one ExternalAgentRun per completed turn, carrying the byte range it was built from, filling any empty run reserved by a hook. Older hook sketches are replaced for compatibility. Idempotent by prompt_id.
  • live — wire events sent through the connection's nerve publisher at the native thread address, waiting for no reader. Only uncommitted parent turns publish: run_started, the fold, then run_ended after the reply is bound. A reconnect reopens an unfinished turn with another run_started; no reflex is woken.

A turn commits on a proven boundary: the next prompt line, or the drained eof a relayed Stop/SessionEnd asks the client for — the transcript is flushed before Claude fires those hooks. Nothing newer than a stopped turn commits early (drain_turn), and the tail process exits once the stopped turn is durable; the next prompt's launcher spawns a fresh one. The committed runs' offsets are what a reconnecting client is told to resume from, so a connection that drops mid-stream leaves its open turn for the next connect to re-stream.

Source code in octomate/tentacles/claude/tailer.py
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
class ClaudeTranscriptTailer:
    """Assembles Claude turns from transcript lines streamed in by `octomate claude
    tail` — the only assembler: the server never opens a transcript, even for a
    session on this machine. Hooks can reserve empty runs, but only the transcript
    produces model messages and ledger rows.

    Each framed line feeds a `ClaudeRunAccumulator` — the same translation the live
    tentacle and the whole-file restore use — driving two decoupled sinks:

    - **durable** — one `ExternalAgentRun` per completed turn, carrying the byte range it
      was built from, filling any empty run reserved by a hook. Older hook sketches
      are replaced for compatibility. Idempotent by `prompt_id`.
    - **live** — wire events sent through the connection's nerve publisher at the
      native thread address, waiting for no reader. Only uncommitted parent turns publish:
      `run_started`, the fold, then `run_ended` after the reply is bound. A reconnect
      reopens an unfinished turn with another `run_started`; no reflex is woken.

    A turn commits on a proven boundary: the next prompt line, or the drained `eof`
    a relayed `Stop`/`SessionEnd` asks the client for — the transcript is flushed
    before Claude fires those hooks. Nothing newer than a stopped turn commits early
    (`drain_turn`), and the tail process exits once the stopped turn is durable; the
    next prompt's launcher spawns a fresh one. The committed runs' offsets are what
    a reconnecting client is told to resume from, so a connection that drops
    mid-stream leaves its open turn for the next connect to re-stream.
    """

    agent_tentacle_id: str

    def __init__(
        self,
        conversation_manager: ConversationManager,
        thread_manager: ThreadManager,
        locks: SessionLocks | None = None,
        *,
        agent_tentacle_id: str,
    ) -> None:
        self.agent_tentacle_id = agent_tentacle_id
        self.conversation_manager = conversation_manager
        self.thread_manager = thread_manager
        # Per-session locks, shared with the hook ingest when wired together, so a turn's
        # run commit here can't race a hook reserving the same run. Its own registry when the tailer runs standalone.
        self.locks = locks if locks is not None else SessionLocks()
        self.sessions: dict[str, TailState] = {}
        # Each session's subagents that started and have not settled, as its hooks
        # report them. An interrupted one settles here, where its marker is read.
        self.working_subagents: dict[str, list[str]] = {}
        # Sessions whose `SessionEnd` fired and that no prompt has reopened: a tail
        # that attaches to one has only its last lines to drain.
        self.ended: set[str] = set()

    async def stop_turn(self, session_id: str, prompt_id: str | None) -> None:
        """The turn just stopped — its `Stop` hook fired: drain it now instead of
        waiting for the next prompt line to close it.

        The stream route relays `finalize` on `stop_event`, the client ships its
        final lines and answers `eof`, and `finish_remote` commits the stopped turn —
        the tail process exits, and the next prompt's launcher spawns a fresh one.
        Scoped by `prompt_id` so nothing newer than the stopped turn ever commits
        early; without one there is nothing to scope, and the turn keeps its old
        boundary. A session no stream covers has nothing to drain.
        """
        if prompt_id is None:
            return
        state = self.sessions.get(session_id)
        if state is None:
            return
        state.drain_turn = prompt_id
        state.stop_event.set()

    async def finalize(self, session_id: str) -> None:
        """End a session (`SessionEnd`): relay the drain to its stream — the route
        watches `stop_event` and sends the client `finalize`; the client drains,
        answers `eof`, and `finish_remote` commits the trailing turns and sets
        `drained`. The wait is bounded: a client that is gone leaves its turns for
        the next connect, and the SessionEnd hook must not hang on it. A session no
        stream covers has nothing to finalize."""
        self.ended.add(session_id)
        state = self.sessions.get(session_id)
        if state is None:
            return
        state.stop_event.set()
        try:
            await asyncio.wait_for(state.drained.wait(), REMOTE_DRAIN_TIMEOUT)
        except TimeoutError:
            logger.warning(
                "session %s: remote tail did not drain within %ss; its trailing "
                "turns are left for the next connect to recover",
                session_id,
                REMOTE_DRAIN_TIMEOUT,
            )

    async def shutdown(self) -> None:
        self.sessions.clear()

    async def attach_remote(
        self,
        session_id: str,
        transcript_path: Path,
        sender: UserProfile,
        address: ChannelAddress,
        impulses: ObjectSendStream[Impulse],
    ) -> tuple[TailState, dict[UUID7, int]]:
        """Register a streamed session and answer where each of its files resumes.

        The offsets are recomputed from the committed runs, per file: the session
        and each known subagent under its own conversation UUID. The client asks
        again on reconnect. A lingering registration (its client died without a close) is
        replaced; the dead route feeds the state object it attached, and its commits
        are idempotent.
        """
        state = TailState(
            session_id=session_id,
            transcript_path=transcript_path,
            stop_event=asyncio.Event(),
            sender=sender,
            address=address,
            impulses=impulses,
        )
        await self.prepare(state)

        conversation = state.conversation
        if conversation is None:
            raise RuntimeError(f"session {session_id} prepared without a conversation")
        state.offset = max(
            (
                run.end_offset or 0
                for run in conversation.runs
                if isinstance(run, ExternalAgentRun)
            ),
            default=0,
        )
        offsets: dict[UUID7, int] = {conversation.id: state.offset}
        for child in await self.conversation_manager.subagents(conversation.id):
            if not child.subagent_id:
                continue
            tail = self.subagent_tail(state, child.subagent_id)
            tail.conversation = child
            tail.recorded = child.native_run_ids
            tail.offset = max(
                (
                    run.end_offset or 0
                    for run in child.runs
                    if isinstance(run, ExternalAgentRun)
                ),
                default=0,
            )
            state.known_spawns.update(
                (run.parent_tool_call_id, child.subagent_id)
                for run in child.runs
                if run.parent_tool_call_id
            )
            offsets[child.id] = tail.offset
        state.spawn_agents.update(state.known_spawns)
        self.sessions[session_id] = state
        logger.info(
            "session %s: remote tail attached, resuming at %s", session_id, offsets
        )
        return state, offsets

    async def feed_remote(
        self, state: TailState, agent_id: str | None, raw: str, start: int, end: int
    ) -> None:
        """Advance a remote session by one framed line — the pumps' per-line body,
        against offsets the client measured in its own file. Takes the state rather
        than a session id so a superseded connection keeps feeding the state it
        attached, never whoever registered after it."""
        if agent_id is None:
            state.offset = end
            line = self.parse_line(raw, state.session_id)
            if state.open_turn is not None and state.open_turn.native is not None:
                state.open_turn.native.replay = end <= state.catchup_end
            if line is not None:
                await self.process_line(state, line, start, end)
            if state.catchup_end and end >= state.catchup_end:
                state.catchup_end = 0
                if state.open_turn is not None and state.open_turn.native is not None:
                    await state.open_turn.native.caught_up()
                else:
                    await state.impulses.send(Impulse(RunEndedEvent(), state.address))
            return
        tail = self.subagent_tail(state, agent_id)
        if tail.conversation is None:
            await self.prepare_subagent(state, tail)
        tail.offset = end
        line = self.parse_line(raw, state.session_id)
        if line is not None:
            await self.process_subagent_line(state, tail, line, start, end)

    async def finish_remote(self, state: TailState) -> None:
        """A remote session's clean end — the client drained to EOF and said `eof`.

        After the session's own end (`finalize` relayed at `SessionEnd`, or the idle
        drain), commit everything still open. After a relayed `Stop` (`drain_turn`
        set), commit only the stopped turn: a prompt queued into the drain window is
        left open to re-stream whole on the next connect, and subagent turns keep
        their own boundary — `SubagentStop` commits them, and force-closing here
        would truncate a background child still running across turns. Either way,
        release any finalize waiter and reclaim the registry slot."""
        try:
            if state.drain_turn is None:
                await self.close_turn(state)
                await self.close_subagent_turns(state)
            else:
                turn = state.open_turn
                if turn is not None and turn.prompt_id == state.drain_turn:
                    await self.close_turn(state)
        finally:
            state.drained.set()
            self.detach_remote(state)

    def detach_remote(self, state: TailState) -> None:
        """Drop a remote session's registration without committing anything: the
        connection died mid-stream, so its open turns' bytes were never provably
        complete. The next connect resumes from the committed offsets and re-streams
        them."""
        if self.sessions.get(state.session_id) is state:
            del self.sessions[state.session_id]

    async def prepare(self, state: TailState) -> None:
        """Resolve the session's conversation and seed the committed-turn guard from it,
        so a resume never re-commits a run the last run already wrote."""
        state.conversation = await self.ensure_session(state.session_id)
        state.recorded = state.conversation.native_run_ids
        previous = max(
            (
                run
                for run in state.conversation.runs
                if isinstance(run, ExternalAgentRun) and run.end_offset is not None
            ),
            key=lambda run: run.end_offset or 0,
            default=None,
        )
        state.last_item_id = previous.last_line_uuid if previous is not None else None

    async def ensure_session(self, session_id: str) -> Conversation:
        """Map a native Claude session id to its Octomate home — the session's thread and
        the conversation hanging off it — creating either if this is its first sighting."""
        thread = await self.thread_manager.ensure(
            ThreadKey(
                channel_tentacle_id=self.agent_tentacle_id,
                chat_type="thread",
                chat_id=session_id,
            ),
            native=True,
        )
        return await self.conversation_manager.ensure(
            thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
        )

    @staticmethod
    def parse_line(raw: str | bytes, session_id: str) -> TranscriptLine | None:
        """One typed line, or None for a blank / malformed / unmodeled one — skipped
        but never allowed to wedge ingest; the caller advances its cursor either way."""
        stripped = raw.strip()
        if not stripped:
            return None
        try:
            return transcript_line_adapter.validate_json(stripped)
        except ValidationError:
            logger.debug(
                "skipping unmodeled/malformed transcript line in session %s",
                session_id,
            )
            return None

    async def process_line(
        self, state: TailState, line: TranscriptLine, start: int, end: int
    ) -> None:
        """Route one typed line: a `prompt_source` user line opens a turn (closing the
        previous one); other user (tool-result) and assistant lines fold into the open
        turn, and a `stop_hook_summary` closes it. Inline `is_sidechain` lines are
        skipped — transcripts since 2.1.177 keep subagents in their own files
        (`pump_subagents`), so this guards only against an older transcript's inline
        relics."""
        if isinstance(line, TranscriptUserLine):
            if line.is_sidechain:
                return
            if line.is_compact_summary:
                await self.record_compaction(state, line, start, end)
                return
            state.last_item_id = line.uuid
            await self.harvest_subagent_call(state, line)
            if line.prompt_source is not None:
                await self.close_turn(state)
                await self.record_permission_mode(state, line.permission_mode)
                state.open_turn = await self.begin_turn(state, line, start, end)
            elif state.open_turn is not None:
                await self.fold(state, line, end)
            if state.open_turn is not None and state.open_turn.interrupted:
                await self.close_turn(state)
        elif isinstance(line, TranscriptAssistantLine):
            if line.is_sidechain:
                return
            state.last_item_id = line.uuid
            if state.open_turn is not None:
                await self.fold(state, line, end)
        elif isinstance(line, TranscriptSystemLine):
            state.omitted_uuids.add(line.uuid)
            if line.subtype == "compact_boundary" and not line.is_sidechain:
                await self.record_compaction(state, line, start, end)
                return
            # Claude writes it once the turn's `Stop` hooks have run, delivered or
            # not: a server down through the stop never hears the hook.
            if line.subtype == "stop_hook_summary" and not line.is_sidechain:
                await self.close_turn(state)
        elif isinstance(line, TranscriptAiTitleLine):
            await self.record_title(state, line.ai_title)
        elif isinstance(line, TranscriptAttachmentLine) and not line.is_sidechain:
            await self.fold_attachment(state, line, end)

    async def record_compaction(
        self,
        state: TailState,
        line: TranscriptSystemLine | TranscriptUserLine,
        start: int,
        end: int,
        *,
        tail: SubagentTail | None = None,
    ) -> None:
        """Keep the boundary and its following summary outside model runs and chat."""
        conversation = tail.conversation if tail is not None else state.conversation
        assert conversation is not None
        messages: list[ModelRequest | ModelResponse] = []
        trigger: CompactionTrigger = "unknown"
        if isinstance(line, TranscriptSystemLine):
            if line.compact_metadata is None:
                return
            native_compaction_id = line.uuid
            trigger = line.compact_metadata.trigger
            (tail or state).compact_metadata = line.compact_metadata
        else:
            native_compaction_id = line.parent_uuid
            if native_compaction_id is None:
                return
            metadata = (tail or state).compact_metadata
            context = (
                metadata.context(
                    line.uuid,
                    (tail or state).last_item_id,
                    (tail or state).omitted_uuids,
                )
                if metadata is not None
                else None
            )
            messages.append(
                ModelRequest(
                    parts=[
                        UserPromptPart(
                            prompt_text(line.message), timestamp=line.timestamp
                        )
                    ],
                    timestamp=line.timestamp,
                    metadata={
                        "native_item_ids": [line.uuid],
                        **(
                            {"compaction_context": context.model_dump(mode="json")}
                            if context is not None
                            else {}
                        ),
                    },
                )
            )
        await self.conversation_manager.record_external_compaction(
            conversation,
            native_session_id=state.session_id,
            native_compaction_id=native_compaction_id,
            trigger=trigger,
            source=str(tail.path if tail is not None else state.transcript_path),
            start_offset=start,
            end_offset=end,
            happened_at=line.timestamp,
            messages=messages,
        )
        if isinstance(line, TranscriptUserLine):
            (tail or state).last_item_id = line.uuid
            (tail or state).compactions_pending = True
            turn = (tail or state).open_turn
            if turn is None:
                await self.conversation_manager.record_native_memberships(
                    conversation, state.session_id
                )
                (tail or state).compactions_pending = False

    async def record_title(self, state: TailState, title: str) -> None:
        """Carry the name Claude gave this session onto the rows that show it.

        The transcript restates the title on every turn and revises it as the work
        turns out to be about something else, so the comparison — not the write —
        is what runs per line. The thread takes it too: a native thread is its
        session, and a name about the work beats the line the thread opened with.
        """
        conversation = state.conversation
        if conversation is None or conversation.name == title.strip():
            return
        await self.conversation_manager.set_name(conversation, title)
        thread = await self.thread_manager.ensure(
            ThreadKey(
                channel_tentacle_id=self.agent_tentacle_id,
                chat_type="thread",
                chat_id=state.session_id,
            )
        )
        await self.thread_manager.rename(thread, title)

    async def harvest_subagent_call(
        self, state: TailState, line: TranscriptUserLine
    ) -> None:
        """Record the spawn as soon as the parent's result identifies the child and
        tool call. Its transcript can arrive on a different connection."""
        result = line.tool_use_result
        if not isinstance(result, dict):
            return
        agent_id = result.get("agentId")
        if not isinstance(agent_id, str) or not agent_id:
            return
        content = line.message.content
        if not isinstance(content, list):
            return
        tool_use_id = next(
            (
                block.get("tool_use_id")
                for block in content
                if isinstance(block, dict) and block.get("type") == "tool_result"
            ),
            None,
        )
        if not isinstance(tool_use_id, str):
            return
        await self.record_spawn(
            state, self.subagent_tail(state, agent_id), line.prompt_id, tool_use_id
        )

    async def record_spawn(
        self, state: TailState, tail: SubagentTail, prompt_id: str, call_id: str
    ) -> None:
        """Reserve the child's run under the parent's turn, linked to the call it
        answers. Once per call: two sources can name the same one."""
        async with self.locks.hold(state.session_id):
            if call_id in state.spawn_agents:
                return
            conversation = tail.conversation or await self.prepare_subagent(state, tail)
            name = state.spawn_names.pop(call_id, None)
            if name and not conversation.name:
                await self.conversation_manager.set_name(conversation, name)
            await self.conversation_manager.record_external_run(
                conversation,
                run_id=f"{tail.agent_id}:{prompt_id}",
                native_session_id=tail.agent_id,
                parent_run_id=prompt_id,
                parent_tool_call_id=call_id,
            )
            state.spawn_agents[call_id] = tail.agent_id

    async def fold(
        self,
        state: TailState,
        line: TranscriptAssistantLine | TranscriptUserLine,
        end: int,
    ) -> None:
        """Fold a line into the open turn: consume it (pushing its live events) and
        extend the turn's byte range and provenance to cover it."""
        turn = state.open_turn
        if turn is None:
            raise RuntimeError(f"session {state.session_id}: no open turn to fold into")
        if turn.native is None:
            return
        written = len(turn.accumulator.messages)
        if isinstance(line, TranscriptUserLine) and (text := prompt_text(line.message)):
            turn.interrupted = text.startswith(INTERRUPTED)
            await turn.native.prompt(
                message_id=line.uuid,
                text=prompt_content(text, line.origin),
                timestamp=line.timestamp,
                metadata={"native_item_ids": [line.uuid]},
                actor_kind="system" if turn.interrupted else "human",
            )
        await turn.native.fold(turn.accumulator.consume(line))
        stamp(turn.accumulator.messages[written:], line.timestamp)
        turn.end_offset = end
        turn.last_line_uuid = line.uuid
        if isinstance(line, TranscriptAssistantLine):
            await self.observe_subagent_calls(state, line)

    async def observe_subagent_calls(
        self, state: TailState, line: TranscriptAssistantLine
    ) -> None:
        """Keep the task title until the child is identified, and announce a
        previously recorded child again when its spawning call is re-streamed."""
        working = self.working_subagents.get(state.session_id, [])
        for block in line.message.content:
            if not isinstance(block, ToolUseBlock):
                continue
            if name := subagent_name(block):
                agent_id = state.spawn_agents.get(block.id)
                if agent_id is None:
                    state.spawn_names[block.id] = name
                    continue
                child = state.subagents[agent_id].conversation
                if child is not None and not child.name:
                    await self.conversation_manager.set_name(child, name)
            if block.id not in state.known_spawns:
                continue
            agent_id = state.known_spawns[block.id]
            kind = block.input.get("subagent_type")
            await state.impulses.send(
                Impulse(
                    SubagentStartedEvent(
                        invocation_id=agent_id,
                        kind="subagent",
                        name=kind if isinstance(kind, str) else "Claude",
                    ),
                    state.address,
                    replay=state.offset <= state.catchup_end,
                )
            )
            if agent_id not in working:
                await state.impulses.send(
                    Impulse(
                        SubagentSettledEvent(
                            invocation_id=agent_id, status="completed"
                        ),
                        state.address,
                        replay=state.offset <= state.catchup_end,
                    )
                )

    async def fold_attachment(
        self, state: TailState, line: TranscriptAttachmentLine, end: int
    ) -> None:
        """Record what another agent session said while the turn ran. Claude queues a
        foreground subagent's hand-back into the turn as an attachment, where a
        background one's opens a turn as a prompt line. Any other attachment is the
        harness's own context and is left out."""
        turn = state.open_turn
        attached = line.attachment
        if turn is None or turn.native is None or not isinstance(attached.prompt, str):
            return
        if attached.origin is None or attached.origin.kind != "peer":
            return
        text = prompt_content(attached.prompt, attached.origin)
        if not isinstance(text, TextContent):
            return
        await turn.native.prompt(
            message_id=line.uuid,
            text=text,
            timestamp=line.timestamp,
            metadata={"native_item_ids": [line.uuid]},
        )
        turn.end_offset = end

    async def record_permission_mode(
        self, state: TailState, permission_mode: str | None
    ) -> None:
        """Keep the conversation's posture at what the session's own transcript says.

        Every prompt line carries the mode that turn ran under, so a ⇧⇥ in the client
        reaches Octomate on the operator's next message. Observed, never set: nothing
        here can change a running client's mode, and the console shows it read-only.

        A mode Claude has that this build's vocabulary does not is skipped rather than
        stored — the column is validated on read, so an unknown one would take the
        conversation out of circulation instead of merely being unrecognized.
        """
        conversation = state.conversation
        if conversation is None or permission_mode is None:
            return
        if permission_mode == conversation.permission_mode:
            return
        if not is_claude_mode(permission_mode):
            logger.debug(
                "session %s reports permission mode %r, which this build does not "
                "model; leaving the conversation at %r",
                state.session_id,
                permission_mode,
                conversation.permission_mode,
            )
            return
        await self.conversation_manager.set_permission_mode(
            conversation, permission_mode
        )

    async def begin_turn(
        self, state: TailState, line: TranscriptUserLine, start: int, end: int
    ) -> OpenTurn:
        """Open the native lifecycle at the transcript's prompt boundary."""
        accumulator = ClaudeRunAccumulator()
        native = await NativeTurn.open(
            run_id=line.prompt_id,
            recorded=state.recorded,
            conversations=self.conversation_manager,
            threads=self.thread_manager,
            locks=self.locks,
            address=state.address,
            sender=state.sender,
            impulses=state.impulses,
            messages=accumulator.messages,
            replay=end <= state.catchup_end,
        )
        text = prompt_text(line.message)
        if native is not None:
            await native.prompt(
                message_id=line.prompt_id,
                text=prompt_content(text, line.origin),
                timestamp=line.timestamp,
                metadata={"native_item_ids": [line.uuid]},
            )
        return OpenTurn(
            prompt_id=line.prompt_id,
            source=line.entrypoint,
            cwd=line.cwd,
            start_offset=start,
            end_offset=end,
            accumulator=accumulator,
            last_line_uuid=line.uuid,
            permission_mode=line.permission_mode,
            native=native,
        )

    async def close_turn(self, state: TailState) -> None:
        """Commit the open turn as an `ExternalAgentRun` with its byte range, then bind
        the turn's human-ledger rows to it. Idempotent by `prompt_id`, so a re-driven
        overlap after a resume is a safe no-op. Held under the session lock so the commit
        cannot race a hook reserving the same turn.

        A commit that cannot be made propagates instead of being skipped past. A
        reconnect resumes from the last committed turn's `end_offset`, which only
        points at the right bytes while the committed turns are the *earliest* ones:
        skipping a turn and streaming on would let a later turn push that mark past
        the gap, stranding the skipped turn where no re-stream could reach it.
        Failing keeps the mark honest — the next connect re-streams the turn from
        there and commits it.
        """
        turn = state.open_turn
        state.open_turn = None
        if turn is None or turn.native is None:
            if state.compactions_pending and state.conversation is not None:
                await self.conversation_manager.record_native_memberships(
                    state.conversation, state.session_id
                )
                state.compactions_pending = False
            return
        conversation = state.conversation
        if conversation is None:
            raise RuntimeError(f"session {state.session_id} has no conversation")
        with claude_logfire.span(
            "claude.tailer.commit_turn {prompt_id} [{session_id}]",
            prompt_id=turn.prompt_id,
            session_id=state.session_id,
            start_offset=turn.start_offset,
            end_offset=turn.end_offset,
            messages=len(turn.accumulator.messages),
        ) as span:
            async with self.locks.hold(
                state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
            ):
                run = await self.conversation_manager.record_external_run(
                    conversation,
                    run_id=turn.prompt_id,
                    messages=turn.accumulator.messages,
                    name=self.agent_tentacle_id,
                    model_name=turn.accumulator.model_name,
                    context_window=turn.accumulator.context_window,
                    context_used=turn.accumulator.context_used,
                    permission_mode=turn.permission_mode,
                    cwd=Path(turn.cwd) if turn.cwd else None,
                    native_session_id=state.session_id,
                    source=turn.source,
                    start_offset=turn.start_offset,
                    end_offset=turn.end_offset,
                    last_line_uuid=turn.last_line_uuid,
                )
                span.set_attribute("committed", run is not None)
                if state.compactions_pending:
                    await self.conversation_manager.record_native_memberships(
                        conversation, state.session_id
                    )
                    state.compactions_pending = False
                await turn.native.close(
                    run,
                    run_id=turn.prompt_id,
                    answer=turn.accumulator.result_text,
                    interrupted=turn.interrupted,
                )
                logger.info(
                    "session %s: turn %s synced — %d messages, bytes %d-%d",
                    state.session_id,
                    turn.prompt_id,
                    len(turn.accumulator.messages),
                    turn.start_offset,
                    turn.end_offset,
                )

    @staticmethod
    def subagent_tail(state: TailState, agent_id: str) -> SubagentTail:
        tail = state.subagents.get(agent_id)
        if tail is None:
            tail = SubagentTail(
                agent_id=agent_id,
                path=state.subagents_dir / f"agent-{agent_id}.jsonl",
            )
            state.subagents[agent_id] = tail
        return tail

    async def finish_subagent(
        self, session_id: str, agent_id: str, *, final_answer: str | None = None
    ) -> str:
        """Drain and commit one subagent on its `SubagentStop` — the child's
        `finalize`, which a Claude child needs: its turns frame on promptId change,
        so nothing in its own file closes the last one. The hook is synchronous but
        the transcript writer is not: the final answer line races it (measured:
        usually loses by ~1-2KB). The child's lines arrive through `feed_remote` on
        their own; when the event names the answer, wait until the stream yields it,
        bounded so a mismatch can never hang the pipe — `tail.offset` says whether
        the writer has gone quiet. A session no stream covers has nothing to
        settle. Returns the answer the committed turn ended on."""
        state = self.sessions.get(session_id)
        if state is None:
            return ""
        if state.conversation is None:
            await self.prepare(state)
        tail = self.subagent_tail(state, agent_id)
        # The turn this stop is for. If a resume arrives inside the settle window,
        # the stream itself closes this turn on the promptId change and opens the
        # next — which must NOT be committed by this stop, mid-flight.
        target = tail.open_turn
        deadline = monotonic() + SUBAGENT_SETTLE_TIMEOUT
        quiet = 0
        while not self.subagent_settled(tail, final_answer):
            if quiet >= 2:
                break  # writer went silent: the file is as final as it gets
            if monotonic() >= deadline:
                logger.warning(
                    "session %s: subagent %s kept writing past the settle window "
                    "without yielding its announced answer; committing what it "
                    "reached",
                    session_id,
                    agent_id,
                )
                break
            before = tail.offset
            await asyncio.sleep(SUBAGENT_SETTLE_POLL)
            quiet = quiet + 1 if tail.offset == before else 0
        turn = target or tail.open_turn
        if target is None or tail.open_turn is target:
            await self.close_subagent_turn(state, tail)
        return turn.accumulator.result_text if turn is not None else ""

    @staticmethod
    def subagent_settled(tail: SubagentTail, final_answer: str | None) -> bool:
        """The fast path: the drained turn already carries the exact answer the
        stop event announced. Divergence (a truncated or differently-joined hook
        payload — no contract promises byte equality) is not an error: the caller's
        byte-quiescence fallback settles those, so strictness here only ever costs
        one extra poll beat, never a wrong commit."""
        if final_answer is None:
            return False  # nothing announced; quiescence decides
        turn = tail.open_turn
        if turn is None:
            return False
        return turn.accumulator.result_text.strip() == final_answer.strip()

    async def prepare_subagent(
        self, state: TailState, tail: SubagentTail
    ) -> Conversation:
        """Resolve the child's conversation under the session's thread and seed its
        committed-turn guard — the first time this child's lines are fed."""
        parent = state.conversation
        if parent is None:
            raise RuntimeError(f"session {state.session_id} has no conversation")
        tail.conversation = await self.conversation_manager.ensure(
            parent.thread_id,
            agent_tentacle_id=self.agent_tentacle_id,
            native=True,
            subagent_id=tail.agent_id,
            parent_conversation_id=parent.id,
        )
        tail.recorded = tail.conversation.native_run_ids
        previous = max(
            (
                run
                for run in tail.conversation.runs
                if isinstance(run, ExternalAgentRun) and run.end_offset is not None
            ),
            key=lambda run: run.end_offset or 0,
            default=None,
        )
        tail.last_item_id = previous.last_line_uuid if previous is not None else None
        return tail.conversation

    async def process_subagent_line(
        self,
        state: TailState,
        tail: SubagentTail,
        line: TranscriptLine,
        start: int,
        end: int,
    ) -> None:
        """Frame a subagent's turns on `promptId` change — the only marker its file
        carries (`promptSource` is absent, and every line is `is_sidechain`, so
        neither parent rule applies). Each turn's `promptId` is the *parent* turn
        that drove it; a resumed subagent opens its next turn on whatever user line
        arrives first, which is measured to be a tool result, not a prompt.

        A result stays with its call. A background child works on while its parent
        takes the next prompt, and the results it writes then carry that prompt's
        id: splitting there would cut one piece of work in two."""
        if (
            isinstance(line, TranscriptSystemLine)
            and line.subtype == "compact_boundary"
        ):
            await self.record_compaction(state, line, start, end, tail=tail)
            return
        if isinstance(line, TranscriptUserLine) and line.is_compact_summary:
            await self.record_compaction(state, line, start, end, tail=tail)
            return
        if isinstance(line, TranscriptUserLine | TranscriptAssistantLine):
            tail.last_item_id = line.uuid
        elif isinstance(line, TranscriptSystemLine):
            tail.omitted_uuids.add(line.uuid)
        if isinstance(line, TranscriptUserLine) and start == 0 and tail.call_id:
            # An interrupted call's result never names this child; its meta file did.
            await self.record_spawn(state, tail, line.prompt_id, tail.call_id)
        if isinstance(line, TranscriptUserLine):
            turn = tail.open_turn
            if turn is not None and (
                line.prompt_id == turn.prompt_id
                or line.source_tool_assistant_uuid in turn.calls
            ):
                self.fold_subagent(tail, line, end)
            else:
                await self.close_subagent_turn(state, tail)
                tail.open_turn = self.begin_subagent_turn(line, start, end)
            working = self.working_subagents.get(state.session_id, [])
            if (
                prompt_text(line.message).startswith(INTERRUPTED)
                and tail.agent_id in working
            ):
                # Claude writes the marker into the child's own file and fires no hook.
                await self.close_subagent_turn(state, tail)
                working.remove(tail.agent_id)
                await state.impulses.send(
                    Impulse(
                        SubagentSettledEvent(
                            invocation_id=tail.agent_id, status="cancelled"
                        ),
                        state.address,
                        replay=end <= tail.catchup_end,
                    )
                )
        elif isinstance(line, TranscriptAssistantLine):
            if tail.open_turn is not None:
                self.fold_subagent(tail, line, end)

    def begin_subagent_turn(
        self, line: TranscriptUserLine, start: int, end: int
    ) -> OpenTurn:
        accumulator = ClaudeRunAccumulator()
        text = prompt_text(line.message)
        if text:
            accumulator.begin(text)
            accumulator.messages[0].metadata = {"native_item_ids": [line.uuid]}
        # The opener may itself carry tool results (a resumed subagent's turn opens on
        # one); consuming is a no-op for a plain prompt line.
        for _ in accumulator.consume(line):
            pass
        stamp(accumulator.messages, line.timestamp)
        return OpenTurn(
            prompt_id=line.prompt_id,
            source=line.entrypoint,
            cwd=line.cwd,
            start_offset=start,
            end_offset=end,
            accumulator=accumulator,
            last_line_uuid=line.uuid,
            permission_mode=line.permission_mode,
        )

    def fold_subagent(
        self,
        tail: SubagentTail,
        line: TranscriptAssistantLine | TranscriptUserLine,
        end: int,
    ) -> None:
        """Fold a line into the child's open turn. Events are consumed, not emitted:
        the live stream is the parent timeline's; fanning child events into it would
        interleave two timelines under one label."""
        turn = tail.open_turn
        if turn is None:
            raise RuntimeError(f"subagent {tail.agent_id}: no open turn to fold into")
        written = len(turn.accumulator.messages)
        for _ in turn.accumulator.consume(line):
            pass
        stamp(turn.accumulator.messages[written:], line.timestamp)
        turn.end_offset = end
        turn.last_line_uuid = line.uuid
        if isinstance(line, TranscriptAssistantLine):
            turn.calls.add(line.uuid)

    async def close_subagent_turn(self, state: TailState, tail: SubagentTail) -> None:
        """Commit the child's open turn as a child run: keyed `<agentId>:<promptId>`
        (which subagent, which parent turn — a bare `promptId` would collide with the
        parent run it belongs to), linked by `parent_run_id` = that `promptId` and the
        harvested spawning call. A subagent has no human prompt or answer, so it never
        touches the ledger."""
        turn = tail.open_turn
        tail.open_turn = None
        if turn is None:
            return
        run_id = f"{tail.agent_id}:{turn.prompt_id}"
        if run_id in tail.recorded or not turn.accumulator.messages:
            return
        conversation = tail.conversation
        if conversation is None:
            raise RuntimeError(f"subagent {tail.agent_id} has no conversation")
        with claude_logfire.span(
            "claude.tailer.commit_subagent_turn {run_id} [{session_id}]",
            run_id=run_id,
            session_id=state.session_id,
            start_offset=turn.start_offset,
            end_offset=turn.end_offset,
            messages=len(turn.accumulator.messages),
        ) as span:
            async with self.locks.hold(
                state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
            ):
                run = await self.conversation_manager.record_external_run(
                    conversation,
                    run_id=run_id,
                    messages=turn.accumulator.messages,
                    name=self.agent_tentacle_id,
                    model_name=turn.accumulator.model_name,
                    context_window=turn.accumulator.context_window,
                    context_used=turn.accumulator.context_used,
                    permission_mode=turn.permission_mode,
                    cwd=Path(turn.cwd) if turn.cwd else None,
                    native_session_id=tail.agent_id,
                    source=turn.source,
                    start_offset=turn.start_offset,
                    end_offset=turn.end_offset,
                    last_line_uuid=turn.last_line_uuid,
                    parent_run_id=turn.prompt_id,
                )
                span.set_attribute("committed", run is not None)
                if run is None:
                    return
                tail.recorded.add(run_id)
                if tail.compactions_pending:
                    await self.conversation_manager.record_native_memberships(
                        conversation, state.session_id
                    )
                    tail.compactions_pending = False
                logger.info(
                    "session %s: subagent %s turn %s synced — %d messages, bytes %d-%d",
                    state.session_id,
                    tail.agent_id,
                    turn.prompt_id,
                    len(turn.accumulator.messages),
                    turn.start_offset,
                    turn.end_offset,
                )

    async def close_subagent_turns(self, state: TailState) -> None:
        """Commit every child's trailing open turn — the subagent counterpart of the
        final `close_turn`, at a session-ending drain (`finish_remote`)."""
        for tail in state.subagents.values():
            await self.close_subagent_turn(state, tail)

agent_tentacle_id instance-attribute

agent_tentacle_id: str = agent_tentacle_id

conversation_manager instance-attribute

conversation_manager = conversation_manager

thread_manager instance-attribute

thread_manager = thread_manager

locks instance-attribute

locks = locks if locks is not None else SessionLocks()

sessions instance-attribute

sessions: dict[str, TailState] = {}

working_subagents instance-attribute

working_subagents: dict[str, list[str]] = {}

ended instance-attribute

ended: set[str] = set()

stop_turn async

stop_turn(session_id: str, prompt_id: str | None) -> None

The turn just stopped — its Stop hook fired: drain it now instead of waiting for the next prompt line to close it.

The stream route relays finalize on stop_event, the client ships its final lines and answers eof, and finish_remote commits the stopped turn — the tail process exits, and the next prompt's launcher spawns a fresh one. Scoped by prompt_id so nothing newer than the stopped turn ever commits early; without one there is nothing to scope, and the turn keeps its old boundary. A session no stream covers has nothing to drain.

Source code in octomate/tentacles/claude/tailer.py
async def stop_turn(self, session_id: str, prompt_id: str | None) -> None:
    """The turn just stopped — its `Stop` hook fired: drain it now instead of
    waiting for the next prompt line to close it.

    The stream route relays `finalize` on `stop_event`, the client ships its
    final lines and answers `eof`, and `finish_remote` commits the stopped turn —
    the tail process exits, and the next prompt's launcher spawns a fresh one.
    Scoped by `prompt_id` so nothing newer than the stopped turn ever commits
    early; without one there is nothing to scope, and the turn keeps its old
    boundary. A session no stream covers has nothing to drain.
    """
    if prompt_id is None:
        return
    state = self.sessions.get(session_id)
    if state is None:
        return
    state.drain_turn = prompt_id
    state.stop_event.set()

finalize async

finalize(session_id: str) -> None

End a session (SessionEnd): relay the drain to its stream — the route watches stop_event and sends the client finalize; the client drains, answers eof, and finish_remote commits the trailing turns and sets drained. The wait is bounded: a client that is gone leaves its turns for the next connect, and the SessionEnd hook must not hang on it. A session no stream covers has nothing to finalize.

Source code in octomate/tentacles/claude/tailer.py
async def finalize(self, session_id: str) -> None:
    """End a session (`SessionEnd`): relay the drain to its stream — the route
    watches `stop_event` and sends the client `finalize`; the client drains,
    answers `eof`, and `finish_remote` commits the trailing turns and sets
    `drained`. The wait is bounded: a client that is gone leaves its turns for
    the next connect, and the SessionEnd hook must not hang on it. A session no
    stream covers has nothing to finalize."""
    self.ended.add(session_id)
    state = self.sessions.get(session_id)
    if state is None:
        return
    state.stop_event.set()
    try:
        await asyncio.wait_for(state.drained.wait(), REMOTE_DRAIN_TIMEOUT)
    except TimeoutError:
        logger.warning(
            "session %s: remote tail did not drain within %ss; its trailing "
            "turns are left for the next connect to recover",
            session_id,
            REMOTE_DRAIN_TIMEOUT,
        )

shutdown async

shutdown() -> None
Source code in octomate/tentacles/claude/tailer.py
async def shutdown(self) -> None:
    self.sessions.clear()

attach_remote async

attach_remote(
    session_id: str,
    transcript_path: Path,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]

Register a streamed session and answer where each of its files resumes.

The offsets are recomputed from the committed runs, per file: the session and each known subagent under its own conversation UUID. The client asks again on reconnect. A lingering registration (its client died without a close) is replaced; the dead route feeds the state object it attached, and its commits are idempotent.

Source code in octomate/tentacles/claude/tailer.py
async def attach_remote(
    self,
    session_id: str,
    transcript_path: Path,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]:
    """Register a streamed session and answer where each of its files resumes.

    The offsets are recomputed from the committed runs, per file: the session
    and each known subagent under its own conversation UUID. The client asks
    again on reconnect. A lingering registration (its client died without a close) is
    replaced; the dead route feeds the state object it attached, and its commits
    are idempotent.
    """
    state = TailState(
        session_id=session_id,
        transcript_path=transcript_path,
        stop_event=asyncio.Event(),
        sender=sender,
        address=address,
        impulses=impulses,
    )
    await self.prepare(state)

    conversation = state.conversation
    if conversation is None:
        raise RuntimeError(f"session {session_id} prepared without a conversation")
    state.offset = max(
        (
            run.end_offset or 0
            for run in conversation.runs
            if isinstance(run, ExternalAgentRun)
        ),
        default=0,
    )
    offsets: dict[UUID7, int] = {conversation.id: state.offset}
    for child in await self.conversation_manager.subagents(conversation.id):
        if not child.subagent_id:
            continue
        tail = self.subagent_tail(state, child.subagent_id)
        tail.conversation = child
        tail.recorded = child.native_run_ids
        tail.offset = max(
            (
                run.end_offset or 0
                for run in child.runs
                if isinstance(run, ExternalAgentRun)
            ),
            default=0,
        )
        state.known_spawns.update(
            (run.parent_tool_call_id, child.subagent_id)
            for run in child.runs
            if run.parent_tool_call_id
        )
        offsets[child.id] = tail.offset
    state.spawn_agents.update(state.known_spawns)
    self.sessions[session_id] = state
    logger.info(
        "session %s: remote tail attached, resuming at %s", session_id, offsets
    )
    return state, offsets

feed_remote async

feed_remote(
    state: TailState,
    agent_id: str | None,
    raw: str,
    start: int,
    end: int,
) -> None

Advance a remote session by one framed line — the pumps' per-line body, against offsets the client measured in its own file. Takes the state rather than a session id so a superseded connection keeps feeding the state it attached, never whoever registered after it.

Source code in octomate/tentacles/claude/tailer.py
async def feed_remote(
    self, state: TailState, agent_id: str | None, raw: str, start: int, end: int
) -> None:
    """Advance a remote session by one framed line — the pumps' per-line body,
    against offsets the client measured in its own file. Takes the state rather
    than a session id so a superseded connection keeps feeding the state it
    attached, never whoever registered after it."""
    if agent_id is None:
        state.offset = end
        line = self.parse_line(raw, state.session_id)
        if state.open_turn is not None and state.open_turn.native is not None:
            state.open_turn.native.replay = end <= state.catchup_end
        if line is not None:
            await self.process_line(state, line, start, end)
        if state.catchup_end and end >= state.catchup_end:
            state.catchup_end = 0
            if state.open_turn is not None and state.open_turn.native is not None:
                await state.open_turn.native.caught_up()
            else:
                await state.impulses.send(Impulse(RunEndedEvent(), state.address))
        return
    tail = self.subagent_tail(state, agent_id)
    if tail.conversation is None:
        await self.prepare_subagent(state, tail)
    tail.offset = end
    line = self.parse_line(raw, state.session_id)
    if line is not None:
        await self.process_subagent_line(state, tail, line, start, end)

finish_remote async

finish_remote(state: TailState) -> None

A remote session's clean end — the client drained to EOF and said eof.

After the session's own end (finalize relayed at SessionEnd, or the idle drain), commit everything still open. After a relayed Stop (drain_turn set), commit only the stopped turn: a prompt queued into the drain window is left open to re-stream whole on the next connect, and subagent turns keep their own boundary — SubagentStop commits them, and force-closing here would truncate a background child still running across turns. Either way, release any finalize waiter and reclaim the registry slot.

Source code in octomate/tentacles/claude/tailer.py
async def finish_remote(self, state: TailState) -> None:
    """A remote session's clean end — the client drained to EOF and said `eof`.

    After the session's own end (`finalize` relayed at `SessionEnd`, or the idle
    drain), commit everything still open. After a relayed `Stop` (`drain_turn`
    set), commit only the stopped turn: a prompt queued into the drain window is
    left open to re-stream whole on the next connect, and subagent turns keep
    their own boundary — `SubagentStop` commits them, and force-closing here
    would truncate a background child still running across turns. Either way,
    release any finalize waiter and reclaim the registry slot."""
    try:
        if state.drain_turn is None:
            await self.close_turn(state)
            await self.close_subagent_turns(state)
        else:
            turn = state.open_turn
            if turn is not None and turn.prompt_id == state.drain_turn:
                await self.close_turn(state)
    finally:
        state.drained.set()
        self.detach_remote(state)

detach_remote

detach_remote(state: TailState) -> None

Drop a remote session's registration without committing anything: the connection died mid-stream, so its open turns' bytes were never provably complete. The next connect resumes from the committed offsets and re-streams them.

Source code in octomate/tentacles/claude/tailer.py
def detach_remote(self, state: TailState) -> None:
    """Drop a remote session's registration without committing anything: the
    connection died mid-stream, so its open turns' bytes were never provably
    complete. The next connect resumes from the committed offsets and re-streams
    them."""
    if self.sessions.get(state.session_id) is state:
        del self.sessions[state.session_id]

prepare async

prepare(state: TailState) -> None

Resolve the session's conversation and seed the committed-turn guard from it, so a resume never re-commits a run the last run already wrote.

Source code in octomate/tentacles/claude/tailer.py
async def prepare(self, state: TailState) -> None:
    """Resolve the session's conversation and seed the committed-turn guard from it,
    so a resume never re-commits a run the last run already wrote."""
    state.conversation = await self.ensure_session(state.session_id)
    state.recorded = state.conversation.native_run_ids
    previous = max(
        (
            run
            for run in state.conversation.runs
            if isinstance(run, ExternalAgentRun) and run.end_offset is not None
        ),
        key=lambda run: run.end_offset or 0,
        default=None,
    )
    state.last_item_id = previous.last_line_uuid if previous is not None else None

ensure_session async

ensure_session(session_id: str) -> Conversation

Map a native Claude session id to its Octomate home — the session's thread and the conversation hanging off it — creating either if this is its first sighting.

Source code in octomate/tentacles/claude/tailer.py
async def ensure_session(self, session_id: str) -> Conversation:
    """Map a native Claude session id to its Octomate home — the session's thread and
    the conversation hanging off it — creating either if this is its first sighting."""
    thread = await self.thread_manager.ensure(
        ThreadKey(
            channel_tentacle_id=self.agent_tentacle_id,
            chat_type="thread",
            chat_id=session_id,
        ),
        native=True,
    )
    return await self.conversation_manager.ensure(
        thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
    )

parse_line staticmethod

parse_line(
    raw: str | bytes, session_id: str
) -> TranscriptLine | None

One typed line, or None for a blank / malformed / unmodeled one — skipped but never allowed to wedge ingest; the caller advances its cursor either way.

Source code in octomate/tentacles/claude/tailer.py
@staticmethod
def parse_line(raw: str | bytes, session_id: str) -> TranscriptLine | None:
    """One typed line, or None for a blank / malformed / unmodeled one — skipped
    but never allowed to wedge ingest; the caller advances its cursor either way."""
    stripped = raw.strip()
    if not stripped:
        return None
    try:
        return transcript_line_adapter.validate_json(stripped)
    except ValidationError:
        logger.debug(
            "skipping unmodeled/malformed transcript line in session %s",
            session_id,
        )
        return None

process_line async

process_line(
    state: TailState,
    line: TranscriptLine,
    start: int,
    end: int,
) -> None

Route one typed line: a prompt_source user line opens a turn (closing the previous one); other user (tool-result) and assistant lines fold into the open turn, and a stop_hook_summary closes it. Inline is_sidechain lines are skipped — transcripts since 2.1.177 keep subagents in their own files (pump_subagents), so this guards only against an older transcript's inline relics.

Source code in octomate/tentacles/claude/tailer.py
async def process_line(
    self, state: TailState, line: TranscriptLine, start: int, end: int
) -> None:
    """Route one typed line: a `prompt_source` user line opens a turn (closing the
    previous one); other user (tool-result) and assistant lines fold into the open
    turn, and a `stop_hook_summary` closes it. Inline `is_sidechain` lines are
    skipped — transcripts since 2.1.177 keep subagents in their own files
    (`pump_subagents`), so this guards only against an older transcript's inline
    relics."""
    if isinstance(line, TranscriptUserLine):
        if line.is_sidechain:
            return
        if line.is_compact_summary:
            await self.record_compaction(state, line, start, end)
            return
        state.last_item_id = line.uuid
        await self.harvest_subagent_call(state, line)
        if line.prompt_source is not None:
            await self.close_turn(state)
            await self.record_permission_mode(state, line.permission_mode)
            state.open_turn = await self.begin_turn(state, line, start, end)
        elif state.open_turn is not None:
            await self.fold(state, line, end)
        if state.open_turn is not None and state.open_turn.interrupted:
            await self.close_turn(state)
    elif isinstance(line, TranscriptAssistantLine):
        if line.is_sidechain:
            return
        state.last_item_id = line.uuid
        if state.open_turn is not None:
            await self.fold(state, line, end)
    elif isinstance(line, TranscriptSystemLine):
        state.omitted_uuids.add(line.uuid)
        if line.subtype == "compact_boundary" and not line.is_sidechain:
            await self.record_compaction(state, line, start, end)
            return
        # Claude writes it once the turn's `Stop` hooks have run, delivered or
        # not: a server down through the stop never hears the hook.
        if line.subtype == "stop_hook_summary" and not line.is_sidechain:
            await self.close_turn(state)
    elif isinstance(line, TranscriptAiTitleLine):
        await self.record_title(state, line.ai_title)
    elif isinstance(line, TranscriptAttachmentLine) and not line.is_sidechain:
        await self.fold_attachment(state, line, end)

record_compaction async

record_compaction(
    state: TailState,
    line: TranscriptSystemLine | TranscriptUserLine,
    start: int,
    end: int,
    *,
    tail: SubagentTail | None = None,
) -> None

Keep the boundary and its following summary outside model runs and chat.

Source code in octomate/tentacles/claude/tailer.py
async def record_compaction(
    self,
    state: TailState,
    line: TranscriptSystemLine | TranscriptUserLine,
    start: int,
    end: int,
    *,
    tail: SubagentTail | None = None,
) -> None:
    """Keep the boundary and its following summary outside model runs and chat."""
    conversation = tail.conversation if tail is not None else state.conversation
    assert conversation is not None
    messages: list[ModelRequest | ModelResponse] = []
    trigger: CompactionTrigger = "unknown"
    if isinstance(line, TranscriptSystemLine):
        if line.compact_metadata is None:
            return
        native_compaction_id = line.uuid
        trigger = line.compact_metadata.trigger
        (tail or state).compact_metadata = line.compact_metadata
    else:
        native_compaction_id = line.parent_uuid
        if native_compaction_id is None:
            return
        metadata = (tail or state).compact_metadata
        context = (
            metadata.context(
                line.uuid,
                (tail or state).last_item_id,
                (tail or state).omitted_uuids,
            )
            if metadata is not None
            else None
        )
        messages.append(
            ModelRequest(
                parts=[
                    UserPromptPart(
                        prompt_text(line.message), timestamp=line.timestamp
                    )
                ],
                timestamp=line.timestamp,
                metadata={
                    "native_item_ids": [line.uuid],
                    **(
                        {"compaction_context": context.model_dump(mode="json")}
                        if context is not None
                        else {}
                    ),
                },
            )
        )
    await self.conversation_manager.record_external_compaction(
        conversation,
        native_session_id=state.session_id,
        native_compaction_id=native_compaction_id,
        trigger=trigger,
        source=str(tail.path if tail is not None else state.transcript_path),
        start_offset=start,
        end_offset=end,
        happened_at=line.timestamp,
        messages=messages,
    )
    if isinstance(line, TranscriptUserLine):
        (tail or state).last_item_id = line.uuid
        (tail or state).compactions_pending = True
        turn = (tail or state).open_turn
        if turn is None:
            await self.conversation_manager.record_native_memberships(
                conversation, state.session_id
            )
            (tail or state).compactions_pending = False

record_title async

record_title(state: TailState, title: str) -> None

Carry the name Claude gave this session onto the rows that show it.

The transcript restates the title on every turn and revises it as the work turns out to be about something else, so the comparison — not the write — is what runs per line. The thread takes it too: a native thread is its session, and a name about the work beats the line the thread opened with.

Source code in octomate/tentacles/claude/tailer.py
async def record_title(self, state: TailState, title: str) -> None:
    """Carry the name Claude gave this session onto the rows that show it.

    The transcript restates the title on every turn and revises it as the work
    turns out to be about something else, so the comparison — not the write —
    is what runs per line. The thread takes it too: a native thread is its
    session, and a name about the work beats the line the thread opened with.
    """
    conversation = state.conversation
    if conversation is None or conversation.name == title.strip():
        return
    await self.conversation_manager.set_name(conversation, title)
    thread = await self.thread_manager.ensure(
        ThreadKey(
            channel_tentacle_id=self.agent_tentacle_id,
            chat_type="thread",
            chat_id=state.session_id,
        )
    )
    await self.thread_manager.rename(thread, title)

harvest_subagent_call async

harvest_subagent_call(
    state: TailState, line: TranscriptUserLine
) -> None

Record the spawn as soon as the parent's result identifies the child and tool call. Its transcript can arrive on a different connection.

Source code in octomate/tentacles/claude/tailer.py
async def harvest_subagent_call(
    self, state: TailState, line: TranscriptUserLine
) -> None:
    """Record the spawn as soon as the parent's result identifies the child and
    tool call. Its transcript can arrive on a different connection."""
    result = line.tool_use_result
    if not isinstance(result, dict):
        return
    agent_id = result.get("agentId")
    if not isinstance(agent_id, str) or not agent_id:
        return
    content = line.message.content
    if not isinstance(content, list):
        return
    tool_use_id = next(
        (
            block.get("tool_use_id")
            for block in content
            if isinstance(block, dict) and block.get("type") == "tool_result"
        ),
        None,
    )
    if not isinstance(tool_use_id, str):
        return
    await self.record_spawn(
        state, self.subagent_tail(state, agent_id), line.prompt_id, tool_use_id
    )

record_spawn async

record_spawn(
    state: TailState,
    tail: SubagentTail,
    prompt_id: str,
    call_id: str,
) -> None

Reserve the child's run under the parent's turn, linked to the call it answers. Once per call: two sources can name the same one.

Source code in octomate/tentacles/claude/tailer.py
async def record_spawn(
    self, state: TailState, tail: SubagentTail, prompt_id: str, call_id: str
) -> None:
    """Reserve the child's run under the parent's turn, linked to the call it
    answers. Once per call: two sources can name the same one."""
    async with self.locks.hold(state.session_id):
        if call_id in state.spawn_agents:
            return
        conversation = tail.conversation or await self.prepare_subagent(state, tail)
        name = state.spawn_names.pop(call_id, None)
        if name and not conversation.name:
            await self.conversation_manager.set_name(conversation, name)
        await self.conversation_manager.record_external_run(
            conversation,
            run_id=f"{tail.agent_id}:{prompt_id}",
            native_session_id=tail.agent_id,
            parent_run_id=prompt_id,
            parent_tool_call_id=call_id,
        )
        state.spawn_agents[call_id] = tail.agent_id

fold async

fold(
    state: TailState,
    line: TranscriptAssistantLine | TranscriptUserLine,
    end: int,
) -> None

Fold a line into the open turn: consume it (pushing its live events) and extend the turn's byte range and provenance to cover it.

Source code in octomate/tentacles/claude/tailer.py
async def fold(
    self,
    state: TailState,
    line: TranscriptAssistantLine | TranscriptUserLine,
    end: int,
) -> None:
    """Fold a line into the open turn: consume it (pushing its live events) and
    extend the turn's byte range and provenance to cover it."""
    turn = state.open_turn
    if turn is None:
        raise RuntimeError(f"session {state.session_id}: no open turn to fold into")
    if turn.native is None:
        return
    written = len(turn.accumulator.messages)
    if isinstance(line, TranscriptUserLine) and (text := prompt_text(line.message)):
        turn.interrupted = text.startswith(INTERRUPTED)
        await turn.native.prompt(
            message_id=line.uuid,
            text=prompt_content(text, line.origin),
            timestamp=line.timestamp,
            metadata={"native_item_ids": [line.uuid]},
            actor_kind="system" if turn.interrupted else "human",
        )
    await turn.native.fold(turn.accumulator.consume(line))
    stamp(turn.accumulator.messages[written:], line.timestamp)
    turn.end_offset = end
    turn.last_line_uuid = line.uuid
    if isinstance(line, TranscriptAssistantLine):
        await self.observe_subagent_calls(state, line)

observe_subagent_calls async

observe_subagent_calls(
    state: TailState, line: TranscriptAssistantLine
) -> None

Keep the task title until the child is identified, and announce a previously recorded child again when its spawning call is re-streamed.

Source code in octomate/tentacles/claude/tailer.py
async def observe_subagent_calls(
    self, state: TailState, line: TranscriptAssistantLine
) -> None:
    """Keep the task title until the child is identified, and announce a
    previously recorded child again when its spawning call is re-streamed."""
    working = self.working_subagents.get(state.session_id, [])
    for block in line.message.content:
        if not isinstance(block, ToolUseBlock):
            continue
        if name := subagent_name(block):
            agent_id = state.spawn_agents.get(block.id)
            if agent_id is None:
                state.spawn_names[block.id] = name
                continue
            child = state.subagents[agent_id].conversation
            if child is not None and not child.name:
                await self.conversation_manager.set_name(child, name)
        if block.id not in state.known_spawns:
            continue
        agent_id = state.known_spawns[block.id]
        kind = block.input.get("subagent_type")
        await state.impulses.send(
            Impulse(
                SubagentStartedEvent(
                    invocation_id=agent_id,
                    kind="subagent",
                    name=kind if isinstance(kind, str) else "Claude",
                ),
                state.address,
                replay=state.offset <= state.catchup_end,
            )
        )
        if agent_id not in working:
            await state.impulses.send(
                Impulse(
                    SubagentSettledEvent(
                        invocation_id=agent_id, status="completed"
                    ),
                    state.address,
                    replay=state.offset <= state.catchup_end,
                )
            )

fold_attachment async

fold_attachment(
    state: TailState,
    line: TranscriptAttachmentLine,
    end: int,
) -> None

Record what another agent session said while the turn ran. Claude queues a foreground subagent's hand-back into the turn as an attachment, where a background one's opens a turn as a prompt line. Any other attachment is the harness's own context and is left out.

Source code in octomate/tentacles/claude/tailer.py
async def fold_attachment(
    self, state: TailState, line: TranscriptAttachmentLine, end: int
) -> None:
    """Record what another agent session said while the turn ran. Claude queues a
    foreground subagent's hand-back into the turn as an attachment, where a
    background one's opens a turn as a prompt line. Any other attachment is the
    harness's own context and is left out."""
    turn = state.open_turn
    attached = line.attachment
    if turn is None or turn.native is None or not isinstance(attached.prompt, str):
        return
    if attached.origin is None or attached.origin.kind != "peer":
        return
    text = prompt_content(attached.prompt, attached.origin)
    if not isinstance(text, TextContent):
        return
    await turn.native.prompt(
        message_id=line.uuid,
        text=text,
        timestamp=line.timestamp,
        metadata={"native_item_ids": [line.uuid]},
    )
    turn.end_offset = end

record_permission_mode async

record_permission_mode(
    state: TailState, permission_mode: str | None
) -> None

Keep the conversation's posture at what the session's own transcript says.

Every prompt line carries the mode that turn ran under, so a ⇧⇥ in the client reaches Octomate on the operator's next message. Observed, never set: nothing here can change a running client's mode, and the console shows it read-only.

A mode Claude has that this build's vocabulary does not is skipped rather than stored — the column is validated on read, so an unknown one would take the conversation out of circulation instead of merely being unrecognized.

Source code in octomate/tentacles/claude/tailer.py
async def record_permission_mode(
    self, state: TailState, permission_mode: str | None
) -> None:
    """Keep the conversation's posture at what the session's own transcript says.

    Every prompt line carries the mode that turn ran under, so a ⇧⇥ in the client
    reaches Octomate on the operator's next message. Observed, never set: nothing
    here can change a running client's mode, and the console shows it read-only.

    A mode Claude has that this build's vocabulary does not is skipped rather than
    stored — the column is validated on read, so an unknown one would take the
    conversation out of circulation instead of merely being unrecognized.
    """
    conversation = state.conversation
    if conversation is None or permission_mode is None:
        return
    if permission_mode == conversation.permission_mode:
        return
    if not is_claude_mode(permission_mode):
        logger.debug(
            "session %s reports permission mode %r, which this build does not "
            "model; leaving the conversation at %r",
            state.session_id,
            permission_mode,
            conversation.permission_mode,
        )
        return
    await self.conversation_manager.set_permission_mode(
        conversation, permission_mode
    )

begin_turn async

begin_turn(
    state: TailState,
    line: TranscriptUserLine,
    start: int,
    end: int,
) -> OpenTurn

Open the native lifecycle at the transcript's prompt boundary.

Source code in octomate/tentacles/claude/tailer.py
async def begin_turn(
    self, state: TailState, line: TranscriptUserLine, start: int, end: int
) -> OpenTurn:
    """Open the native lifecycle at the transcript's prompt boundary."""
    accumulator = ClaudeRunAccumulator()
    native = await NativeTurn.open(
        run_id=line.prompt_id,
        recorded=state.recorded,
        conversations=self.conversation_manager,
        threads=self.thread_manager,
        locks=self.locks,
        address=state.address,
        sender=state.sender,
        impulses=state.impulses,
        messages=accumulator.messages,
        replay=end <= state.catchup_end,
    )
    text = prompt_text(line.message)
    if native is not None:
        await native.prompt(
            message_id=line.prompt_id,
            text=prompt_content(text, line.origin),
            timestamp=line.timestamp,
            metadata={"native_item_ids": [line.uuid]},
        )
    return OpenTurn(
        prompt_id=line.prompt_id,
        source=line.entrypoint,
        cwd=line.cwd,
        start_offset=start,
        end_offset=end,
        accumulator=accumulator,
        last_line_uuid=line.uuid,
        permission_mode=line.permission_mode,
        native=native,
    )

close_turn async

close_turn(state: TailState) -> None

Commit the open turn as an ExternalAgentRun with its byte range, then bind the turn's human-ledger rows to it. Idempotent by prompt_id, so a re-driven overlap after a resume is a safe no-op. Held under the session lock so the commit cannot race a hook reserving the same turn.

A commit that cannot be made propagates instead of being skipped past. A reconnect resumes from the last committed turn's end_offset, which only points at the right bytes while the committed turns are the earliest ones: skipping a turn and streaming on would let a later turn push that mark past the gap, stranding the skipped turn where no re-stream could reach it. Failing keeps the mark honest — the next connect re-streams the turn from there and commits it.

Source code in octomate/tentacles/claude/tailer.py
async def close_turn(self, state: TailState) -> None:
    """Commit the open turn as an `ExternalAgentRun` with its byte range, then bind
    the turn's human-ledger rows to it. Idempotent by `prompt_id`, so a re-driven
    overlap after a resume is a safe no-op. Held under the session lock so the commit
    cannot race a hook reserving the same turn.

    A commit that cannot be made propagates instead of being skipped past. A
    reconnect resumes from the last committed turn's `end_offset`, which only
    points at the right bytes while the committed turns are the *earliest* ones:
    skipping a turn and streaming on would let a later turn push that mark past
    the gap, stranding the skipped turn where no re-stream could reach it.
    Failing keeps the mark honest — the next connect re-streams the turn from
    there and commits it.
    """
    turn = state.open_turn
    state.open_turn = None
    if turn is None or turn.native is None:
        if state.compactions_pending and state.conversation is not None:
            await self.conversation_manager.record_native_memberships(
                state.conversation, state.session_id
            )
            state.compactions_pending = False
        return
    conversation = state.conversation
    if conversation is None:
        raise RuntimeError(f"session {state.session_id} has no conversation")
    with claude_logfire.span(
        "claude.tailer.commit_turn {prompt_id} [{session_id}]",
        prompt_id=turn.prompt_id,
        session_id=state.session_id,
        start_offset=turn.start_offset,
        end_offset=turn.end_offset,
        messages=len(turn.accumulator.messages),
    ) as span:
        async with self.locks.hold(
            state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
        ):
            run = await self.conversation_manager.record_external_run(
                conversation,
                run_id=turn.prompt_id,
                messages=turn.accumulator.messages,
                name=self.agent_tentacle_id,
                model_name=turn.accumulator.model_name,
                context_window=turn.accumulator.context_window,
                context_used=turn.accumulator.context_used,
                permission_mode=turn.permission_mode,
                cwd=Path(turn.cwd) if turn.cwd else None,
                native_session_id=state.session_id,
                source=turn.source,
                start_offset=turn.start_offset,
                end_offset=turn.end_offset,
                last_line_uuid=turn.last_line_uuid,
            )
            span.set_attribute("committed", run is not None)
            if state.compactions_pending:
                await self.conversation_manager.record_native_memberships(
                    conversation, state.session_id
                )
                state.compactions_pending = False
            await turn.native.close(
                run,
                run_id=turn.prompt_id,
                answer=turn.accumulator.result_text,
                interrupted=turn.interrupted,
            )
            logger.info(
                "session %s: turn %s synced — %d messages, bytes %d-%d",
                state.session_id,
                turn.prompt_id,
                len(turn.accumulator.messages),
                turn.start_offset,
                turn.end_offset,
            )

subagent_tail staticmethod

subagent_tail(
    state: TailState, agent_id: str
) -> SubagentTail
Source code in octomate/tentacles/claude/tailer.py
@staticmethod
def subagent_tail(state: TailState, agent_id: str) -> SubagentTail:
    tail = state.subagents.get(agent_id)
    if tail is None:
        tail = SubagentTail(
            agent_id=agent_id,
            path=state.subagents_dir / f"agent-{agent_id}.jsonl",
        )
        state.subagents[agent_id] = tail
    return tail

finish_subagent async

finish_subagent(
    session_id: str,
    agent_id: str,
    *,
    final_answer: str | None = None,
) -> str

Drain and commit one subagent on its SubagentStop — the child's finalize, which a Claude child needs: its turns frame on promptId change, so nothing in its own file closes the last one. The hook is synchronous but the transcript writer is not: the final answer line races it (measured: usually loses by ~1-2KB). The child's lines arrive through feed_remote on their own; when the event names the answer, wait until the stream yields it, bounded so a mismatch can never hang the pipe — tail.offset says whether the writer has gone quiet. A session no stream covers has nothing to settle. Returns the answer the committed turn ended on.

Source code in octomate/tentacles/claude/tailer.py
async def finish_subagent(
    self, session_id: str, agent_id: str, *, final_answer: str | None = None
) -> str:
    """Drain and commit one subagent on its `SubagentStop` — the child's
    `finalize`, which a Claude child needs: its turns frame on promptId change,
    so nothing in its own file closes the last one. The hook is synchronous but
    the transcript writer is not: the final answer line races it (measured:
    usually loses by ~1-2KB). The child's lines arrive through `feed_remote` on
    their own; when the event names the answer, wait until the stream yields it,
    bounded so a mismatch can never hang the pipe — `tail.offset` says whether
    the writer has gone quiet. A session no stream covers has nothing to
    settle. Returns the answer the committed turn ended on."""
    state = self.sessions.get(session_id)
    if state is None:
        return ""
    if state.conversation is None:
        await self.prepare(state)
    tail = self.subagent_tail(state, agent_id)
    # The turn this stop is for. If a resume arrives inside the settle window,
    # the stream itself closes this turn on the promptId change and opens the
    # next — which must NOT be committed by this stop, mid-flight.
    target = tail.open_turn
    deadline = monotonic() + SUBAGENT_SETTLE_TIMEOUT
    quiet = 0
    while not self.subagent_settled(tail, final_answer):
        if quiet >= 2:
            break  # writer went silent: the file is as final as it gets
        if monotonic() >= deadline:
            logger.warning(
                "session %s: subagent %s kept writing past the settle window "
                "without yielding its announced answer; committing what it "
                "reached",
                session_id,
                agent_id,
            )
            break
        before = tail.offset
        await asyncio.sleep(SUBAGENT_SETTLE_POLL)
        quiet = quiet + 1 if tail.offset == before else 0
    turn = target or tail.open_turn
    if target is None or tail.open_turn is target:
        await self.close_subagent_turn(state, tail)
    return turn.accumulator.result_text if turn is not None else ""

subagent_settled staticmethod

subagent_settled(
    tail: SubagentTail, final_answer: str | None
) -> bool

The fast path: the drained turn already carries the exact answer the stop event announced. Divergence (a truncated or differently-joined hook payload — no contract promises byte equality) is not an error: the caller's byte-quiescence fallback settles those, so strictness here only ever costs one extra poll beat, never a wrong commit.

Source code in octomate/tentacles/claude/tailer.py
@staticmethod
def subagent_settled(tail: SubagentTail, final_answer: str | None) -> bool:
    """The fast path: the drained turn already carries the exact answer the
    stop event announced. Divergence (a truncated or differently-joined hook
    payload — no contract promises byte equality) is not an error: the caller's
    byte-quiescence fallback settles those, so strictness here only ever costs
    one extra poll beat, never a wrong commit."""
    if final_answer is None:
        return False  # nothing announced; quiescence decides
    turn = tail.open_turn
    if turn is None:
        return False
    return turn.accumulator.result_text.strip() == final_answer.strip()

prepare_subagent async

prepare_subagent(
    state: TailState, tail: SubagentTail
) -> Conversation

Resolve the child's conversation under the session's thread and seed its committed-turn guard — the first time this child's lines are fed.

Source code in octomate/tentacles/claude/tailer.py
async def prepare_subagent(
    self, state: TailState, tail: SubagentTail
) -> Conversation:
    """Resolve the child's conversation under the session's thread and seed its
    committed-turn guard — the first time this child's lines are fed."""
    parent = state.conversation
    if parent is None:
        raise RuntimeError(f"session {state.session_id} has no conversation")
    tail.conversation = await self.conversation_manager.ensure(
        parent.thread_id,
        agent_tentacle_id=self.agent_tentacle_id,
        native=True,
        subagent_id=tail.agent_id,
        parent_conversation_id=parent.id,
    )
    tail.recorded = tail.conversation.native_run_ids
    previous = max(
        (
            run
            for run in tail.conversation.runs
            if isinstance(run, ExternalAgentRun) and run.end_offset is not None
        ),
        key=lambda run: run.end_offset or 0,
        default=None,
    )
    tail.last_item_id = previous.last_line_uuid if previous is not None else None
    return tail.conversation

process_subagent_line async

process_subagent_line(
    state: TailState,
    tail: SubagentTail,
    line: TranscriptLine,
    start: int,
    end: int,
) -> None

Frame a subagent's turns on promptId change — the only marker its file carries (promptSource is absent, and every line is is_sidechain, so neither parent rule applies). Each turn's promptId is the parent turn that drove it; a resumed subagent opens its next turn on whatever user line arrives first, which is measured to be a tool result, not a prompt.

A result stays with its call. A background child works on while its parent takes the next prompt, and the results it writes then carry that prompt's id: splitting there would cut one piece of work in two.

Source code in octomate/tentacles/claude/tailer.py
async def process_subagent_line(
    self,
    state: TailState,
    tail: SubagentTail,
    line: TranscriptLine,
    start: int,
    end: int,
) -> None:
    """Frame a subagent's turns on `promptId` change — the only marker its file
    carries (`promptSource` is absent, and every line is `is_sidechain`, so
    neither parent rule applies). Each turn's `promptId` is the *parent* turn
    that drove it; a resumed subagent opens its next turn on whatever user line
    arrives first, which is measured to be a tool result, not a prompt.

    A result stays with its call. A background child works on while its parent
    takes the next prompt, and the results it writes then carry that prompt's
    id: splitting there would cut one piece of work in two."""
    if (
        isinstance(line, TranscriptSystemLine)
        and line.subtype == "compact_boundary"
    ):
        await self.record_compaction(state, line, start, end, tail=tail)
        return
    if isinstance(line, TranscriptUserLine) and line.is_compact_summary:
        await self.record_compaction(state, line, start, end, tail=tail)
        return
    if isinstance(line, TranscriptUserLine | TranscriptAssistantLine):
        tail.last_item_id = line.uuid
    elif isinstance(line, TranscriptSystemLine):
        tail.omitted_uuids.add(line.uuid)
    if isinstance(line, TranscriptUserLine) and start == 0 and tail.call_id:
        # An interrupted call's result never names this child; its meta file did.
        await self.record_spawn(state, tail, line.prompt_id, tail.call_id)
    if isinstance(line, TranscriptUserLine):
        turn = tail.open_turn
        if turn is not None and (
            line.prompt_id == turn.prompt_id
            or line.source_tool_assistant_uuid in turn.calls
        ):
            self.fold_subagent(tail, line, end)
        else:
            await self.close_subagent_turn(state, tail)
            tail.open_turn = self.begin_subagent_turn(line, start, end)
        working = self.working_subagents.get(state.session_id, [])
        if (
            prompt_text(line.message).startswith(INTERRUPTED)
            and tail.agent_id in working
        ):
            # Claude writes the marker into the child's own file and fires no hook.
            await self.close_subagent_turn(state, tail)
            working.remove(tail.agent_id)
            await state.impulses.send(
                Impulse(
                    SubagentSettledEvent(
                        invocation_id=tail.agent_id, status="cancelled"
                    ),
                    state.address,
                    replay=end <= tail.catchup_end,
                )
            )
    elif isinstance(line, TranscriptAssistantLine):
        if tail.open_turn is not None:
            self.fold_subagent(tail, line, end)

begin_subagent_turn

begin_subagent_turn(
    line: TranscriptUserLine, start: int, end: int
) -> OpenTurn
Source code in octomate/tentacles/claude/tailer.py
def begin_subagent_turn(
    self, line: TranscriptUserLine, start: int, end: int
) -> OpenTurn:
    accumulator = ClaudeRunAccumulator()
    text = prompt_text(line.message)
    if text:
        accumulator.begin(text)
        accumulator.messages[0].metadata = {"native_item_ids": [line.uuid]}
    # The opener may itself carry tool results (a resumed subagent's turn opens on
    # one); consuming is a no-op for a plain prompt line.
    for _ in accumulator.consume(line):
        pass
    stamp(accumulator.messages, line.timestamp)
    return OpenTurn(
        prompt_id=line.prompt_id,
        source=line.entrypoint,
        cwd=line.cwd,
        start_offset=start,
        end_offset=end,
        accumulator=accumulator,
        last_line_uuid=line.uuid,
        permission_mode=line.permission_mode,
    )

fold_subagent

fold_subagent(
    tail: SubagentTail,
    line: TranscriptAssistantLine | TranscriptUserLine,
    end: int,
) -> None

Fold a line into the child's open turn. Events are consumed, not emitted: the live stream is the parent timeline's; fanning child events into it would interleave two timelines under one label.

Source code in octomate/tentacles/claude/tailer.py
def fold_subagent(
    self,
    tail: SubagentTail,
    line: TranscriptAssistantLine | TranscriptUserLine,
    end: int,
) -> None:
    """Fold a line into the child's open turn. Events are consumed, not emitted:
    the live stream is the parent timeline's; fanning child events into it would
    interleave two timelines under one label."""
    turn = tail.open_turn
    if turn is None:
        raise RuntimeError(f"subagent {tail.agent_id}: no open turn to fold into")
    written = len(turn.accumulator.messages)
    for _ in turn.accumulator.consume(line):
        pass
    stamp(turn.accumulator.messages[written:], line.timestamp)
    turn.end_offset = end
    turn.last_line_uuid = line.uuid
    if isinstance(line, TranscriptAssistantLine):
        turn.calls.add(line.uuid)

close_subagent_turn async

close_subagent_turn(
    state: TailState, tail: SubagentTail
) -> None

Commit the child's open turn as a child run: keyed <agentId>:<promptId> (which subagent, which parent turn — a bare promptId would collide with the parent run it belongs to), linked by parent_run_id = that promptId and the harvested spawning call. A subagent has no human prompt or answer, so it never touches the ledger.

Source code in octomate/tentacles/claude/tailer.py
async def close_subagent_turn(self, state: TailState, tail: SubagentTail) -> None:
    """Commit the child's open turn as a child run: keyed `<agentId>:<promptId>`
    (which subagent, which parent turn — a bare `promptId` would collide with the
    parent run it belongs to), linked by `parent_run_id` = that `promptId` and the
    harvested spawning call. A subagent has no human prompt or answer, so it never
    touches the ledger."""
    turn = tail.open_turn
    tail.open_turn = None
    if turn is None:
        return
    run_id = f"{tail.agent_id}:{turn.prompt_id}"
    if run_id in tail.recorded or not turn.accumulator.messages:
        return
    conversation = tail.conversation
    if conversation is None:
        raise RuntimeError(f"subagent {tail.agent_id} has no conversation")
    with claude_logfire.span(
        "claude.tailer.commit_subagent_turn {run_id} [{session_id}]",
        run_id=run_id,
        session_id=state.session_id,
        start_offset=turn.start_offset,
        end_offset=turn.end_offset,
        messages=len(turn.accumulator.messages),
    ) as span:
        async with self.locks.hold(
            state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
        ):
            run = await self.conversation_manager.record_external_run(
                conversation,
                run_id=run_id,
                messages=turn.accumulator.messages,
                name=self.agent_tentacle_id,
                model_name=turn.accumulator.model_name,
                context_window=turn.accumulator.context_window,
                context_used=turn.accumulator.context_used,
                permission_mode=turn.permission_mode,
                cwd=Path(turn.cwd) if turn.cwd else None,
                native_session_id=tail.agent_id,
                source=turn.source,
                start_offset=turn.start_offset,
                end_offset=turn.end_offset,
                last_line_uuid=turn.last_line_uuid,
                parent_run_id=turn.prompt_id,
            )
            span.set_attribute("committed", run is not None)
            if run is None:
                return
            tail.recorded.add(run_id)
            if tail.compactions_pending:
                await self.conversation_manager.record_native_memberships(
                    conversation, state.session_id
                )
                tail.compactions_pending = False
            logger.info(
                "session %s: subagent %s turn %s synced — %d messages, bytes %d-%d",
                state.session_id,
                tail.agent_id,
                turn.prompt_id,
                len(turn.accumulator.messages),
                turn.start_offset,
                turn.end_offset,
            )

close_subagent_turns async

close_subagent_turns(state: TailState) -> None

Commit every child's trailing open turn — the subagent counterpart of the final close_turn, at a session-ending drain (finish_remote).

Source code in octomate/tentacles/claude/tailer.py
async def close_subagent_turns(self, state: TailState) -> None:
    """Commit every child's trailing open turn — the subagent counterpart of the
    final `close_turn`, at a session-ending drain (`finish_remote`)."""
    for tail in state.subagents.values():
        await self.close_subagent_turn(state, tail)

stamp

stamp(
    messages: list[ModelMessage], timestamp: datetime | None
) -> None

Date the messages a transcript record produced by that record's own clock — the accumulator stamps now, which is wrong for a run replayed off disk (AgentRun.started_at and displayed times read from these).

Source code in octomate/tentacles/claude/tailer.py
def stamp(messages: list[PydanticModelMessage], timestamp: datetime | None) -> None:
    """Date the messages a transcript record produced by that record's own clock — the
    accumulator stamps `now`, which is wrong for a run replayed off disk
    (`AgentRun.started_at` and displayed times read from these)."""
    if timestamp is None:
        return
    for message in messages:
        message.timestamp = timestamp

octomate.tentacles.codex.transcript

Typed lines of a Codex rollout file, and the runtime's own tree.

CODEX_HOME_DIRS module-attribute

CODEX_HOME_DIRS: tuple[Path, ...] = (
    Path(
        os.environ.get("CODEX_HOME")
        or Path.home() / ".codex"
    ),
)

rollout_line_adapter module-attribute

rollout_line_adapter = TypeAdapter(RolloutLine)

compaction_item_adapter module-attribute

compaction_item_adapter: TypeAdapter[
    EncryptedCompactionItem | ContextCompactionItem
] = TypeAdapter(
    Annotated[
        EncryptedCompactionItem | ContextCompactionItem,
        Field(discriminator="type"),
    ]
)

session_metadata_adapter module-attribute

session_metadata_adapter = TypeAdapter(SessionMetadata)

RolloutLine pydantic-model

Bases: BaseModel

One line of a Codex rollout: its timestamp, record type, and raw payload.

Config:

  • extra: ignore

Fields:

  • timestamp (AwareDatetime)
  • type (Literal['session_meta', 'turn_context', 'event_msg', 'response_item', 'world_state', 'compacted', 'inter_agent_communication_metadata'])
  • payload (JsonObject)
Source code in octomate/tentacles/codex/transcript.py
class RolloutLine(BaseModel):
    """One line of a Codex rollout: its timestamp, record type, and raw payload."""

    model_config = ConfigDict(extra="ignore")

    timestamp: AwareDatetime
    type: Literal[
        "session_meta",
        "turn_context",
        "event_msg",
        "response_item",
        "world_state",
        "compacted",
        "inter_agent_communication_metadata",
    ]
    payload: JsonObject

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

timestamp pydantic-field

timestamp: AwareDatetime

type pydantic-field

type: Literal[
    "session_meta",
    "turn_context",
    "event_msg",
    "response_item",
    "world_state",
    "compacted",
    "inter_agent_communication_metadata",
]

payload pydantic-field

payload: JsonObject

CompactedItem pydantic-model

Bases: BaseModel

A committed context replacement, independent of turn lifecycle events.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class CompactedItem(BaseModel):
    """A committed context replacement, independent of turn lifecycle events."""

    message: str = Field(description="Readable summary; empty for opaque compaction.")
    replacement_history: list[JsonObject] | None = Field(
        default=None,
        description="Native replacement items, including retained context and provider checkpoints.",
    )
    compaction_response_id: str | None = Field(
        default=None,
        description="Provider response ID of the compaction request, when reported.",
    )

    def to_messages(
        self,
        timestamp: AwareDatetime,
        *,
        last_item_id: str | None = None,
        item_aliases: dict[str, str] | None = None,
    ) -> list[ModelRequest | ModelResponse]:
        """Normalize created summaries/checkpoints; retained messages keep their owner."""
        metadata = codex_metadata()
        if last_item_id is not None and self.replacement_history is not None:
            replacements: list[str] = []
            for item in self.replacement_history:
                if is_injected_message(item):
                    continue
                identity = context_item_id(item)
                if identity is None:
                    break
                replacements.append(identity)
            else:
                referenced = {last_item_id, *replacements}
                metadata = {
                    **metadata,
                    "compaction_context": NativeContext(
                        last_item_id=last_item_id,
                        replacement_ids=replacements,
                        item_aliases={
                            alias: identity
                            for alias, identity in (item_aliases or {}).items()
                            if identity in referenced
                        },
                    ).model_dump(mode="json"),
                }
        checkpoints = [
            compaction_item_adapter.validate_python(raw)
            for raw in self.replacement_history or []
            if raw.get("type")
            in {"compaction", "compaction_summary", "context_compaction"}
        ]
        messages: list[ModelRequest | ModelResponse] = []
        if self.message:
            messages.append(
                ModelRequest(
                    parts=[UserPromptPart(self.message, timestamp=timestamp)],
                    timestamp=timestamp,
                    metadata=metadata,
                )
            )
        messages.extend(
            ModelResponse(
                parts=[
                    CompactionPart(
                        id=checkpoint.id,
                        provider_name=CODEX_PROVIDER_NAME,
                        provider_details={
                            "encrypted_content": checkpoint.encrypted_content
                        }
                        if checkpoint.encrypted_content is not None
                        else None,
                    )
                ],
                timestamp=timestamp,
                provider_name=CODEX_PROVIDER_NAME,
                provider_response_id=self.compaction_response_id,
                metadata={
                    **(
                        metadata
                        if not self.message and index == 0
                        else codex_metadata()
                    ),
                    "native_item_ids": [checkpoint.id] if checkpoint.id else [],
                },
            )
            for index, checkpoint in enumerate(checkpoints)
        )
        return messages

message pydantic-field

message: str

Readable summary; empty for opaque compaction.

replacement_history pydantic-field

replacement_history: list[JsonObject] | None = None

Native replacement items, including retained context and provider checkpoints.

compaction_response_id pydantic-field

compaction_response_id: str | None = None

Provider response ID of the compaction request, when reported.

to_messages

to_messages(
    timestamp: AwareDatetime,
    *,
    last_item_id: str | None = None,
    item_aliases: dict[str, str] | None = None,
) -> list[ModelRequest | ModelResponse]

Normalize created summaries/checkpoints; retained messages keep their owner.

Source code in octomate/tentacles/codex/transcript.py
def to_messages(
    self,
    timestamp: AwareDatetime,
    *,
    last_item_id: str | None = None,
    item_aliases: dict[str, str] | None = None,
) -> list[ModelRequest | ModelResponse]:
    """Normalize created summaries/checkpoints; retained messages keep their owner."""
    metadata = codex_metadata()
    if last_item_id is not None and self.replacement_history is not None:
        replacements: list[str] = []
        for item in self.replacement_history:
            if is_injected_message(item):
                continue
            identity = context_item_id(item)
            if identity is None:
                break
            replacements.append(identity)
        else:
            referenced = {last_item_id, *replacements}
            metadata = {
                **metadata,
                "compaction_context": NativeContext(
                    last_item_id=last_item_id,
                    replacement_ids=replacements,
                    item_aliases={
                        alias: identity
                        for alias, identity in (item_aliases or {}).items()
                        if identity in referenced
                    },
                ).model_dump(mode="json"),
            }
    checkpoints = [
        compaction_item_adapter.validate_python(raw)
        for raw in self.replacement_history or []
        if raw.get("type")
        in {"compaction", "compaction_summary", "context_compaction"}
    ]
    messages: list[ModelRequest | ModelResponse] = []
    if self.message:
        messages.append(
            ModelRequest(
                parts=[UserPromptPart(self.message, timestamp=timestamp)],
                timestamp=timestamp,
                metadata=metadata,
            )
        )
    messages.extend(
        ModelResponse(
            parts=[
                CompactionPart(
                    id=checkpoint.id,
                    provider_name=CODEX_PROVIDER_NAME,
                    provider_details={
                        "encrypted_content": checkpoint.encrypted_content
                    }
                    if checkpoint.encrypted_content is not None
                    else None,
                )
            ],
            timestamp=timestamp,
            provider_name=CODEX_PROVIDER_NAME,
            provider_response_id=self.compaction_response_id,
            metadata={
                **(
                    metadata
                    if not self.message and index == 0
                    else codex_metadata()
                ),
                "native_item_ids": [checkpoint.id] if checkpoint.id else [],
            },
        )
        for index, checkpoint in enumerate(checkpoints)
    )
    return messages

CompletedCompactionItem pydantic-model

Bases: BaseModel

The native rollout's completed context-compaction item.

Fields:

  • type (Literal['ContextCompaction'])
  • id (str)
Source code in octomate/tentacles/codex/transcript.py
class CompletedCompactionItem(BaseModel):
    """The native rollout's completed context-compaction item."""

    type: Literal["ContextCompaction"]
    id: str

type pydantic-field

type: Literal['ContextCompaction']

id pydantic-field

id: str

CompactionCompletedEvent pydantic-model

Bases: BaseModel

The source item identity following a committed replacement.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class CompactionCompletedEvent(BaseModel):
    """The source item identity following a committed replacement."""

    type: Literal["item_completed"]
    thread_id: str
    turn_id: str
    item: CompletedCompactionItem

type pydantic-field

type: Literal['item_completed']

thread_id pydantic-field

thread_id: str

turn_id pydantic-field

turn_id: str

item pydantic-field

item: CompletedCompactionItem

EncryptedCompactionItem pydantic-model

Bases: BaseModel

An opaque provider checkpoint carried in replacement history.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class EncryptedCompactionItem(BaseModel):
    """An opaque provider checkpoint carried in replacement history."""

    type: Literal["compaction", "compaction_summary"]
    id: str | None = None
    encrypted_content: str

type pydantic-field

type: Literal['compaction', 'compaction_summary']

id pydantic-field

id: str | None = None

encrypted_content pydantic-field

encrypted_content: str

ContextCompactionItem pydantic-model

Bases: BaseModel

A context-compaction item that may omit its encrypted content.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class ContextCompactionItem(BaseModel):
    """A context-compaction item that may omit its encrypted content."""

    type: Literal["context_compaction"]
    id: str | None = None
    encrypted_content: str | None = None

type pydantic-field

type: Literal['context_compaction']

id pydantic-field

id: str | None = None

encrypted_content pydantic-field

encrypted_content: str | None = None

ParsedCommand pydantic-model

Bases: BaseModel

Codex's classification of one command in a native execution item.

Fields:

  • type (Literal['read', 'list_files', 'search', 'unknown'])
  • cmd (str | None)
  • name (str | None)
  • path (str | None)
  • query (str | None)
Source code in octomate/tentacles/codex/transcript.py
class ParsedCommand(BaseModel):
    """Codex's classification of one command in a native execution item."""

    type: Literal["read", "list_files", "search", "unknown"]
    cmd: str | None = Field(
        default=None, description="Command text classified by Codex."
    )
    name: str | None = Field(default=None, description="Display name of the read file.")
    path: str | None = Field(
        default=None, description="File or directory targeted by the command."
    )
    query: str | None = Field(
        default=None, description="Search query recorded by Codex."
    )

type pydantic-field

type: Literal['read', 'list_files', 'search', 'unknown']

cmd pydantic-field

cmd: str | None = None

Command text classified by Codex.

name pydantic-field

name: str | None = None

Display name of the read file.

path pydantic-field

path: str | None = None

File or directory targeted by the command.

query pydantic-field

query: str | None = None

Search query recorded by Codex.

CompletedCommandItem pydantic-model

Bases: BaseModel

An executed command recorded separately from its outer tool call.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class CompletedCommandItem(BaseModel):
    """An executed command recorded separately from its outer tool call."""

    type: Literal["CommandExecution"]
    id: str
    command: list[str]
    cwd: str
    parsed_cmd: list[ParsedCommand]
    status: Literal["completed", "failed", "declined"]
    aggregated_output: str

type pydantic-field

type: Literal['CommandExecution']

id pydantic-field

id: str

command pydantic-field

command: list[str]

cwd pydantic-field

cwd: str

parsed_cmd pydantic-field

parsed_cmd: list[ParsedCommand]

status pydantic-field

status: Literal['completed', 'failed', 'declined']

aggregated_output pydantic-field

aggregated_output: str

UserMessageContent pydantic-model

Bases: BaseModel

A user-role content part; only input text is imported.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class UserMessageContent(BaseModel):
    """A user-role content part; only input text is imported."""

    type: str
    text: str | None = None

type pydantic-field

type: str

text pydantic-field

text: str | None = None

UserMessageMetadata pydantic-model

Bases: BaseModel

Codex's provenance labels, aligned with the message's content parts.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class UserMessageMetadata(BaseModel):
    """Codex's provenance labels, aligned with the message's content parts."""

    turn_id: str
    content_item_kinds: list[str]

turn_id pydantic-field

turn_id: str

content_item_kinds pydantic-field

content_item_kinds: list[str]

UserMessageItem pydantic-model

Bases: BaseModel

A current-format user message with explicit per-part provenance.

User-role records also carry injected context. Only parts labelled user.text are human text; unlabelled records rely on the legacy event.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class UserMessageItem(BaseModel):
    """A current-format user message with explicit per-part provenance.

    User-role records also carry injected context. Only parts labelled
    `user.text` are human text; unlabelled records rely on the legacy event.
    """

    type: Literal["message"]
    id: str | None = None
    role: Literal["user"]
    content: list[UserMessageContent]
    metadata: UserMessageMetadata = Field(
        alias="internal_chat_message_metadata_passthrough"
    )

type pydantic-field

type: Literal['message']

id pydantic-field

id: str | None = None

role pydantic-field

role: Literal['user']

content pydantic-field

content: list[UserMessageContent]

metadata pydantic-field

metadata: UserMessageMetadata

CompletedUserMessageItem pydantic-model

Bases: BaseModel

The app-server identity of a prompt already written to the rollout.

Fields:

  • type (Literal['UserMessage'])
  • id (str)
Source code in octomate/tentacles/codex/transcript.py
class CompletedUserMessageItem(BaseModel):
    """The app-server identity of a prompt already written to the rollout."""

    type: Literal["UserMessage"]
    id: str

type pydantic-field

type: Literal['UserMessage']

id pydantic-field

id: str

UserMessageCompletedEvent pydantic-model

Bases: BaseModel

A prompt completion scoped to its native session and turn.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class UserMessageCompletedEvent(BaseModel):
    """A prompt completion scoped to its native session and turn."""

    type: Literal["item_completed"]
    thread_id: str
    turn_id: str
    item: CompletedUserMessageItem

type pydantic-field

type: Literal['item_completed']

thread_id pydantic-field

thread_id: str

turn_id pydantic-field

turn_id: str

item pydantic-field

item: CompletedUserMessageItem

UserMessageIdentities dataclass

Pair source occurrences, including repeated text, without importing a turn.

Source code in octomate/tentacles/codex/transcript.py
@dataclass
class UserMessageIdentities:
    """Pair source occurrences, including repeated text, without importing a turn."""

    turn_id: str | None = None
    pending: list[str] = field(default_factory=list)
    aliases: dict[str, str] = field(default_factory=dict)

    def consume(self, line: RolloutLine, thread_id: str) -> None:
        kind = payload_type(line)
        if line.type == "event_msg" and kind in {
            "task_started",
            "task_complete",
            "turn_aborted",
        }:
            turn_id = line.payload.get("turn_id")
            self.turn_id = (
                turn_id if kind == "task_started" and isinstance(turn_id, str) else None
            )
            self.pending.clear()
            return
        if line.type == "response_item" and line.payload.get("role") == "user":
            try:
                item = UserMessageItem.model_validate(line.payload)
            except ValidationError:
                self.pending.clear()
                return
            if (
                item.id is not None
                and item.metadata.turn_id == self.turn_id
                and len(item.metadata.content_item_kinds) == len(item.content)
                and "user.text" in item.metadata.content_item_kinds
            ):
                self.pending.append(item.id)
            else:
                self.pending.clear()
            return
        if line.type == "event_msg" and kind == "user_message":
            return
        if not self.pending:
            return
        pending, self.pending = self.pending, []
        if line.type != "event_msg" or kind != "item_completed" or len(pending) != 1:
            return
        try:
            event = UserMessageCompletedEvent.model_validate(line.payload)
        except ValidationError:
            return
        if event.thread_id == thread_id and event.turn_id == self.turn_id:
            self.aliases[event.item.id] = pending[0]

turn_id class-attribute instance-attribute

turn_id: str | None = None

pending class-attribute instance-attribute

pending: list[str] = field(default_factory=list)

aliases class-attribute instance-attribute

aliases: dict[str, str] = field(default_factory=dict)

consume

consume(line: RolloutLine, thread_id: str) -> None
Source code in octomate/tentacles/codex/transcript.py
def consume(self, line: RolloutLine, thread_id: str) -> None:
    kind = payload_type(line)
    if line.type == "event_msg" and kind in {
        "task_started",
        "task_complete",
        "turn_aborted",
    }:
        turn_id = line.payload.get("turn_id")
        self.turn_id = (
            turn_id if kind == "task_started" and isinstance(turn_id, str) else None
        )
        self.pending.clear()
        return
    if line.type == "response_item" and line.payload.get("role") == "user":
        try:
            item = UserMessageItem.model_validate(line.payload)
        except ValidationError:
            self.pending.clear()
            return
        if (
            item.id is not None
            and item.metadata.turn_id == self.turn_id
            and len(item.metadata.content_item_kinds) == len(item.content)
            and "user.text" in item.metadata.content_item_kinds
        ):
            self.pending.append(item.id)
        else:
            self.pending.clear()
        return
    if line.type == "event_msg" and kind == "user_message":
        return
    if not self.pending:
        return
    pending, self.pending = self.pending, []
    if line.type != "event_msg" or kind != "item_completed" or len(pending) != 1:
        return
    try:
        event = UserMessageCompletedEvent.model_validate(line.payload)
    except ValidationError:
        return
    if event.thread_id == thread_id and event.turn_id == self.turn_id:
        self.aliases[event.item.id] = pending[0]

ThreadSpawnMetadata pydantic-model

Bases: BaseModel

A child rollout's thread_spawn metadata, naming the parent thread.

Config:

  • extra: ignore

Fields:

Source code in octomate/tentacles/codex/transcript.py
class ThreadSpawnMetadata(BaseModel):
    """A child rollout's `thread_spawn` metadata, naming the parent thread."""

    model_config = ConfigDict(extra="ignore")

    parent_thread_id: str
    depth: int = 1
    agent_path: str = ""

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

parent_thread_id pydantic-field

parent_thread_id: str

depth pydantic-field

depth: int = 1

agent_path pydantic-field

agent_path: str = ''

SubagentSource pydantic-model

Bases: BaseModel

The subagent block of a session's source, present on a spawned child.

Config:

  • extra: ignore

Fields:

Source code in octomate/tentacles/codex/transcript.py
class SubagentSource(BaseModel):
    """The `subagent` block of a session's `source`, present on a spawned child."""

    model_config = ConfigDict(extra="ignore")

    thread_spawn: ThreadSpawnMetadata | None = None

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

thread_spawn pydantic-field

thread_spawn: ThreadSpawnMetadata | None = None

SessionSource pydantic-model

Bases: BaseModel

A structured session_meta source, carrying a spawned child's lineage.

Config:

  • extra: ignore

Fields:

Source code in octomate/tentacles/codex/transcript.py
class SessionSource(BaseModel):
    """A structured `session_meta` `source`, carrying a spawned child's lineage."""

    model_config = ConfigDict(extra="ignore")

    subagent: SubagentSource | None = None

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

subagent pydantic-field

subagent: SubagentSource | None = None

SessionMetadata pydantic-model

Bases: BaseModel

The payload of a rollout's opening session_meta line.

Config:

  • extra: ignore

Fields:

Source code in octomate/tentacles/codex/transcript.py
class SessionMetadata(BaseModel):
    """The payload of a rollout's opening `session_meta` line."""

    model_config = ConfigDict(extra="ignore")

    session_id: str
    id: str | None = None
    # The directory the session opened in. Codex repeats it per turn in a
    # `turn_context` line, which across every rollout on hand never disagrees with
    # this one, so the session's own report is the whole of where its turns ran.
    cwd: str = ""
    originator: str | None = None
    source: str | SessionSource | None = None
    thread_source: str | None = None

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='ignore')

session_id pydantic-field

session_id: str

id pydantic-field

id: str | None = None

cwd pydantic-field

cwd: str = ''

originator pydantic-field

originator: str | None = None

source pydantic-field

source: str | SessionSource | None = None

thread_source pydantic-field

thread_source: str | None = None

WorkspaceWritePolicy pydantic-model

Bases: BaseModel

The workspace sandbox representable by Octomate's review presets.

Config:

  • extra: forbid

Fields:

Source code in octomate/tentacles/codex/transcript.py
class WorkspaceWritePolicy(BaseModel):
    """The workspace sandbox representable by Octomate's review presets."""

    model_config = ConfigDict(extra="forbid")

    type: Literal["workspace-write"]
    writable_roots: list[str] = Field(default_factory=list, max_length=0)
    network_access: Literal[False] = False
    exclude_tmpdir_env_var: bool = False
    exclude_slash_tmp: bool = False

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='forbid')

type pydantic-field

type: Literal['workspace-write']

writable_roots pydantic-field

writable_roots: list[str]

network_access pydantic-field

network_access: Literal[False] = False

exclude_tmpdir_env_var pydantic-field

exclude_tmpdir_env_var: bool = False

exclude_slash_tmp pydantic-field

exclude_slash_tmp: bool = False

FullAccessPolicy pydantic-model

Bases: BaseModel

The unrestricted sandbox used by the full-access preset.

Config:

  • extra: forbid

Fields:

  • type (Literal['danger-full-access'])
Source code in octomate/tentacles/codex/transcript.py
class FullAccessPolicy(BaseModel):
    """The unrestricted sandbox used by the full-access preset."""

    model_config = ConfigDict(extra="forbid")

    type: Literal["danger-full-access"]

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='forbid')

type pydantic-field

type: Literal['danger-full-access']

ActivePermissionProfile pydantic-model

Bases: BaseModel

Native profiles whose boundaries Octomate can reproduce on a fork.

Fields:

Source code in octomate/tentacles/codex/transcript.py
class ActivePermissionProfile(BaseModel):
    """Native profiles whose boundaries Octomate can reproduce on a fork."""

    id: Literal[":workspace"] | PermissionProfile = Field(
        description="The built-in legacy profile or an Octomate-selected native profile."
    )

id pydantic-field

id: Literal[':workspace'] | PermissionProfile

The built-in legacy profile or an Octomate-selected native profile.

TurnPermissions pydantic-model

Bases: BaseModel

Permissions recorded in a native rollout's turn_context payload.

Fields:

Validators:

Source code in octomate/tentacles/codex/transcript.py
class TurnPermissions(BaseModel):
    """Permissions recorded in a native rollout's turn_context payload."""

    approval_policy: Literal["on-request", "never"]
    approvals_reviewer: Literal["user", "auto_review"] = "user"
    sandbox_policy: WorkspaceWritePolicy | FullAccessPolicy = Field(
        discriminator="type"
    )
    active_permission_profile: ActivePermissionProfile | None = Field(
        default=None, description="Selected native profile, absent in legacy rollouts."
    )

    @model_validator(mode="after")
    def profile_matches_sandbox(self) -> Self:
        profile = self.active_permission_profile
        if isinstance(self.sandbox_policy, FullAccessPolicy):
            if profile is not None and profile.id != ":danger-full-access":
                raise ValueError("Native profile does not match sandbox_policy")
            return self
        strict = profile is not None and profile.id == "octomate-workspace"
        flags = (
            self.sandbox_policy.exclude_tmpdir_env_var,
            self.sandbox_policy.exclude_slash_tmp,
        )
        if flags != (strict, strict) or (
            profile is not None
            and profile.id not in {":workspace", "octomate-workspace"}
        ):
            raise ValueError("Native profile does not match sandbox_policy")
        return self

    @property
    def permission_mode(self) -> CodexPermissionMode:
        if isinstance(self.sandbox_policy, FullAccessPolicy):
            if self.approval_policy == "never":
                return "full_access"
        elif self.approval_policy == "on-request":
            return (
                "auto_review"
                if self.approvals_reviewer == "auto_review"
                else "user_review"
            )
        raise ValueError("Native Codex permissions do not match an Octomate preset")

approval_policy pydantic-field

approval_policy: Literal['on-request', 'never']

approvals_reviewer pydantic-field

approvals_reviewer: Literal['user', 'auto_review'] = 'user'

sandbox_policy pydantic-field

sandbox_policy: WorkspaceWritePolicy | FullAccessPolicy

active_permission_profile pydantic-field

active_permission_profile: (
    ActivePermissionProfile | None
) = None

Selected native profile, absent in legacy rollouts.

permission_mode property

permission_mode: CodexPermissionMode

profile_matches_sandbox pydantic-validator

profile_matches_sandbox() -> Self
Source code in octomate/tentacles/codex/transcript.py
@model_validator(mode="after")
def profile_matches_sandbox(self) -> Self:
    profile = self.active_permission_profile
    if isinstance(self.sandbox_policy, FullAccessPolicy):
        if profile is not None and profile.id != ":danger-full-access":
            raise ValueError("Native profile does not match sandbox_policy")
        return self
    strict = profile is not None and profile.id == "octomate-workspace"
    flags = (
        self.sandbox_policy.exclude_tmpdir_env_var,
        self.sandbox_policy.exclude_slash_tmp,
    )
    if flags != (strict, strict) or (
        profile is not None
        and profile.id not in {":workspace", "octomate-workspace"}
    ):
        raise ValueError("Native profile does not match sandbox_policy")
    return self

is_injected_message

is_injected_message(item: JsonObject) -> bool

Injected instructions have no normalized archive message to retain.

Source code in octomate/tentacles/codex/transcript.py
def is_injected_message(item: JsonObject) -> bool:
    """Injected instructions have no normalized archive message to retain."""
    if item.get("type") != "message":
        return False
    if item.get("role") in {"system", "developer"}:
        return True
    metadata = item.get("internal_chat_message_metadata_passthrough")
    if item.get("role") != "user" or not isinstance(metadata, dict):
        return False
    kinds = metadata.get("content_item_kinds")
    return isinstance(kinds, list) and "user.text" not in kinds

context_item_id

context_item_id(item: JsonObject) -> str | None

The runtime identity of a modeled item, including tool results without ids.

Source code in octomate/tentacles/codex/transcript.py
def context_item_id(item: JsonObject) -> str | None:
    """The runtime identity of a modeled item, including tool results without ids."""
    kind = item.get("type")
    if kind in {
        "function_call",
        "custom_tool_call",
        "function_call_output",
        "custom_tool_call_output",
    }:
        call_id = item.get("call_id")
        if isinstance(call_id, str):
            return ("return:" if kind.endswith("output") else "call:") + call_id
    value = item.get("id")
    return value if isinstance(value, str) else None

payload_type

payload_type(line: RolloutLine) -> str | None
Source code in octomate/tentacles/codex/transcript.py
def payload_type(line: RolloutLine) -> str | None:
    value = line.payload.get("type")
    return value if isinstance(value, str) else None

octomate.tentacles.codex.tailer

Assembly of native Codex turns from a streamed rollout.

Lines streamed in by octomate codex tail feed CodexTranscriptTailer, which commits each completed turn as an ExternalAgentRun.

logger module-attribute

logger = logging.getLogger(__name__)

COMMIT_LOCK_TIMEOUT module-attribute

COMMIT_LOCK_TIMEOUT = 30.0

PendingCompaction dataclass

The committed replacement waiting for its native completion item ID.

Source code in octomate/tentacles/codex/tailer.py
@dataclass
class PendingCompaction:
    """The committed replacement waiting for its native completion item ID."""

    line: RolloutLine
    start: int  # Inclusive byte offset of the replacement record.
    end: int  # Exclusive byte offset of the replacement record.
    last_item_id: str | None

line instance-attribute

line: RolloutLine

start instance-attribute

start: int

end instance-attribute

end: int

last_item_id instance-attribute

last_item_id: str | None

OpenTurn dataclass

The turn being assembled off the stream.

Opened by a task_started line, closed by the task_complete or turn_aborted naming the same turn id.

Source code in octomate/tentacles/codex/tailer.py
@dataclass
class OpenTurn:
    """The turn being assembled off the stream.

    Opened by a `task_started` line, closed by the `task_complete` or `turn_aborted`
    naming the same turn id.
    """

    turn_id: str
    start_offset: int
    end_offset: int
    timestamp: datetime
    source: str | None
    model_name: str | None = None
    permission_mode: str | None = None
    messages: list[ModelMessage] = field(default_factory=list)
    answer: str = ""
    pending_calls: dict[str, NativeToolCallPart] = field(default_factory=dict)
    usage: RequestUsage | None = None
    part_index: int = 0
    native: NativeTurn | None = None
    compacted: bool = False  # A validated compaction completed within this task.
    has_response_items: bool = False  # Includes pending or unsupported model items.
    compaction: PendingCompaction | None = None
    visualizations: dict[int, list[HtmlSnapshot]] = field(
        default_factory=dict
    )  # Snapshots keyed by their model message position.
    unpaired_prompts: list[tuple[str, str, int]] = field(
        default_factory=list
    )  # Source representation and text awaiting their counterpart in a mixed rollout.
    ide_context: str | None = None  # Supplied IDE context awaiting its human prompt.

    def consume_prompt(self, line: RolloutLine) -> str | TextContent | None:
        """Read human text once per source occurrence, pairing mirrored formats.

        Pair across representations rather than deduplicating by text: the user
        can send identical prompts twice in one turn, including while it runs.
        """
        if line.type == "event_msg" and payload_type(line) == "user_message":
            text = line.payload.get("message")
            if not isinstance(text, str):
                return None
        elif line.type == "response_item" and line.payload.get("role") == "user":
            try:
                item = UserMessageItem.model_validate(line.payload)
            except ValidationError:
                return None
            kinds = item.metadata.content_item_kinds
            if item.metadata.turn_id != self.turn_id or len(kinds) != len(item.content):
                return None
            for part, kind in zip(item.content, kinds, strict=True):
                if (
                    kind == "additional_content.ide_context"
                    and part.type == "input_text"
                    and part.text
                ):
                    self.ide_context = part.text
            text = "\n".join(
                part.text
                for part, kind in zip(item.content, kinds, strict=True)
                if kind == "user.text" and part.type == "input_text" and part.text
            )
        else:
            return None
        if not text:
            return None
        for index, (source, previous, position) in enumerate(self.unpaired_prompts):
            if source != line.type and previous == text:
                self.unpaired_prompts.pop(index)
                identity = context_item_id(line.payload)
                if identity is not None and position < len(self.messages):
                    self.messages[position].metadata = {
                        **(self.messages[position].metadata or {}),
                        "native_item_ids": [identity],
                    }
                self.ide_context = None
                return None
        self.unpaired_prompts.append((line.type, text, len(self.messages)))
        context, self.ide_context = self.ide_context, None
        return prompt_content(text, ide_context=context)

turn_id instance-attribute

turn_id: str

start_offset instance-attribute

start_offset: int

end_offset instance-attribute

end_offset: int

timestamp instance-attribute

timestamp: datetime

source instance-attribute

source: str | None

model_name class-attribute instance-attribute

model_name: str | None = None

permission_mode class-attribute instance-attribute

permission_mode: str | None = None

messages class-attribute instance-attribute

messages: list[ModelMessage] = field(default_factory=list)

answer class-attribute instance-attribute

answer: str = ''

pending_calls class-attribute instance-attribute

pending_calls: dict[str, NativeToolCallPart] = field(
    default_factory=dict
)

usage class-attribute instance-attribute

usage: RequestUsage | None = None

part_index class-attribute instance-attribute

part_index: int = 0

native class-attribute instance-attribute

native: NativeTurn | None = None

compacted class-attribute instance-attribute

compacted: bool = False

has_response_items class-attribute instance-attribute

has_response_items: bool = False

compaction class-attribute instance-attribute

compaction: PendingCompaction | None = None

visualizations class-attribute instance-attribute

visualizations: dict[int, list[HtmlSnapshot]] = field(
    default_factory=dict
)

unpaired_prompts class-attribute instance-attribute

unpaired_prompts: list[tuple[str, str, int]] = field(
    default_factory=list
)

ide_context class-attribute instance-attribute

ide_context: str | None = None

consume_prompt

consume_prompt(
    line: RolloutLine,
) -> str | TextContent | None

Read human text once per source occurrence, pairing mirrored formats.

Pair across representations rather than deduplicating by text: the user can send identical prompts twice in one turn, including while it runs.

Source code in octomate/tentacles/codex/tailer.py
def consume_prompt(self, line: RolloutLine) -> str | TextContent | None:
    """Read human text once per source occurrence, pairing mirrored formats.

    Pair across representations rather than deduplicating by text: the user
    can send identical prompts twice in one turn, including while it runs.
    """
    if line.type == "event_msg" and payload_type(line) == "user_message":
        text = line.payload.get("message")
        if not isinstance(text, str):
            return None
    elif line.type == "response_item" and line.payload.get("role") == "user":
        try:
            item = UserMessageItem.model_validate(line.payload)
        except ValidationError:
            return None
        kinds = item.metadata.content_item_kinds
        if item.metadata.turn_id != self.turn_id or len(kinds) != len(item.content):
            return None
        for part, kind in zip(item.content, kinds, strict=True):
            if (
                kind == "additional_content.ide_context"
                and part.type == "input_text"
                and part.text
            ):
                self.ide_context = part.text
        text = "\n".join(
            part.text
            for part, kind in zip(item.content, kinds, strict=True)
            if kind == "user.text" and part.type == "input_text" and part.text
        )
    else:
        return None
    if not text:
        return None
    for index, (source, previous, position) in enumerate(self.unpaired_prompts):
        if source != line.type and previous == text:
            self.unpaired_prompts.pop(index)
            identity = context_item_id(line.payload)
            if identity is not None and position < len(self.messages):
                self.messages[position].metadata = {
                    **(self.messages[position].metadata or {}),
                    "native_item_ids": [identity],
                }
            self.ide_context = None
            return None
    self.unpaired_prompts.append((line.type, text, len(self.messages)))
    context, self.ide_context = self.ide_context, None
    return prompt_content(text, ide_context=context)

SubagentCall dataclass

One sub_agent_activity line of the parent rollout.

The parent turn and tool call that started or prompted a child thread, and when, so the child's runs can be linked back to it.

Source code in octomate/tentacles/codex/tailer.py
@dataclass(frozen=True)
class SubagentCall:
    """One `sub_agent_activity` line of the parent rollout.

    The parent turn and tool call that started or prompted a child thread, and
    when, so the child's runs can be linked back to it.
    """

    parent_run_id: str
    parent_tool_call_id: str
    occurred_at_ms: int

parent_run_id instance-attribute

parent_run_id: str

parent_tool_call_id instance-attribute

parent_tool_call_id: str

occurred_at_ms instance-attribute

occurred_at_ms: int

SubagentTail dataclass

One child thread's rollout within a session's tail.

Its own cursor, conversation, and open turn, plus the parent calls already linked to its committed runs.

Source code in octomate/tentacles/codex/tailer.py
@dataclass
class SubagentTail:
    """One child thread's rollout within a session's tail.

    Its own cursor, conversation, and open turn, plus the parent calls already
    linked to its committed runs.
    """

    thread_id: str
    path: Path
    name: str = ""  # Final component of the runtime's agent path.
    cwd: str = ""  # from the child rollout's own session metadata
    offset: int = 0
    conversation: Conversation | None = None
    recorded: set[str] = field(default_factory=set)
    open_turn: OpenTurn | None = None
    own_turns_started: bool = False
    last_item_id: str | None = None
    compactions_pending: bool = False
    message_identities: UserMessageIdentities = field(
        default_factory=UserMessageIdentities
    )
    linked_call_ids: set[str] = field(default_factory=set)

thread_id instance-attribute

thread_id: str

path instance-attribute

path: Path

name class-attribute instance-attribute

name: str = ''

cwd class-attribute instance-attribute

cwd: str = ''

offset class-attribute instance-attribute

offset: int = 0

conversation class-attribute instance-attribute

conversation: Conversation | None = None

recorded class-attribute instance-attribute

recorded: set[str] = field(default_factory=set)

open_turn class-attribute instance-attribute

open_turn: OpenTurn | None = None

own_turns_started class-attribute instance-attribute

own_turns_started: bool = False

last_item_id class-attribute instance-attribute

last_item_id: str | None = None

compactions_pending class-attribute instance-attribute

compactions_pending: bool = False

message_identities class-attribute instance-attribute

message_identities: UserMessageIdentities = field(
    default_factory=UserMessageIdentities
)

linked_call_ids class-attribute instance-attribute

linked_call_ids: set[str] = field(default_factory=set)

TailState dataclass

One streamed session. Its rollout lives on the client machine that streams it (octomate codex tail); the stream route feeds feed_remote, which drives the per-line assembly. transcript_path is the client's claim in the client's own namespace, a label never opened here, and the subagent tails' paths are likewise the client's labels for its sibling files.

Source code in octomate/tentacles/codex/tailer.py
@dataclass
class TailState:
    """One streamed session. Its rollout lives on the client machine that streams it
    (`octomate codex tail`); the stream route feeds `feed_remote`, which drives the
    per-line assembly. `transcript_path` is the client's claim in the client's own
    namespace, a label never opened here, and the subagent tails' paths are likewise
    the client's labels for its sibling files."""

    session_id: str
    transcript_path: Path
    stop_event: asyncio.Event
    # The verified bearer's own profile — who every ledger row this stream
    # writes is attributed to.
    sender: UserProfile
    address: ChannelAddress
    impulses: ObjectSendStream[Impulse]
    catchup_end: int = (
        0  # Initial root transcript length advertised by this connection.
    )
    offset: int = 0
    conversation: Conversation | None = None
    recorded: set[str] = field(default_factory=set)
    thread_id: str | None = None
    cwd: str = ""  # from the rollout's session metadata
    source: str | None = None
    open_turn: OpenTurn | None = None
    last_item_id: str | None = None
    compactions_pending: bool = False
    message_identities: UserMessageIdentities = field(
        default_factory=UserMessageIdentities
    )
    subagents: dict[str, SubagentTail] = field(default_factory=dict)
    subagent_calls: dict[str, list[SubagentCall]] = field(default_factory=dict)
    classified_rollouts: set[Path] = field(default_factory=set)
    # Stop requests a drain after this turn's terminal transcript line commits.
    drain_turn: str | None = None

session_id instance-attribute

session_id: str

transcript_path instance-attribute

transcript_path: Path

stop_event instance-attribute

stop_event: Event

sender instance-attribute

sender: UserProfile

address instance-attribute

address: ChannelAddress

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

catchup_end class-attribute instance-attribute

catchup_end: int = 0

offset class-attribute instance-attribute

offset: int = 0

conversation class-attribute instance-attribute

conversation: Conversation | None = None

recorded class-attribute instance-attribute

recorded: set[str] = field(default_factory=set)

thread_id class-attribute instance-attribute

thread_id: str | None = None

cwd class-attribute instance-attribute

cwd: str = ''

source class-attribute instance-attribute

source: str | None = None

open_turn class-attribute instance-attribute

open_turn: OpenTurn | None = None

last_item_id class-attribute instance-attribute

last_item_id: str | None = None

compactions_pending class-attribute instance-attribute

compactions_pending: bool = False

message_identities class-attribute instance-attribute

message_identities: UserMessageIdentities = field(
    default_factory=UserMessageIdentities
)

subagents class-attribute instance-attribute

subagents: dict[str, SubagentTail] = field(
    default_factory=dict
)

subagent_calls class-attribute instance-attribute

subagent_calls: dict[str, list[SubagentCall]] = field(
    default_factory=dict
)

classified_rollouts class-attribute instance-attribute

classified_rollouts: set[Path] = field(default_factory=set)

drain_turn class-attribute instance-attribute

drain_turn: str | None = None

CodexTranscriptTailer

Assembles Codex turns from rollout lines streamed in by octomate codex tail.

The stream is the only assembler — the server never opens a rollout file, even for a session on this machine. Hooks establish sessions; only the rollout writes runs, prompts, response items, tool activity, reasoning and usage. Each connection publishes run brackets and whole-item events at its native address. Committed and driven turns stay silent; replay of an open turn starts a fresh fold. The end is published only after the run and ledger are durable. Codex documents transcript_path for hook convenience while warning that its format is unstable, so parsing is deliberately narrow and fail-forward.

A parser update does not repair completed imports. To repair a session, stop its tail and verify the full procedure on a consistent database copy first: identify only its external runs missing prompts, load those ExternalAgentRun schemas through Arcanus, clear their end_offset, and commit. Re-stream the complete original rollout with the same session id and verified sender. record_external_run replaces the incomplete model history in transcript order; bind_native_run reuses each existing reply's ledger row by turn id. Compare run ids, reply ledger ids, prompt timestamps and bindings before and after, and replay again to check idempotency. Model message ids are replaced, so inspect shared histories and artifact bindings before selecting any turn. Never clear offsets automatically or change a live database without approval.

Source code in octomate/tentacles/codex/tailer.py
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
class CodexTranscriptTailer:
    """Assembles Codex turns from rollout lines streamed in by `octomate codex tail`.

    The stream is the only assembler — the server never opens a rollout file, even
    for a session on this machine. Hooks establish sessions; only the rollout
    writes runs, prompts, response items, tool activity, reasoning and usage.
    Each connection publishes run brackets and whole-item events at its native
    address. Committed and driven turns stay silent; replay of an open turn starts
    a fresh fold. The end is published only after the run and ledger are durable. Codex
    documents `transcript_path` for hook convenience while warning that its format
    is unstable, so parsing is deliberately narrow and fail-forward.

    A parser update does not repair completed imports. To repair a session, stop
    its tail and verify the full procedure on a consistent database copy first:
    identify only its external runs missing prompts, load those `ExternalAgentRun`
    schemas through Arcanus, clear their `end_offset`, and commit. Re-stream the
    complete original rollout with the same session id and verified sender.
    `record_external_run` replaces the incomplete model history in transcript
    order; `bind_native_run` reuses each existing reply's ledger row by turn id.
    Compare run ids, reply ledger ids, prompt timestamps and bindings before and
    after, and replay again to check idempotency. Model message ids are replaced,
    so inspect shared histories and artifact bindings before selecting any turn.
    Never clear offsets automatically or change a live database without approval.
    """

    agent_tentacle_id: str

    def __init__(
        self,
        conversations: ConversationManager,
        threads: ThreadManager,
        files: FileManager,
        locks: SessionLocks | None = None,
        *,
        agent_tentacle_id: str,
    ) -> None:
        self.agent_tentacle_id = agent_tentacle_id
        self.conversation_manager = conversations
        self.thread_manager = threads
        self.files: FileManager = files
        self.locks = locks if locks is not None else SessionLocks()
        self.sessions: dict[str, TailState] = {}

    async def stop_turn(self, session_id: str, turn_id: str | None) -> None:
        """Request a drain after this turn's terminal line, without holding Stop.

        Codex may flush the reply and `task_complete` only after its hook returns.
        A timeout must not finalize the stream before those bytes arrive. An open
        turn stays attached until its matching terminal line commits; a turn already
        finished can drain immediately. Without a turn id, the idle limit owns exit.
        """
        state = self.sessions.get(session_id)
        if state is None or turn_id is None:
            return
        state.drain_turn = turn_id
        if turn_id in state.recorded and (
            state.open_turn is None or state.open_turn.turn_id != turn_id
        ):
            state.stop_event.set()

    async def shutdown(self) -> None:
        self.sessions.clear()

    async def attach_remote(
        self,
        session_id: str,
        transcript_path: Path,
        sender: UserProfile,
        address: ChannelAddress,
        impulses: ObjectSendStream[Impulse],
    ) -> tuple[TailState, dict[UUID7, int]]:
        """Register a streamed session — its rollout lives on the client machine
        that streams it (`octomate codex tail`) — and answer where its files resume.

        The answer is always byte 0: a rollout's head is load-bearing (`session_meta`
        carries the thread id every child classification checks against, and the
        parent's `sub_agent_activity` lines are what link child runs to their spawning
        calls), so a reconnect re-streams whole files and the committed-turn guard
        skips what is already durable. Child files are not named here either: the
        client registers each file by its opening `session_meta` and receives
        its conversation UUID.

        A lingering registration (its client died without a close) is replaced; the
        dead route feeds the state object it attached, and its commits are
        idempotent.
        """
        state = TailState(
            session_id, transcript_path, asyncio.Event(), sender, address, impulses
        )
        state.conversation = await self.ensure_session(session_id)
        state.recorded = state.conversation.native_run_ids
        self.sessions[session_id] = state
        logger.info("session %s: remote tail attached", session_id)
        return state, {state.conversation.id: 0}

    async def feed_remote(
        self,
        state: TailState,
        key: str | None,
        raw: str,
        start: int,
        end: int,
        *,
        visualizations: list[HtmlSnapshot] | None = None,
    ) -> None:
        """Advance a remote session by one framed line — the pumps' per-line body,
        against offsets the client measured in its own file. Takes the state rather
        than a session id so a superseded connection keeps feeding the state it
        attached, never whoever registered after it. `key` is None for the session's
        own rollout, else the client's label for a sibling file."""
        if key is None:
            state.offset = end
            try:
                line = rollout_line_adapter.validate_json(raw)
            except ValidationError:
                logger.debug("skipping unmodeled Codex rollout line")
                line = None
            if state.open_turn is not None and state.open_turn.native is not None:
                state.open_turn.native.replay = end <= state.catchup_end
            if line is not None:
                await self.process_line(
                    state, line, start, end, visualizations=visualizations
                )
            if state.catchup_end and end >= state.catchup_end:
                state.catchup_end = 0
                if state.open_turn is not None and state.open_turn.native is not None:
                    await state.open_turn.native.caught_up()
                else:
                    await state.impulses.send(Impulse(RunEndedEvent(), state.address))
            return
        tail = await self.remote_subagent(state, key, raw)
        if tail is None:
            return
        tail.offset = end
        try:
            line = rollout_line_adapter.validate_json(raw)
        except ValidationError:
            logger.debug(
                "skipping unmodeled Codex subagent line in session %s/%s",
                state.session_id,
                tail.thread_id,
            )
            return
        await self.process_subagent_line(state, tail, line, start, end)

    async def remote_subagent(
        self, state: TailState, key: str, raw: str
    ) -> SubagentTail | None:
        """The child tail a client label maps to, classified on first sight from the
        line in hand — `discover_subagent`'s test without the disk read it cannot do
        here. The first line is the file's `session_meta`, because every remote file
        streams from byte 0; a label that names no child of this session is
        remembered and its lines dropped."""
        path = Path(key)
        for tail in state.subagents.values():
            if tail.path == path:
                return tail
        if path in state.classified_rollouts:
            return None
        if state.thread_id is None:
            return None
        try:
            line = rollout_line_adapter.validate_json(raw)
            if line.type != "session_meta":
                return None
            metadata = session_metadata_adapter.validate_python(line.payload)
        except ValidationError:
            logger.debug("skipping remote rollout with malformed metadata: %s", key)
            return None
        state.classified_rollouts.add(path)
        tail = self.subagent_from_metadata(state, metadata, path)
        if tail is None:
            return None
        await self.prepare_subagent(state, tail)
        return tail

    def detach_remote(self, state: TailState) -> None:
        """Drop a remote session's registration. Nothing commits on the way out, eof
        or not — a Codex turn closes on its own `task_complete`/`turn_aborted` line,
        so a turn still open here is mid-flight, and committing it would plant its id
        in the committed-turn guard where the completed version could never replace
        it. The next connect re-streams from byte 0 and the closed turn lands whole."""
        if self.sessions.get(state.session_id) is state:
            del self.sessions[state.session_id]

    async def ensure_session(self, session_id: str) -> Conversation:
        thread = await self.thread_manager.ensure(
            ThreadKey(
                channel_tentacle_id=self.agent_tentacle_id,
                chat_type="thread",
                chat_id=session_id,
            ),
            native=True,
        )
        return await self.conversation_manager.ensure(
            thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
        )

    async def process_line(
        self,
        state: TailState,
        line: RolloutLine,
        start: int,
        end: int,
        *,
        visualizations: list[HtmlSnapshot] | None = None,
    ) -> None:
        state.message_identities.consume(line, state.session_id)
        if line.type == "response_item" and not is_injected_message(line.payload):
            state.last_item_id = context_item_id(line.payload)
        if line.type == "compacted":
            await self.record_compaction(state, line, start, end)
            return
        kind = payload_type(line)
        if line.type == "session_meta":
            try:
                metadata = session_metadata_adapter.validate_python(line.payload)
            except ValidationError:
                logger.debug("skipping malformed Codex session metadata")
                return
            state.thread_id = metadata.id or state.thread_id or state.session_id
            state.cwd = metadata.cwd
            state.source = metadata.originator or (
                metadata.source if isinstance(metadata.source, str) else None
            )
            return
        if line.type == "event_msg" and kind == "task_started":
            turn_id = line.payload.get("turn_id")
            if not isinstance(turn_id, str) or not turn_id:
                return
            if state.open_turn is not None:
                await self.close_turn(state)
            state.open_turn = OpenTurn(
                turn_id=turn_id,
                start_offset=start,
                end_offset=end,
                timestamp=line.timestamp,
                source=state.source,
            )
            state.open_turn.native = await NativeTurn.open(
                run_id=turn_id,
                recorded=state.recorded,
                conversations=self.conversation_manager,
                threads=self.thread_manager,
                locks=self.locks,
                address=state.address,
                sender=state.sender,
                impulses=state.impulses,
                messages=state.open_turn.messages,
                replay=end <= state.catchup_end,
            )
            return
        turn = state.open_turn
        if turn is None:
            return
        turn.end_offset = end
        if line.type == "event_msg" and kind == "item_completed":
            await self.identify_compaction(state, turn, line)
        if line.type == "turn_context":
            self.consume_turn_context(turn, line)
            return
        if (
            turn.native is not None
            and (prompt := turn.consume_prompt(line)) is not None
        ):
            await turn.native.prompt(
                message_id=turn.turn_id
                if not turn.native.prompts
                else f"{turn.turn_id}:{start}",
                text=prompt,
                timestamp=line.timestamp,
                metadata={
                    **codex_metadata(),
                    "native_item_ids": [context_item_id(line.payload)]
                    if context_item_id(line.payload)
                    else [],
                },
            )
            return
        if line.type == "response_item" and turn.native is not None:
            turn.has_response_items = True
            if visualizations:
                if state.sender.user_id is None:
                    raise ValueError(
                        "HTML capture requires a registered artifact owner"
                    )
                turn.visualizations[len(turn.messages)] = visualizations
            await turn.native.fold(
                self.consume_response_item(turn, line, captured=bool(visualizations))
            )
            return
        if line.type != "event_msg":
            return
        if kind == "item_completed" and turn.native is not None:
            await turn.native.fold(self.consume_completed_command(turn, line))
        elif kind == "token_count":
            turn.usage = self.parse_usage(line.payload)
        elif kind == "sub_agent_activity":
            child_thread_id = line.payload.get("agent_thread_id")
            tool_call_id = line.payload.get("event_id")
            occurred_at_ms = line.payload.get("occurred_at_ms")
            activity_kind = line.payload.get("kind")
            if (
                isinstance(child_thread_id, str)
                and isinstance(tool_call_id, str)
                and isinstance(occurred_at_ms, int)
                and activity_kind in {"started", "interacted"}
            ):
                state.subagent_calls.setdefault(child_thread_id, []).append(
                    SubagentCall(turn.turn_id, tool_call_id, occurred_at_ms)
                )
        elif kind in {"task_complete", "turn_aborted"}:
            ended_id = line.payload.get("turn_id")
            if ended_id == turn.turn_id:
                # An aborted turn is still real work in the file — commit what it
                # reached, as an interrupted Claude turn commits at the next
                # prompt. (`turn_aborted` carries no last message; the fallback
                # read is a no-op there.)
                fallback = line.payload.get("last_agent_message")
                if not turn.answer and isinstance(fallback, str):
                    turn.answer = answer_part(
                        visualization_text(fallback, final=True)[0]
                        if turn.visualizations
                        else fallback
                    ).content
                await self.close_turn(state)
                if ended_id == state.drain_turn:
                    state.stop_event.set()

    def subagent_from_metadata(
        self, state: TailState, metadata: SessionMetadata, path: Path
    ) -> SubagentTail | None:
        """A new child tail when the metadata names a thread-spawned child of this
        session — the test `remote_subagent` runs against a file's streamed opening
        line."""
        source = metadata.source
        spawn = (
            source.subagent.thread_spawn
            if source is not None
            and not isinstance(source, str)
            and source.subagent is not None
            else None
        )
        if (
            spawn is None
            or metadata.session_id != state.session_id
            or spawn.parent_thread_id != state.thread_id
            or not metadata.id
            or self.uuid7_timestamp(metadata.id) is None
        ):
            return None
        tail = SubagentTail(
            thread_id=metadata.id,
            path=path,
            cwd=metadata.cwd,
            name=spawn.agent_path.rsplit("/", 1)[-1],
        )
        state.subagents[tail.thread_id] = tail
        return tail

    async def prepare_subagent(self, state: TailState, tail: SubagentTail) -> None:
        """The child's durable state: its conversation under the parent's, and the
        committed-turn guard seeded from what is already assembled."""
        parent = state.conversation
        assert parent is not None
        tail.conversation = await self.conversation_manager.ensure(
            parent.thread_id,
            agent_tentacle_id=self.agent_tentacle_id,
            native=True,
            subagent_id=tail.thread_id,
            name=tail.name,
            parent_conversation_id=parent.id,
        )
        tail.recorded = tail.conversation.native_run_ids
        tail.linked_call_ids = {
            run.parent_tool_call_id
            for run in tail.conversation.runs
            if run.parent_tool_call_id is not None
        }

    async def process_subagent_line(
        self,
        state: TailState,
        tail: SubagentTail,
        line: RolloutLine,
        start: int,
        end: int,
    ) -> None:
        tail.message_identities.consume(line, tail.thread_id)
        if line.type == "response_item" and not is_injected_message(line.payload):
            tail.last_item_id = context_item_id(line.payload)
        if line.type == "compacted":
            if tail.own_turns_started:
                await self.record_compaction(state, line, start, end, tail=tail)
            return
        kind = payload_type(line)
        if line.type == "event_msg" and kind == "task_started":
            turn_id = line.payload.get("turn_id")
            if not isinstance(turn_id, str) or not turn_id:
                return
            if not tail.own_turns_started:
                if not self.turn_belongs_to_subagent(tail.thread_id, turn_id):
                    return
                tail.own_turns_started = True
            await self.close_subagent_turn(state, tail)
            tail.open_turn = OpenTurn(
                turn_id=turn_id,
                start_offset=start,
                end_offset=end,
                timestamp=line.timestamp,
                source="subagent",
            )
            return
        turn = tail.open_turn
        if turn is not None and line.type == "event_msg" and kind == "item_completed":
            await self.identify_compaction(state, turn, line, tail=tail)
        if turn is None or turn.turn_id in tail.recorded:
            return
        turn.end_offset = end
        if line.type == "turn_context":
            self.consume_turn_context(turn, line)
            return
        if (prompt := turn.consume_prompt(line)) is not None:
            content = prompt
            turn.messages.append(
                ModelRequest(
                    parts=[
                        UserPromptPart(
                            content=[content]
                            if isinstance(content, TextContent)
                            else content,
                            timestamp=line.timestamp,
                        )
                    ],
                    timestamp=line.timestamp,
                    metadata={
                        **codex_metadata(),
                        "native_item_ids": [context_item_id(line.payload)]
                        if context_item_id(line.payload)
                        else [],
                    },
                )
            )
            return
        if line.type == "response_item":
            turn.has_response_items = True
            for _ in self.consume_response_item(turn, line):
                pass
            return
        if line.type != "event_msg":
            return
        if kind == "item_completed":
            for _ in self.consume_completed_command(turn, line):
                pass
        elif kind == "token_count":
            turn.usage = self.parse_usage(line.payload)
        elif kind in {"task_complete", "turn_aborted"}:
            ended_id = line.payload.get("turn_id")
            if ended_id == turn.turn_id:
                fallback = line.payload.get("last_agent_message")
                if not turn.answer and isinstance(fallback, str):
                    turn.answer = answer_part(fallback).content
                await self.close_subagent_turn(state, tail)

    async def record_compaction(
        self,
        state: TailState,
        line: RolloutLine,
        start: int,
        end: int,
        *,
        tail: SubagentTail | None = None,
        native_compaction_id: str | None = None,
        last_item_id: str | None = None,
    ) -> None:
        """Capture summary/checkpoint content without changing the archived turn."""
        try:
            item = CompactedItem.model_validate(line.payload)
            before = (
                last_item_id
                if native_compaction_id is not None
                else (tail or state).last_item_id
            )
            messages = item.to_messages(
                line.timestamp,
                last_item_id=before,
                item_aliases=(tail or state).message_identities.aliases,
            )
        except ValidationError:
            logger.debug("skipping malformed Codex compaction")
            return
        conversation = tail.conversation if tail is not None else state.conversation
        assert conversation is not None
        # TODO: Preserve the native compaction trigger when Codex exposes a reliable manual/auto signal.
        await self.conversation_manager.record_external_compaction(
            conversation,
            native_session_id=tail.thread_id if tail is not None else state.session_id,
            native_compaction_id=native_compaction_id,
            source=str(tail.path if tail is not None else state.transcript_path),
            start_offset=start,
            end_offset=end,
            happened_at=line.timestamp,
            messages=messages,
        )
        (tail or state).compactions_pending = True
        if native_compaction_id is None and messages:
            context = NativeMessage.model_validate(
                messages[0].metadata or {}
            ).compaction_context
            (tail or state).last_item_id = (
                context.replacement_ids[-1]
                if context is not None and context.replacement_ids
                else None
            )
        turn = tail.open_turn if tail is not None else state.open_turn
        if turn is None:
            await self.conversation_manager.record_native_memberships(
                conversation,
                tail.thread_id if tail else state.session_id,
            )
            (tail or state).compactions_pending = False
        if turn is not None:
            turn.compacted = True
            if native_compaction_id is None:
                turn.compaction = PendingCompaction(line, start, end, before)

    async def identify_compaction(
        self,
        state: TailState,
        turn: OpenTurn,
        line: RolloutLine,
        *,
        tail: SubagentTail | None = None,
    ) -> None:
        """Bind the following completion ID to the already durable replacement."""
        pending = turn.compaction
        if pending is None:
            return
        try:
            event = CompactionCompletedEvent.model_validate(line.payload)
        except ValidationError:
            return
        session_id = tail.thread_id if tail is not None else state.session_id
        if event.thread_id != session_id or event.turn_id != turn.turn_id:
            return
        await self.record_compaction(
            state,
            pending.line,
            pending.start,
            pending.end,
            tail=tail,
            native_compaction_id=event.item.id,
            last_item_id=pending.last_item_id,
        )
        turn.compaction = None

    async def close_subagent_turn(self, state: TailState, tail: SubagentTail) -> None:
        turn = tail.open_turn
        tail.open_turn = None
        if turn is None or turn.turn_id in tail.recorded or not turn.messages:
            return
        for message in reversed(turn.messages):
            if isinstance(message, ModelResponse):
                if turn.usage is not None:
                    message.usage = turn.usage
                break
        conversation = tail.conversation
        assert conversation is not None
        with codex_logfire.span(
            "codex.tailer.commit_subagent_turn {turn_id} [{session_id}]",
            turn_id=turn.turn_id,
            session_id=state.session_id,
            child_thread_id=tail.thread_id,
            start_offset=turn.start_offset,
            end_offset=turn.end_offset,
            messages=len(turn.messages),
        ) as span:
            async with self.locks.hold(
                state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
            ):
                call = next(
                    (
                        candidate
                        for candidate in reversed(
                            state.subagent_calls.get(tail.thread_id, [])
                        )
                        if candidate.occurred_at_ms
                        <= int(turn.timestamp.timestamp() * 1000)
                        and candidate.parent_tool_call_id not in tail.linked_call_ids
                    ),
                    None,
                )
                run = await self.conversation_manager.record_external_run(
                    conversation,
                    run_id=turn.turn_id,
                    messages=turn.messages,
                    name=self.agent_tentacle_id,
                    model_name=turn.model_name,
                    context_used=turn.usage.input_tokens
                    if turn.usage is not None
                    else None,
                    context_window=turn.usage.details.get("model_context_window")
                    if turn.usage is not None
                    else None,
                    permission_mode=turn.permission_mode,
                    cwd=Path(tail.cwd) if tail.cwd else None,
                    native_session_id=tail.thread_id,
                    source=turn.source,
                    start_offset=turn.start_offset,
                    end_offset=turn.end_offset,
                    parent_run_id=call.parent_run_id if call is not None else None,
                    parent_tool_call_id=call.parent_tool_call_id
                    if call is not None
                    else None,
                )
                span.set_attribute("committed", run is not None)
                if run is None:
                    return
                tail.recorded.add(turn.turn_id)
                if tail.compactions_pending:
                    await self.conversation_manager.record_native_memberships(
                        conversation, tail.thread_id
                    )
                    tail.compactions_pending = False
                if call is not None:
                    tail.linked_call_ids.add(call.parent_tool_call_id)
                logger.info(
                    "session %s: subagent %s turn %s synced — %d messages, bytes %d-%d",
                    state.session_id,
                    tail.thread_id,
                    turn.turn_id,
                    len(turn.messages),
                    turn.start_offset,
                    turn.end_offset,
                )

    async def close_turn(self, state: TailState) -> None:
        turn = state.open_turn
        state.open_turn = None
        if turn is None or turn.native is None:
            if state.compactions_pending and state.conversation is not None:
                await self.conversation_manager.record_native_memberships(
                    state.conversation, state.session_id
                )
                state.compactions_pending = False
            return
        for message in reversed(turn.messages):
            if isinstance(message, ModelResponse):
                if turn.usage is not None:
                    message.usage = turn.usage
                break
        conversation = state.conversation
        assert conversation is not None
        if (
            turn.compacted
            and not turn.messages
            and not turn.answer
            and not turn.has_response_items
        ):
            await turn.native.settle(turn.turn_id)
            if state.compactions_pending:
                await self.conversation_manager.record_native_memberships(
                    conversation, state.session_id
                )
                state.compactions_pending = False
            return
        with codex_logfire.span(
            "codex.tailer.commit_turn {turn_id} [{session_id}]",
            turn_id=turn.turn_id,
            session_id=state.session_id,
            start_offset=turn.start_offset,
            end_offset=turn.end_offset,
            messages=len(turn.messages),
        ) as span:
            async with self.locks.hold(
                state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
            ):
                run = await self.conversation_manager.record_external_run(
                    conversation,
                    run_id=turn.turn_id,
                    messages=turn.messages,
                    name=self.agent_tentacle_id,
                    model_name=turn.model_name,
                    context_used=turn.usage.input_tokens
                    if turn.usage is not None
                    else None,
                    context_window=turn.usage.details.get("model_context_window")
                    if turn.usage is not None
                    else None,
                    permission_mode=turn.permission_mode,
                    cwd=Path(state.cwd) if state.cwd else None,
                    native_session_id=state.session_id,
                    source=turn.source,
                    start_offset=turn.start_offset,
                    end_offset=turn.end_offset,
                )
                span.set_attribute("committed", run is not None)
                if run is not None:
                    await self.capture_html(state, turn, run)
                if state.compactions_pending:
                    await self.conversation_manager.record_native_memberships(
                        conversation, state.session_id
                    )
                    state.compactions_pending = False
                await turn.native.close(run, run_id=turn.turn_id, answer=turn.answer)
                logger.info(
                    "session %s: turn %s synced — %d messages, bytes %d-%d",
                    state.session_id,
                    turn.turn_id,
                    len(turn.messages),
                    turn.start_offset,
                    turn.end_offset,
                )

    async def capture_html(
        self, state: TailState, turn: OpenTurn, run: ExternalAgentRun
    ) -> None:
        """Persist client snapshots and bind them to the completed native response.

        The bearer supplies ownership; client paths are labels only. Artifacts use
        the existing file storage, ledger and event stream before the run closes.
        """
        if not turn.visualizations:
            return
        owner_id = state.sender.user_id
        conversation = state.conversation
        assert owner_id is not None
        assert turn.native is not None
        assert conversation is not None
        for position, snapshots in turn.visualizations.items():
            for snapshot in snapshots:
                reference = snapshot.reference
                with BytesIO(snapshot.html.encode("utf-8")) as source:
                    stored = await self.files.write(
                        UploadFile(
                            source,
                            filename=reference.path.name,
                            headers=Headers(
                                {"content-type": "text/html; charset=utf-8"}
                            ),
                        ),
                        owner_id=owner_id,
                    )
                message = await self.thread_manager.record_artifact(
                    conversation.thread_id,
                    HtmlArtifact(
                        owner_id=owner_id,
                        title=reference.title or reference.path.stem,
                        mode=reference.mode,
                        file_id=stored.id,
                    ),
                    sender=state.sender,
                    agent_tentacle_id=self.agent_tentacle_id,
                )
                await self.thread_manager.bind_messages(
                    [message.id],
                    run.messages[position].id,
                    kind="assistant_reply",
                    run_id=run.id,
                )
                await turn.native.fold(
                    [
                        ArtifactAvailableEvent(
                            message_id=message.id, artifact_id=message.artifact_id
                        )
                    ]
                )

    @staticmethod
    def turn_belongs_to_subagent(thread_id: str, turn_id: str) -> bool:
        thread_time = CodexTranscriptTailer.uuid7_timestamp(thread_id)
        turn_time = CodexTranscriptTailer.uuid7_timestamp(turn_id)
        return (
            thread_time is not None
            and turn_time is not None
            and turn_time >= thread_time
        )

    @staticmethod
    def uuid7_timestamp(value: str) -> int | None:
        try:
            parsed = UUID(value)
        except ValueError:
            return None
        if parsed.version != 7:
            return None
        return parsed.timestamp

    @staticmethod
    def parse_usage(payload: JsonObject) -> RequestUsage | None:
        info = payload.get("info")
        if not isinstance(info, dict):
            return None
        usage = info.get("last_token_usage")
        if not isinstance(usage, dict):
            return None
        values = {key: value for key, value in usage.items() if isinstance(value, int)}
        details = {"reasoning_output_tokens": values.get("reasoning_output_tokens", 0)}
        window = info.get("model_context_window")
        if isinstance(window, int) and not isinstance(window, bool) and window > 0:
            details["model_context_window"] = window
        return RequestUsage(
            input_tokens=values.get("input_tokens", 0),
            output_tokens=values.get("output_tokens", 0),
            cache_read_tokens=values.get("cached_input_tokens", 0),
            details=details,
        )

    @staticmethod
    def consume_turn_context(turn: OpenTurn, line: RolloutLine) -> None:
        model = line.payload.get("model")
        turn.model_name = model if isinstance(model, str) else None
        try:
            turn.permission_mode = TurnPermissions.model_validate(
                line.payload
            ).permission_mode
        except ValueError as error:
            # Custom native permissions are valid history, but not a forkable preset.
            turn.permission_mode = None
            reason = str(error)
            if isinstance(error, ValidationError):
                reason = "; ".join(
                    f"{'.'.join(map(str, detail['loc']))}: {detail['msg']}"
                    for detail in error.errors(
                        include_input=False, include_context=False, include_url=False
                    )
                )
            logger.debug(
                "Codex turn %s has no matching permission preset; "
                "history sync continues, but forking is unavailable: %s",
                turn.turn_id,
                reason,
            )

    @staticmethod
    def consume_completed_command(
        turn: OpenTurn, line: RolloutLine
    ) -> Iterator[AgentStreamEvent]:
        payload = line.payload.get("item")
        if not isinstance(payload, dict) or payload.get("type") != "CommandExecution":
            return
        item = CompletedCommandItem.model_validate(payload)
        if item.id in turn.pending_calls or any(
            isinstance(part, NativeToolCallPart) and part.tool_call_id == item.id
            for message in turn.messages
            for part in message.parts
        ):
            return
        call = NativeToolCallPart(
            tool_name="codex_command_execution",
            tool_call_id=item.id,
            args={
                "command": shlex.join(item.command),
                "cwd": item.cwd,
                "status": item.status,
                "commandActions": [model_json(action) for action in item.parsed_cmd],
            },
            provider_name=CODEX_PROVIDER_NAME,
        )
        outcome = (
            "success"
            if item.status == "completed"
            else "denied"
            if item.status == "declined"
            else "failed"
        )
        result = NativeToolReturnPart(
            tool_name=call.tool_name,
            tool_call_id=item.id,
            content=item.aggregated_output,
            outcome=outcome,
            provider_name=CODEX_PROVIDER_NAME,
        )
        turn.messages.append(
            ModelResponse(
                parts=[call, result],
                timestamp=line.timestamp,
                provider_name=CODEX_PROVIDER_NAME,
                provider_response_id=item.id,
                metadata=codex_metadata(),
            )
        )
        yield FunctionToolCallEvent(
            part=ToolCallPart(
                tool_name=call.tool_name,
                tool_call_id=item.id,
                args=call.args,
                provider_name=CODEX_PROVIDER_NAME,
            )
        )
        yield FunctionToolResultEvent(
            part=ToolReturnPart(
                tool_name=call.tool_name,
                tool_call_id=item.id,
                content=result.content,
                outcome=outcome,
            )
        )

    @staticmethod
    def consume_response_item(
        turn: OpenTurn, line: RolloutLine, *, captured: bool = False
    ) -> Iterator[AgentStreamEvent]:
        """Yield whole items, hiding captured references without editing the rollout."""
        payload = line.payload
        kind = payload_type(line)
        if kind == "message" and payload.get("role") == "assistant":
            texts: list[str] = []
            content = payload.get("content")
            if not isinstance(content, list):
                return
            for part in content:
                if isinstance(part, dict) and isinstance(
                    part_text := part.get("text"), str
                ):
                    texts.append(part_text)
            text = "\n".join(texts)
            if text:
                text = visualization_text(text, final=True)[0] if captured else text
                response_id = payload.get("id")
                part = answer_part(text)
                turn.messages.append(
                    ModelResponse(
                        parts=[part],
                        timestamp=line.timestamp,
                        provider_name=CODEX_PROVIDER_NAME,
                        provider_response_id=response_id
                        if isinstance(response_id, str)
                        else None,
                        metadata={
                            **codex_metadata(),
                            "native_item_ids": [context_item_id(payload)]
                            if context_item_id(payload)
                            else [],
                        },
                    )
                )
                yield PartStartEvent(index=turn.part_index, part=part)
                yield PartEndEvent(index=turn.part_index, part=part)
                turn.part_index += 1
                if (
                    payload.get("phase") == "final_answer"
                    or payload.get("phase") is None
                ):
                    turn.answer = part.content
            return
        if kind == "reasoning":
            parts: list[ThinkingPart] = []
            for field in ("content", "summary"):
                blocks = payload.get(field)
                if not isinstance(blocks, list):
                    continue
                texts = [
                    fragment
                    for block in blocks
                    if isinstance(block, str | dict)
                    if isinstance(
                        fragment := block
                        if isinstance(block, str)
                        else block.get("text"),
                        str,
                    )
                ]
                content = "\n\n".join(texts)
                if not content:
                    continue
                parts.append(
                    ThinkingPart(
                        content=content,
                        provider_name=CODEX_PROVIDER_NAME,
                        provider_details={
                            "reasoning_format": "summary"
                            if field == "summary"
                            else "reasoning"
                        },
                    )
                )
            encrypted = payload.get("encrypted_content")
            if not parts and isinstance(encrypted, str) and encrypted:
                response_id = payload.get("id")
                parts.append(
                    ThinkingPart(
                        content="",
                        id=response_id if isinstance(response_id, str) else None,
                        provider_name=CODEX_PROVIDER_NAME,
                    )
                )
            for part in parts:
                turn.messages.append(
                    ModelResponse(
                        parts=[part],
                        timestamp=line.timestamp,
                        provider_name=CODEX_PROVIDER_NAME,
                        metadata={
                            **codex_metadata(),
                            "native_item_ids": [context_item_id(payload)]
                            if context_item_id(payload)
                            else [],
                        },
                    )
                )
                yield PartStartEvent(index=turn.part_index, part=part)
                yield PartEndEvent(index=turn.part_index, part=part)
                turn.part_index += 1
            return
        if kind in {"custom_tool_call", "function_call"}:
            call_id = payload.get("call_id")
            name = payload.get("name")
            if isinstance(call_id, str) and isinstance(name, str):
                args = payload.get("input", payload.get("arguments", {}))
                call = NativeToolCallPart(
                    tool_name=name,
                    args=args if isinstance(args, str | dict) else {},
                    tool_call_id=call_id,
                    provider_name=CODEX_PROVIDER_NAME,
                )
                turn.pending_calls[call_id] = call
                yield FunctionToolCallEvent(
                    part=ToolCallPart(
                        tool_name=call.tool_name,
                        args=call.args,
                        tool_call_id=call_id,
                        provider_name=CODEX_PROVIDER_NAME,
                    )
                )
            return
        if kind in {"custom_tool_call_output", "function_call_output"}:
            call_id = payload.get("call_id")
            if not isinstance(call_id, str):
                return
            call = turn.pending_calls.pop(call_id, None)
            if call is None:
                return
            output = payload.get("output", "")
            yield FunctionToolResultEvent(
                part=ToolReturnPart(
                    tool_name=call.tool_name,
                    content=output,
                    tool_call_id=call_id,
                )
            )
            result = NativeToolReturnPart(
                tool_name=call.tool_name,
                content=output,
                tool_call_id=call_id,
                provider_name=CODEX_PROVIDER_NAME,
            )
            turn.messages.append(
                ModelResponse(
                    parts=[call, result],
                    timestamp=line.timestamp,
                    provider_name=CODEX_PROVIDER_NAME,
                    provider_response_id=call_id,
                    metadata={
                        **codex_metadata(),
                        "native_item_ids": ["call:" + call_id, "return:" + call_id],
                    },
                )
            )

agent_tentacle_id instance-attribute

agent_tentacle_id: str = agent_tentacle_id

conversation_manager instance-attribute

conversation_manager = conversations

thread_manager instance-attribute

thread_manager = threads

files instance-attribute

files: FileManager = files

locks instance-attribute

locks = locks if locks is not None else SessionLocks()

sessions instance-attribute

sessions: dict[str, TailState] = {}

stop_turn async

stop_turn(session_id: str, turn_id: str | None) -> None

Request a drain after this turn's terminal line, without holding Stop.

Codex may flush the reply and task_complete only after its hook returns. A timeout must not finalize the stream before those bytes arrive. An open turn stays attached until its matching terminal line commits; a turn already finished can drain immediately. Without a turn id, the idle limit owns exit.

Source code in octomate/tentacles/codex/tailer.py
async def stop_turn(self, session_id: str, turn_id: str | None) -> None:
    """Request a drain after this turn's terminal line, without holding Stop.

    Codex may flush the reply and `task_complete` only after its hook returns.
    A timeout must not finalize the stream before those bytes arrive. An open
    turn stays attached until its matching terminal line commits; a turn already
    finished can drain immediately. Without a turn id, the idle limit owns exit.
    """
    state = self.sessions.get(session_id)
    if state is None or turn_id is None:
        return
    state.drain_turn = turn_id
    if turn_id in state.recorded and (
        state.open_turn is None or state.open_turn.turn_id != turn_id
    ):
        state.stop_event.set()

shutdown async

shutdown() -> None
Source code in octomate/tentacles/codex/tailer.py
async def shutdown(self) -> None:
    self.sessions.clear()

attach_remote async

attach_remote(
    session_id: str,
    transcript_path: Path,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]

Register a streamed session — its rollout lives on the client machine that streams it (octomate codex tail) — and answer where its files resume.

The answer is always byte 0: a rollout's head is load-bearing (session_meta carries the thread id every child classification checks against, and the parent's sub_agent_activity lines are what link child runs to their spawning calls), so a reconnect re-streams whole files and the committed-turn guard skips what is already durable. Child files are not named here either: the client registers each file by its opening session_meta and receives its conversation UUID.

A lingering registration (its client died without a close) is replaced; the dead route feeds the state object it attached, and its commits are idempotent.

Source code in octomate/tentacles/codex/tailer.py
async def attach_remote(
    self,
    session_id: str,
    transcript_path: Path,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]:
    """Register a streamed session — its rollout lives on the client machine
    that streams it (`octomate codex tail`) — and answer where its files resume.

    The answer is always byte 0: a rollout's head is load-bearing (`session_meta`
    carries the thread id every child classification checks against, and the
    parent's `sub_agent_activity` lines are what link child runs to their spawning
    calls), so a reconnect re-streams whole files and the committed-turn guard
    skips what is already durable. Child files are not named here either: the
    client registers each file by its opening `session_meta` and receives
    its conversation UUID.

    A lingering registration (its client died without a close) is replaced; the
    dead route feeds the state object it attached, and its commits are
    idempotent.
    """
    state = TailState(
        session_id, transcript_path, asyncio.Event(), sender, address, impulses
    )
    state.conversation = await self.ensure_session(session_id)
    state.recorded = state.conversation.native_run_ids
    self.sessions[session_id] = state
    logger.info("session %s: remote tail attached", session_id)
    return state, {state.conversation.id: 0}

feed_remote async

feed_remote(
    state: TailState,
    key: str | None,
    raw: str,
    start: int,
    end: int,
    *,
    visualizations: list[HtmlSnapshot] | None = None,
) -> None

Advance a remote session by one framed line — the pumps' per-line body, against offsets the client measured in its own file. Takes the state rather than a session id so a superseded connection keeps feeding the state it attached, never whoever registered after it. key is None for the session's own rollout, else the client's label for a sibling file.

Source code in octomate/tentacles/codex/tailer.py
async def feed_remote(
    self,
    state: TailState,
    key: str | None,
    raw: str,
    start: int,
    end: int,
    *,
    visualizations: list[HtmlSnapshot] | None = None,
) -> None:
    """Advance a remote session by one framed line — the pumps' per-line body,
    against offsets the client measured in its own file. Takes the state rather
    than a session id so a superseded connection keeps feeding the state it
    attached, never whoever registered after it. `key` is None for the session's
    own rollout, else the client's label for a sibling file."""
    if key is None:
        state.offset = end
        try:
            line = rollout_line_adapter.validate_json(raw)
        except ValidationError:
            logger.debug("skipping unmodeled Codex rollout line")
            line = None
        if state.open_turn is not None and state.open_turn.native is not None:
            state.open_turn.native.replay = end <= state.catchup_end
        if line is not None:
            await self.process_line(
                state, line, start, end, visualizations=visualizations
            )
        if state.catchup_end and end >= state.catchup_end:
            state.catchup_end = 0
            if state.open_turn is not None and state.open_turn.native is not None:
                await state.open_turn.native.caught_up()
            else:
                await state.impulses.send(Impulse(RunEndedEvent(), state.address))
        return
    tail = await self.remote_subagent(state, key, raw)
    if tail is None:
        return
    tail.offset = end
    try:
        line = rollout_line_adapter.validate_json(raw)
    except ValidationError:
        logger.debug(
            "skipping unmodeled Codex subagent line in session %s/%s",
            state.session_id,
            tail.thread_id,
        )
        return
    await self.process_subagent_line(state, tail, line, start, end)

remote_subagent async

remote_subagent(
    state: TailState, key: str, raw: str
) -> SubagentTail | None

The child tail a client label maps to, classified on first sight from the line in hand — discover_subagent's test without the disk read it cannot do here. The first line is the file's session_meta, because every remote file streams from byte 0; a label that names no child of this session is remembered and its lines dropped.

Source code in octomate/tentacles/codex/tailer.py
async def remote_subagent(
    self, state: TailState, key: str, raw: str
) -> SubagentTail | None:
    """The child tail a client label maps to, classified on first sight from the
    line in hand — `discover_subagent`'s test without the disk read it cannot do
    here. The first line is the file's `session_meta`, because every remote file
    streams from byte 0; a label that names no child of this session is
    remembered and its lines dropped."""
    path = Path(key)
    for tail in state.subagents.values():
        if tail.path == path:
            return tail
    if path in state.classified_rollouts:
        return None
    if state.thread_id is None:
        return None
    try:
        line = rollout_line_adapter.validate_json(raw)
        if line.type != "session_meta":
            return None
        metadata = session_metadata_adapter.validate_python(line.payload)
    except ValidationError:
        logger.debug("skipping remote rollout with malformed metadata: %s", key)
        return None
    state.classified_rollouts.add(path)
    tail = self.subagent_from_metadata(state, metadata, path)
    if tail is None:
        return None
    await self.prepare_subagent(state, tail)
    return tail

detach_remote

detach_remote(state: TailState) -> None

Drop a remote session's registration. Nothing commits on the way out, eof or not — a Codex turn closes on its own task_complete/turn_aborted line, so a turn still open here is mid-flight, and committing it would plant its id in the committed-turn guard where the completed version could never replace it. The next connect re-streams from byte 0 and the closed turn lands whole.

Source code in octomate/tentacles/codex/tailer.py
def detach_remote(self, state: TailState) -> None:
    """Drop a remote session's registration. Nothing commits on the way out, eof
    or not — a Codex turn closes on its own `task_complete`/`turn_aborted` line,
    so a turn still open here is mid-flight, and committing it would plant its id
    in the committed-turn guard where the completed version could never replace
    it. The next connect re-streams from byte 0 and the closed turn lands whole."""
    if self.sessions.get(state.session_id) is state:
        del self.sessions[state.session_id]

ensure_session async

ensure_session(session_id: str) -> Conversation
Source code in octomate/tentacles/codex/tailer.py
async def ensure_session(self, session_id: str) -> Conversation:
    thread = await self.thread_manager.ensure(
        ThreadKey(
            channel_tentacle_id=self.agent_tentacle_id,
            chat_type="thread",
            chat_id=session_id,
        ),
        native=True,
    )
    return await self.conversation_manager.ensure(
        thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
    )

process_line async

process_line(
    state: TailState,
    line: RolloutLine,
    start: int,
    end: int,
    *,
    visualizations: list[HtmlSnapshot] | None = None,
) -> None
Source code in octomate/tentacles/codex/tailer.py
async def process_line(
    self,
    state: TailState,
    line: RolloutLine,
    start: int,
    end: int,
    *,
    visualizations: list[HtmlSnapshot] | None = None,
) -> None:
    state.message_identities.consume(line, state.session_id)
    if line.type == "response_item" and not is_injected_message(line.payload):
        state.last_item_id = context_item_id(line.payload)
    if line.type == "compacted":
        await self.record_compaction(state, line, start, end)
        return
    kind = payload_type(line)
    if line.type == "session_meta":
        try:
            metadata = session_metadata_adapter.validate_python(line.payload)
        except ValidationError:
            logger.debug("skipping malformed Codex session metadata")
            return
        state.thread_id = metadata.id or state.thread_id or state.session_id
        state.cwd = metadata.cwd
        state.source = metadata.originator or (
            metadata.source if isinstance(metadata.source, str) else None
        )
        return
    if line.type == "event_msg" and kind == "task_started":
        turn_id = line.payload.get("turn_id")
        if not isinstance(turn_id, str) or not turn_id:
            return
        if state.open_turn is not None:
            await self.close_turn(state)
        state.open_turn = OpenTurn(
            turn_id=turn_id,
            start_offset=start,
            end_offset=end,
            timestamp=line.timestamp,
            source=state.source,
        )
        state.open_turn.native = await NativeTurn.open(
            run_id=turn_id,
            recorded=state.recorded,
            conversations=self.conversation_manager,
            threads=self.thread_manager,
            locks=self.locks,
            address=state.address,
            sender=state.sender,
            impulses=state.impulses,
            messages=state.open_turn.messages,
            replay=end <= state.catchup_end,
        )
        return
    turn = state.open_turn
    if turn is None:
        return
    turn.end_offset = end
    if line.type == "event_msg" and kind == "item_completed":
        await self.identify_compaction(state, turn, line)
    if line.type == "turn_context":
        self.consume_turn_context(turn, line)
        return
    if (
        turn.native is not None
        and (prompt := turn.consume_prompt(line)) is not None
    ):
        await turn.native.prompt(
            message_id=turn.turn_id
            if not turn.native.prompts
            else f"{turn.turn_id}:{start}",
            text=prompt,
            timestamp=line.timestamp,
            metadata={
                **codex_metadata(),
                "native_item_ids": [context_item_id(line.payload)]
                if context_item_id(line.payload)
                else [],
            },
        )
        return
    if line.type == "response_item" and turn.native is not None:
        turn.has_response_items = True
        if visualizations:
            if state.sender.user_id is None:
                raise ValueError(
                    "HTML capture requires a registered artifact owner"
                )
            turn.visualizations[len(turn.messages)] = visualizations
        await turn.native.fold(
            self.consume_response_item(turn, line, captured=bool(visualizations))
        )
        return
    if line.type != "event_msg":
        return
    if kind == "item_completed" and turn.native is not None:
        await turn.native.fold(self.consume_completed_command(turn, line))
    elif kind == "token_count":
        turn.usage = self.parse_usage(line.payload)
    elif kind == "sub_agent_activity":
        child_thread_id = line.payload.get("agent_thread_id")
        tool_call_id = line.payload.get("event_id")
        occurred_at_ms = line.payload.get("occurred_at_ms")
        activity_kind = line.payload.get("kind")
        if (
            isinstance(child_thread_id, str)
            and isinstance(tool_call_id, str)
            and isinstance(occurred_at_ms, int)
            and activity_kind in {"started", "interacted"}
        ):
            state.subagent_calls.setdefault(child_thread_id, []).append(
                SubagentCall(turn.turn_id, tool_call_id, occurred_at_ms)
            )
    elif kind in {"task_complete", "turn_aborted"}:
        ended_id = line.payload.get("turn_id")
        if ended_id == turn.turn_id:
            # An aborted turn is still real work in the file — commit what it
            # reached, as an interrupted Claude turn commits at the next
            # prompt. (`turn_aborted` carries no last message; the fallback
            # read is a no-op there.)
            fallback = line.payload.get("last_agent_message")
            if not turn.answer and isinstance(fallback, str):
                turn.answer = answer_part(
                    visualization_text(fallback, final=True)[0]
                    if turn.visualizations
                    else fallback
                ).content
            await self.close_turn(state)
            if ended_id == state.drain_turn:
                state.stop_event.set()

subagent_from_metadata

subagent_from_metadata(
    state: TailState, metadata: SessionMetadata, path: Path
) -> SubagentTail | None

A new child tail when the metadata names a thread-spawned child of this session — the test remote_subagent runs against a file's streamed opening line.

Source code in octomate/tentacles/codex/tailer.py
def subagent_from_metadata(
    self, state: TailState, metadata: SessionMetadata, path: Path
) -> SubagentTail | None:
    """A new child tail when the metadata names a thread-spawned child of this
    session — the test `remote_subagent` runs against a file's streamed opening
    line."""
    source = metadata.source
    spawn = (
        source.subagent.thread_spawn
        if source is not None
        and not isinstance(source, str)
        and source.subagent is not None
        else None
    )
    if (
        spawn is None
        or metadata.session_id != state.session_id
        or spawn.parent_thread_id != state.thread_id
        or not metadata.id
        or self.uuid7_timestamp(metadata.id) is None
    ):
        return None
    tail = SubagentTail(
        thread_id=metadata.id,
        path=path,
        cwd=metadata.cwd,
        name=spawn.agent_path.rsplit("/", 1)[-1],
    )
    state.subagents[tail.thread_id] = tail
    return tail

prepare_subagent async

prepare_subagent(
    state: TailState, tail: SubagentTail
) -> None

The child's durable state: its conversation under the parent's, and the committed-turn guard seeded from what is already assembled.

Source code in octomate/tentacles/codex/tailer.py
async def prepare_subagent(self, state: TailState, tail: SubagentTail) -> None:
    """The child's durable state: its conversation under the parent's, and the
    committed-turn guard seeded from what is already assembled."""
    parent = state.conversation
    assert parent is not None
    tail.conversation = await self.conversation_manager.ensure(
        parent.thread_id,
        agent_tentacle_id=self.agent_tentacle_id,
        native=True,
        subagent_id=tail.thread_id,
        name=tail.name,
        parent_conversation_id=parent.id,
    )
    tail.recorded = tail.conversation.native_run_ids
    tail.linked_call_ids = {
        run.parent_tool_call_id
        for run in tail.conversation.runs
        if run.parent_tool_call_id is not None
    }

process_subagent_line async

process_subagent_line(
    state: TailState,
    tail: SubagentTail,
    line: RolloutLine,
    start: int,
    end: int,
) -> None
Source code in octomate/tentacles/codex/tailer.py
async def process_subagent_line(
    self,
    state: TailState,
    tail: SubagentTail,
    line: RolloutLine,
    start: int,
    end: int,
) -> None:
    tail.message_identities.consume(line, tail.thread_id)
    if line.type == "response_item" and not is_injected_message(line.payload):
        tail.last_item_id = context_item_id(line.payload)
    if line.type == "compacted":
        if tail.own_turns_started:
            await self.record_compaction(state, line, start, end, tail=tail)
        return
    kind = payload_type(line)
    if line.type == "event_msg" and kind == "task_started":
        turn_id = line.payload.get("turn_id")
        if not isinstance(turn_id, str) or not turn_id:
            return
        if not tail.own_turns_started:
            if not self.turn_belongs_to_subagent(tail.thread_id, turn_id):
                return
            tail.own_turns_started = True
        await self.close_subagent_turn(state, tail)
        tail.open_turn = OpenTurn(
            turn_id=turn_id,
            start_offset=start,
            end_offset=end,
            timestamp=line.timestamp,
            source="subagent",
        )
        return
    turn = tail.open_turn
    if turn is not None and line.type == "event_msg" and kind == "item_completed":
        await self.identify_compaction(state, turn, line, tail=tail)
    if turn is None or turn.turn_id in tail.recorded:
        return
    turn.end_offset = end
    if line.type == "turn_context":
        self.consume_turn_context(turn, line)
        return
    if (prompt := turn.consume_prompt(line)) is not None:
        content = prompt
        turn.messages.append(
            ModelRequest(
                parts=[
                    UserPromptPart(
                        content=[content]
                        if isinstance(content, TextContent)
                        else content,
                        timestamp=line.timestamp,
                    )
                ],
                timestamp=line.timestamp,
                metadata={
                    **codex_metadata(),
                    "native_item_ids": [context_item_id(line.payload)]
                    if context_item_id(line.payload)
                    else [],
                },
            )
        )
        return
    if line.type == "response_item":
        turn.has_response_items = True
        for _ in self.consume_response_item(turn, line):
            pass
        return
    if line.type != "event_msg":
        return
    if kind == "item_completed":
        for _ in self.consume_completed_command(turn, line):
            pass
    elif kind == "token_count":
        turn.usage = self.parse_usage(line.payload)
    elif kind in {"task_complete", "turn_aborted"}:
        ended_id = line.payload.get("turn_id")
        if ended_id == turn.turn_id:
            fallback = line.payload.get("last_agent_message")
            if not turn.answer and isinstance(fallback, str):
                turn.answer = answer_part(fallback).content
            await self.close_subagent_turn(state, tail)

record_compaction async

record_compaction(
    state: TailState,
    line: RolloutLine,
    start: int,
    end: int,
    *,
    tail: SubagentTail | None = None,
    native_compaction_id: str | None = None,
    last_item_id: str | None = None,
) -> None

Capture summary/checkpoint content without changing the archived turn.

Source code in octomate/tentacles/codex/tailer.py
async def record_compaction(
    self,
    state: TailState,
    line: RolloutLine,
    start: int,
    end: int,
    *,
    tail: SubagentTail | None = None,
    native_compaction_id: str | None = None,
    last_item_id: str | None = None,
) -> None:
    """Capture summary/checkpoint content without changing the archived turn."""
    try:
        item = CompactedItem.model_validate(line.payload)
        before = (
            last_item_id
            if native_compaction_id is not None
            else (tail or state).last_item_id
        )
        messages = item.to_messages(
            line.timestamp,
            last_item_id=before,
            item_aliases=(tail or state).message_identities.aliases,
        )
    except ValidationError:
        logger.debug("skipping malformed Codex compaction")
        return
    conversation = tail.conversation if tail is not None else state.conversation
    assert conversation is not None
    # TODO: Preserve the native compaction trigger when Codex exposes a reliable manual/auto signal.
    await self.conversation_manager.record_external_compaction(
        conversation,
        native_session_id=tail.thread_id if tail is not None else state.session_id,
        native_compaction_id=native_compaction_id,
        source=str(tail.path if tail is not None else state.transcript_path),
        start_offset=start,
        end_offset=end,
        happened_at=line.timestamp,
        messages=messages,
    )
    (tail or state).compactions_pending = True
    if native_compaction_id is None and messages:
        context = NativeMessage.model_validate(
            messages[0].metadata or {}
        ).compaction_context
        (tail or state).last_item_id = (
            context.replacement_ids[-1]
            if context is not None and context.replacement_ids
            else None
        )
    turn = tail.open_turn if tail is not None else state.open_turn
    if turn is None:
        await self.conversation_manager.record_native_memberships(
            conversation,
            tail.thread_id if tail else state.session_id,
        )
        (tail or state).compactions_pending = False
    if turn is not None:
        turn.compacted = True
        if native_compaction_id is None:
            turn.compaction = PendingCompaction(line, start, end, before)

identify_compaction async

identify_compaction(
    state: TailState,
    turn: OpenTurn,
    line: RolloutLine,
    *,
    tail: SubagentTail | None = None,
) -> None

Bind the following completion ID to the already durable replacement.

Source code in octomate/tentacles/codex/tailer.py
async def identify_compaction(
    self,
    state: TailState,
    turn: OpenTurn,
    line: RolloutLine,
    *,
    tail: SubagentTail | None = None,
) -> None:
    """Bind the following completion ID to the already durable replacement."""
    pending = turn.compaction
    if pending is None:
        return
    try:
        event = CompactionCompletedEvent.model_validate(line.payload)
    except ValidationError:
        return
    session_id = tail.thread_id if tail is not None else state.session_id
    if event.thread_id != session_id or event.turn_id != turn.turn_id:
        return
    await self.record_compaction(
        state,
        pending.line,
        pending.start,
        pending.end,
        tail=tail,
        native_compaction_id=event.item.id,
        last_item_id=pending.last_item_id,
    )
    turn.compaction = None

close_subagent_turn async

close_subagent_turn(
    state: TailState, tail: SubagentTail
) -> None
Source code in octomate/tentacles/codex/tailer.py
async def close_subagent_turn(self, state: TailState, tail: SubagentTail) -> None:
    turn = tail.open_turn
    tail.open_turn = None
    if turn is None or turn.turn_id in tail.recorded or not turn.messages:
        return
    for message in reversed(turn.messages):
        if isinstance(message, ModelResponse):
            if turn.usage is not None:
                message.usage = turn.usage
            break
    conversation = tail.conversation
    assert conversation is not None
    with codex_logfire.span(
        "codex.tailer.commit_subagent_turn {turn_id} [{session_id}]",
        turn_id=turn.turn_id,
        session_id=state.session_id,
        child_thread_id=tail.thread_id,
        start_offset=turn.start_offset,
        end_offset=turn.end_offset,
        messages=len(turn.messages),
    ) as span:
        async with self.locks.hold(
            state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
        ):
            call = next(
                (
                    candidate
                    for candidate in reversed(
                        state.subagent_calls.get(tail.thread_id, [])
                    )
                    if candidate.occurred_at_ms
                    <= int(turn.timestamp.timestamp() * 1000)
                    and candidate.parent_tool_call_id not in tail.linked_call_ids
                ),
                None,
            )
            run = await self.conversation_manager.record_external_run(
                conversation,
                run_id=turn.turn_id,
                messages=turn.messages,
                name=self.agent_tentacle_id,
                model_name=turn.model_name,
                context_used=turn.usage.input_tokens
                if turn.usage is not None
                else None,
                context_window=turn.usage.details.get("model_context_window")
                if turn.usage is not None
                else None,
                permission_mode=turn.permission_mode,
                cwd=Path(tail.cwd) if tail.cwd else None,
                native_session_id=tail.thread_id,
                source=turn.source,
                start_offset=turn.start_offset,
                end_offset=turn.end_offset,
                parent_run_id=call.parent_run_id if call is not None else None,
                parent_tool_call_id=call.parent_tool_call_id
                if call is not None
                else None,
            )
            span.set_attribute("committed", run is not None)
            if run is None:
                return
            tail.recorded.add(turn.turn_id)
            if tail.compactions_pending:
                await self.conversation_manager.record_native_memberships(
                    conversation, tail.thread_id
                )
                tail.compactions_pending = False
            if call is not None:
                tail.linked_call_ids.add(call.parent_tool_call_id)
            logger.info(
                "session %s: subagent %s turn %s synced — %d messages, bytes %d-%d",
                state.session_id,
                tail.thread_id,
                turn.turn_id,
                len(turn.messages),
                turn.start_offset,
                turn.end_offset,
            )

close_turn async

close_turn(state: TailState) -> None
Source code in octomate/tentacles/codex/tailer.py
async def close_turn(self, state: TailState) -> None:
    turn = state.open_turn
    state.open_turn = None
    if turn is None or turn.native is None:
        if state.compactions_pending and state.conversation is not None:
            await self.conversation_manager.record_native_memberships(
                state.conversation, state.session_id
            )
            state.compactions_pending = False
        return
    for message in reversed(turn.messages):
        if isinstance(message, ModelResponse):
            if turn.usage is not None:
                message.usage = turn.usage
            break
    conversation = state.conversation
    assert conversation is not None
    if (
        turn.compacted
        and not turn.messages
        and not turn.answer
        and not turn.has_response_items
    ):
        await turn.native.settle(turn.turn_id)
        if state.compactions_pending:
            await self.conversation_manager.record_native_memberships(
                conversation, state.session_id
            )
            state.compactions_pending = False
        return
    with codex_logfire.span(
        "codex.tailer.commit_turn {turn_id} [{session_id}]",
        turn_id=turn.turn_id,
        session_id=state.session_id,
        start_offset=turn.start_offset,
        end_offset=turn.end_offset,
        messages=len(turn.messages),
    ) as span:
        async with self.locks.hold(
            state.session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT
        ):
            run = await self.conversation_manager.record_external_run(
                conversation,
                run_id=turn.turn_id,
                messages=turn.messages,
                name=self.agent_tentacle_id,
                model_name=turn.model_name,
                context_used=turn.usage.input_tokens
                if turn.usage is not None
                else None,
                context_window=turn.usage.details.get("model_context_window")
                if turn.usage is not None
                else None,
                permission_mode=turn.permission_mode,
                cwd=Path(state.cwd) if state.cwd else None,
                native_session_id=state.session_id,
                source=turn.source,
                start_offset=turn.start_offset,
                end_offset=turn.end_offset,
            )
            span.set_attribute("committed", run is not None)
            if run is not None:
                await self.capture_html(state, turn, run)
            if state.compactions_pending:
                await self.conversation_manager.record_native_memberships(
                    conversation, state.session_id
                )
                state.compactions_pending = False
            await turn.native.close(run, run_id=turn.turn_id, answer=turn.answer)
            logger.info(
                "session %s: turn %s synced — %d messages, bytes %d-%d",
                state.session_id,
                turn.turn_id,
                len(turn.messages),
                turn.start_offset,
                turn.end_offset,
            )

capture_html async

capture_html(
    state: TailState, turn: OpenTurn, run: ExternalAgentRun
) -> None

Persist client snapshots and bind them to the completed native response.

The bearer supplies ownership; client paths are labels only. Artifacts use the existing file storage, ledger and event stream before the run closes.

Source code in octomate/tentacles/codex/tailer.py
async def capture_html(
    self, state: TailState, turn: OpenTurn, run: ExternalAgentRun
) -> None:
    """Persist client snapshots and bind them to the completed native response.

    The bearer supplies ownership; client paths are labels only. Artifacts use
    the existing file storage, ledger and event stream before the run closes.
    """
    if not turn.visualizations:
        return
    owner_id = state.sender.user_id
    conversation = state.conversation
    assert owner_id is not None
    assert turn.native is not None
    assert conversation is not None
    for position, snapshots in turn.visualizations.items():
        for snapshot in snapshots:
            reference = snapshot.reference
            with BytesIO(snapshot.html.encode("utf-8")) as source:
                stored = await self.files.write(
                    UploadFile(
                        source,
                        filename=reference.path.name,
                        headers=Headers(
                            {"content-type": "text/html; charset=utf-8"}
                        ),
                    ),
                    owner_id=owner_id,
                )
            message = await self.thread_manager.record_artifact(
                conversation.thread_id,
                HtmlArtifact(
                    owner_id=owner_id,
                    title=reference.title or reference.path.stem,
                    mode=reference.mode,
                    file_id=stored.id,
                ),
                sender=state.sender,
                agent_tentacle_id=self.agent_tentacle_id,
            )
            await self.thread_manager.bind_messages(
                [message.id],
                run.messages[position].id,
                kind="assistant_reply",
                run_id=run.id,
            )
            await turn.native.fold(
                [
                    ArtifactAvailableEvent(
                        message_id=message.id, artifact_id=message.artifact_id
                    )
                ]
            )

turn_belongs_to_subagent staticmethod

turn_belongs_to_subagent(
    thread_id: str, turn_id: str
) -> bool
Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def turn_belongs_to_subagent(thread_id: str, turn_id: str) -> bool:
    thread_time = CodexTranscriptTailer.uuid7_timestamp(thread_id)
    turn_time = CodexTranscriptTailer.uuid7_timestamp(turn_id)
    return (
        thread_time is not None
        and turn_time is not None
        and turn_time >= thread_time
    )

uuid7_timestamp staticmethod

uuid7_timestamp(value: str) -> int | None
Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def uuid7_timestamp(value: str) -> int | None:
    try:
        parsed = UUID(value)
    except ValueError:
        return None
    if parsed.version != 7:
        return None
    return parsed.timestamp

parse_usage staticmethod

parse_usage(payload: JsonObject) -> RequestUsage | None
Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def parse_usage(payload: JsonObject) -> RequestUsage | None:
    info = payload.get("info")
    if not isinstance(info, dict):
        return None
    usage = info.get("last_token_usage")
    if not isinstance(usage, dict):
        return None
    values = {key: value for key, value in usage.items() if isinstance(value, int)}
    details = {"reasoning_output_tokens": values.get("reasoning_output_tokens", 0)}
    window = info.get("model_context_window")
    if isinstance(window, int) and not isinstance(window, bool) and window > 0:
        details["model_context_window"] = window
    return RequestUsage(
        input_tokens=values.get("input_tokens", 0),
        output_tokens=values.get("output_tokens", 0),
        cache_read_tokens=values.get("cached_input_tokens", 0),
        details=details,
    )

consume_turn_context staticmethod

consume_turn_context(
    turn: OpenTurn, line: RolloutLine
) -> None
Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def consume_turn_context(turn: OpenTurn, line: RolloutLine) -> None:
    model = line.payload.get("model")
    turn.model_name = model if isinstance(model, str) else None
    try:
        turn.permission_mode = TurnPermissions.model_validate(
            line.payload
        ).permission_mode
    except ValueError as error:
        # Custom native permissions are valid history, but not a forkable preset.
        turn.permission_mode = None
        reason = str(error)
        if isinstance(error, ValidationError):
            reason = "; ".join(
                f"{'.'.join(map(str, detail['loc']))}: {detail['msg']}"
                for detail in error.errors(
                    include_input=False, include_context=False, include_url=False
                )
            )
        logger.debug(
            "Codex turn %s has no matching permission preset; "
            "history sync continues, but forking is unavailable: %s",
            turn.turn_id,
            reason,
        )

consume_completed_command staticmethod

consume_completed_command(
    turn: OpenTurn, line: RolloutLine
) -> Iterator[AgentStreamEvent]
Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def consume_completed_command(
    turn: OpenTurn, line: RolloutLine
) -> Iterator[AgentStreamEvent]:
    payload = line.payload.get("item")
    if not isinstance(payload, dict) or payload.get("type") != "CommandExecution":
        return
    item = CompletedCommandItem.model_validate(payload)
    if item.id in turn.pending_calls or any(
        isinstance(part, NativeToolCallPart) and part.tool_call_id == item.id
        for message in turn.messages
        for part in message.parts
    ):
        return
    call = NativeToolCallPart(
        tool_name="codex_command_execution",
        tool_call_id=item.id,
        args={
            "command": shlex.join(item.command),
            "cwd": item.cwd,
            "status": item.status,
            "commandActions": [model_json(action) for action in item.parsed_cmd],
        },
        provider_name=CODEX_PROVIDER_NAME,
    )
    outcome = (
        "success"
        if item.status == "completed"
        else "denied"
        if item.status == "declined"
        else "failed"
    )
    result = NativeToolReturnPart(
        tool_name=call.tool_name,
        tool_call_id=item.id,
        content=item.aggregated_output,
        outcome=outcome,
        provider_name=CODEX_PROVIDER_NAME,
    )
    turn.messages.append(
        ModelResponse(
            parts=[call, result],
            timestamp=line.timestamp,
            provider_name=CODEX_PROVIDER_NAME,
            provider_response_id=item.id,
            metadata=codex_metadata(),
        )
    )
    yield FunctionToolCallEvent(
        part=ToolCallPart(
            tool_name=call.tool_name,
            tool_call_id=item.id,
            args=call.args,
            provider_name=CODEX_PROVIDER_NAME,
        )
    )
    yield FunctionToolResultEvent(
        part=ToolReturnPart(
            tool_name=call.tool_name,
            tool_call_id=item.id,
            content=result.content,
            outcome=outcome,
        )
    )

consume_response_item staticmethod

consume_response_item(
    turn: OpenTurn,
    line: RolloutLine,
    *,
    captured: bool = False,
) -> Iterator[AgentStreamEvent]

Yield whole items, hiding captured references without editing the rollout.

Source code in octomate/tentacles/codex/tailer.py
@staticmethod
def consume_response_item(
    turn: OpenTurn, line: RolloutLine, *, captured: bool = False
) -> Iterator[AgentStreamEvent]:
    """Yield whole items, hiding captured references without editing the rollout."""
    payload = line.payload
    kind = payload_type(line)
    if kind == "message" and payload.get("role") == "assistant":
        texts: list[str] = []
        content = payload.get("content")
        if not isinstance(content, list):
            return
        for part in content:
            if isinstance(part, dict) and isinstance(
                part_text := part.get("text"), str
            ):
                texts.append(part_text)
        text = "\n".join(texts)
        if text:
            text = visualization_text(text, final=True)[0] if captured else text
            response_id = payload.get("id")
            part = answer_part(text)
            turn.messages.append(
                ModelResponse(
                    parts=[part],
                    timestamp=line.timestamp,
                    provider_name=CODEX_PROVIDER_NAME,
                    provider_response_id=response_id
                    if isinstance(response_id, str)
                    else None,
                    metadata={
                        **codex_metadata(),
                        "native_item_ids": [context_item_id(payload)]
                        if context_item_id(payload)
                        else [],
                    },
                )
            )
            yield PartStartEvent(index=turn.part_index, part=part)
            yield PartEndEvent(index=turn.part_index, part=part)
            turn.part_index += 1
            if (
                payload.get("phase") == "final_answer"
                or payload.get("phase") is None
            ):
                turn.answer = part.content
        return
    if kind == "reasoning":
        parts: list[ThinkingPart] = []
        for field in ("content", "summary"):
            blocks = payload.get(field)
            if not isinstance(blocks, list):
                continue
            texts = [
                fragment
                for block in blocks
                if isinstance(block, str | dict)
                if isinstance(
                    fragment := block
                    if isinstance(block, str)
                    else block.get("text"),
                    str,
                )
            ]
            content = "\n\n".join(texts)
            if not content:
                continue
            parts.append(
                ThinkingPart(
                    content=content,
                    provider_name=CODEX_PROVIDER_NAME,
                    provider_details={
                        "reasoning_format": "summary"
                        if field == "summary"
                        else "reasoning"
                    },
                )
            )
        encrypted = payload.get("encrypted_content")
        if not parts and isinstance(encrypted, str) and encrypted:
            response_id = payload.get("id")
            parts.append(
                ThinkingPart(
                    content="",
                    id=response_id if isinstance(response_id, str) else None,
                    provider_name=CODEX_PROVIDER_NAME,
                )
            )
        for part in parts:
            turn.messages.append(
                ModelResponse(
                    parts=[part],
                    timestamp=line.timestamp,
                    provider_name=CODEX_PROVIDER_NAME,
                    metadata={
                        **codex_metadata(),
                        "native_item_ids": [context_item_id(payload)]
                        if context_item_id(payload)
                        else [],
                    },
                )
            )
            yield PartStartEvent(index=turn.part_index, part=part)
            yield PartEndEvent(index=turn.part_index, part=part)
            turn.part_index += 1
        return
    if kind in {"custom_tool_call", "function_call"}:
        call_id = payload.get("call_id")
        name = payload.get("name")
        if isinstance(call_id, str) and isinstance(name, str):
            args = payload.get("input", payload.get("arguments", {}))
            call = NativeToolCallPart(
                tool_name=name,
                args=args if isinstance(args, str | dict) else {},
                tool_call_id=call_id,
                provider_name=CODEX_PROVIDER_NAME,
            )
            turn.pending_calls[call_id] = call
            yield FunctionToolCallEvent(
                part=ToolCallPart(
                    tool_name=call.tool_name,
                    args=call.args,
                    tool_call_id=call_id,
                    provider_name=CODEX_PROVIDER_NAME,
                )
            )
        return
    if kind in {"custom_tool_call_output", "function_call_output"}:
        call_id = payload.get("call_id")
        if not isinstance(call_id, str):
            return
        call = turn.pending_calls.pop(call_id, None)
        if call is None:
            return
        output = payload.get("output", "")
        yield FunctionToolResultEvent(
            part=ToolReturnPart(
                tool_name=call.tool_name,
                content=output,
                tool_call_id=call_id,
            )
        )
        result = NativeToolReturnPart(
            tool_name=call.tool_name,
            content=output,
            tool_call_id=call_id,
            provider_name=CODEX_PROVIDER_NAME,
        )
        turn.messages.append(
            ModelResponse(
                parts=[call, result],
                timestamp=line.timestamp,
                provider_name=CODEX_PROVIDER_NAME,
                provider_response_id=call_id,
                metadata={
                    **codex_metadata(),
                    "native_item_ids": ["call:" + call_id, "return:" + call_id],
                },
            )
        )

octomate.tentacles.deepseek.tailer

Assembly of native dsh turns from a streamed session log.

History entries streamed in by octomate deepseek tail feed DeepseekEventTailer, which commits each completed turn as an ExternalAgentRun.

logger module-attribute

logger = logging.getLogger(__name__)

COMMIT_LOCK_TIMEOUT module-attribute

COMMIT_LOCK_TIMEOUT = 30.0

STOP_SETTLE_TIMEOUT module-attribute

STOP_SETTLE_TIMEOUT = 5.0

PendingPrompt dataclass

One human user/message — the ledger row's raw material.

Source code in octomate/tentacles/deepseek/tailer.py
@dataclass
class PendingPrompt:
    """One human `user/message` — the ledger row's raw material."""

    text: str
    time: datetime
    seq: int
    via_gateway: bool
    event: SessionEvent

text instance-attribute

text: str

time instance-attribute

time: datetime

seq instance-attribute

seq: int

via_gateway instance-attribute

via_gateway: bool

event instance-attribute

event: SessionEvent

OpenTurn dataclass

The turn currently being assembled off the stream — its accumulator fed entry by entry, its seq range advancing to cover the last one folded in.

Source code in octomate/tentacles/deepseek/tailer.py
@dataclass
class OpenTurn:
    """The turn currently being assembled off the stream — its accumulator fed
    entry by entry, its seq range advancing to cover the last one folded in."""

    turn: int | None
    start_seq: int
    end_seq: int
    # The prompt arrived through the /api gateway (it carries the gateway's
    # rpcId) rather than being typed into a local CLI/TUI.
    prompt_via_gateway: bool
    permission_mode: str | None  # Observed permission preset for this turn.
    accumulator: DeepseekRunAccumulator = field(default_factory=DeepseekRunAccumulator)
    native: NativeTurn | None = None

turn instance-attribute

turn: int | None

start_seq instance-attribute

start_seq: int

end_seq instance-attribute

end_seq: int

prompt_via_gateway instance-attribute

prompt_via_gateway: bool

permission_mode instance-attribute

permission_mode: str | None

accumulator class-attribute instance-attribute

accumulator: DeepseekRunAccumulator = field(
    default_factory=DeepseekRunAccumulator
)

native class-attribute instance-attribute

native: NativeTurn | None = None

TailState dataclass

One streamed session. Its log lives on the client machine that streams it (octomate deepseek tail, reading that machine's dsh gateway); the stream route feeds feed_remote, which drives the per-event assembly. transcript_path is the client's claim in the client's own namespace, a label never opened here.

Source code in octomate/tentacles/deepseek/tailer.py
@dataclass
class TailState:
    """One streamed session. Its log lives on the client machine that streams
    it (`octomate deepseek tail`, reading that machine's dsh gateway); the
    stream route feeds `feed_remote`, which drives the per-event assembly.
    `transcript_path` is the client's claim in the client's own namespace, a
    label never opened here."""

    session_id: str
    transcript_path: Path
    cwd: str
    stop_event: asyncio.Event
    # The verified bearer's own profile — who every ledger row this stream
    # writes is attributed to.
    sender: UserProfile
    address: ChannelAddress  # The native surface resolved by the tentacle.
    impulses: ObjectSendStream[Impulse]  # The publisher open for this connection.
    conversation: Conversation | None = None
    compactions: DeepseekCompactions | None = None
    recorded: set[str] = field(default_factory=set)
    floor: int = -1
    prompts: list[PendingPrompt] = field(default_factory=list)
    open_turn: OpenTurn | None = None
    context_window: int | None = None  # Latest request/context capacity across turns.
    # Pulses on every committed turn; a relayed `Stop` clears it and waits so
    # the finalize goes out only once the stopped turn is durable (or the
    # bounded wait ran out).
    commit_pulse: asyncio.Event = field(default_factory=asyncio.Event)

session_id instance-attribute

session_id: str

transcript_path instance-attribute

transcript_path: Path

cwd instance-attribute

cwd: str

stop_event instance-attribute

stop_event: Event

sender instance-attribute

sender: UserProfile

address instance-attribute

address: ChannelAddress

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

conversation class-attribute instance-attribute

conversation: Conversation | None = None

compactions class-attribute instance-attribute

compactions: DeepseekCompactions | None = None

recorded class-attribute instance-attribute

recorded: set[str] = field(default_factory=set)

floor class-attribute instance-attribute

floor: int = -1

prompts class-attribute instance-attribute

prompts: list[PendingPrompt] = field(default_factory=list)

open_turn class-attribute instance-attribute

open_turn: OpenTurn | None = None

context_window class-attribute instance-attribute

context_window: int | None = None

commit_pulse class-attribute instance-attribute

commit_pulse: Event = field(default_factory=asyncio.Event)

DeepseekEventTailer

Assembles native dsh turns from history entries streamed in by octomate deepseek tail — the stream is the only assembler: the server never opens a session log and never speaks to the client machine's dsh.

The client reads its local gateway (session.history, which serves the zstd-framed log decoded and unpacked, cold sessions included) and ships each entry as one framed line, the event's dense seq standing where a file tail's byte offsets stand. Entries fold through the same DeepseekRunAccumulator the driven tentacle uses; a turn commits on its own turn/end line as an ExternalAgentRun keyed <session>:<turn>, carrying the seq range it was assembled from — the committed floor a reconnecting client is told to resume past. An open turn never commits at a connection boundary: the next connect re-streams it whole.

Source code in octomate/tentacles/deepseek/tailer.py
class DeepseekEventTailer:
    """Assembles native dsh turns from history entries streamed in by
    `octomate deepseek tail` — the stream is the only assembler: the server
    never opens a session log and never speaks to the client machine's dsh.

    The client reads its local gateway (`session.history`, which serves the
    zstd-framed log decoded and unpacked, cold sessions included) and ships
    each entry as one framed line, the event's dense `seq` standing where a
    file tail's byte offsets stand. Entries fold through the same
    `DeepseekRunAccumulator` the driven tentacle uses; a turn commits on its
    own `turn/end` line as an `ExternalAgentRun` keyed `<session>:<turn>`,
    carrying the seq range it was assembled from — the committed floor a
    reconnecting client is told to resume past. An open turn never commits at
    a connection boundary: the next connect re-streams it whole.
    """

    agent_tentacle_id: str

    def __init__(
        self,
        conversation_manager: ConversationManager,
        thread_manager: ThreadManager,
        locks: SessionLocks | None = None,
        *,
        agent_tentacle_id: str,
    ) -> None:
        self.agent_tentacle_id = agent_tentacle_id
        self.conversation_manager = conversation_manager
        self.thread_manager = thread_manager
        self.locks = locks if locks is not None else SessionLocks()
        self.sessions: dict[str, TailState] = {}

    async def attach_remote(
        self,
        session_id: str,
        transcript_path: Path,
        cwd: str,
        sender: UserProfile,
        address: ChannelAddress,
        impulses: ObjectSendStream[Impulse],
    ) -> tuple[TailState, dict[UUID7, int]]:
        """Register a streamed session and answer where it resumes: the seq
        after the committed floor, recomputed from the durable runs — the
        client holds no cursor of its own. A lingering registration (its
        client died without a close) is replaced; the dead route keeps feeding
        the state it attached, and its commits are idempotent."""
        state = TailState(
            session_id, transcript_path, cwd, asyncio.Event(), sender, address, impulses
        )
        thread = await self.session_thread(session_id)
        state.conversation = await self.conversation_manager.ensure(
            thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
        )
        state.recorded = state.conversation.native_run_ids
        state.compactions = DeepseekCompactions(
            self.conversation_manager,
            state.conversation,
            session_id,
            source=str(transcript_path),
        )
        state.context_window = await self.conversation_manager.latest_context_window(
            state.conversation.id
        )
        state.floor = committed_floor(state.conversation)
        self.sessions[session_id] = state
        logger.info("session %s: remote tail attached", session_id)
        return state, {state.conversation.id: state.floor + 1}

    async def feed_remote(self, state: TailState, raw: str) -> None:
        """Fold one history entry; the route validates the sequence framing."""
        try:
            entry = history_entry_adapter.validate_json(raw)
        except ValidationError:
            logger.debug("skipping unparseable dsh history entry")
            return
        await self.process_entry(state, entry)

    def detach_remote(self, state: TailState) -> None:
        """Drop a streamed session's registration. Nothing commits on the way
        out — a dsh turn closes on its own `turn/end` line, so a turn still
        open here is mid-flight, and the next connect re-streams it whole from
        the committed floor."""
        if self.sessions.get(state.session_id) is state:
            del self.sessions[state.session_id]

    async def stop_turn(self, session_id: str) -> None:
        """The turn just stopped — its `Stop` hook fired: wait for the stopped
        turn's streamed close to commit, then ask the drain. Runs detached
        from the hook (dsh's stopping seam waits on the hook serially, ahead
        of the very `turn/end` this waits for). A session no stream covers has
        nothing to settle: its turns land at the next connect."""
        state = self.sessions.get(session_id)
        if state is None:
            return
        state.commit_pulse.clear()
        with contextlib.suppress(TimeoutError):
            await asyncio.wait_for(state.commit_pulse.wait(), STOP_SETTLE_TIMEOUT)
        state.stop_event.set()

    async def shutdown(self) -> None:
        self.sessions.clear()

    async def session_thread(self, session_id: str) -> Thread:
        """Reuse the session thread attributed at authenticated entry."""
        return await self.thread_manager.ensure(
            ThreadKey(
                channel_tentacle_id=self.agent_tentacle_id,
                chat_type="thread",
                chat_id=session_id,
            ),
            native=True,
        )

    async def process_entry(self, state: TailState, entry: HistoryEntry) -> None:
        event = entry.event
        assert state.compactions is not None
        await state.compactions.consume(event)
        if event.type == "compaction/end" and state.open_turn is None:
            await state.compactions.record_memberships()
        if event.seq <= state.floor:
            return
        if event.type == "request/context":
            context = request_route_of(event)
            if context is not None:
                state.context_window = context.context_window
        if event.type == "session/title":
            try:
                name = SessionTitle.model_validate(event.data).title
            except ValidationError:
                return
            if not name or not name.strip():
                return
            conversation = state.conversation
            assert conversation is not None
            async with self.locks.hold(state.session_id):
                await self.conversation_manager.set_name(conversation, name)
                thread = await self.session_thread(state.session_id)
                await self.thread_manager.rename(thread, name)
            return
        if event.type == "permission/preset":
            preset = permission_preset_of(event)
            await self.record_permission_mode(state, preset)
            if state.open_turn is not None and preset is not None:
                state.open_turn.permission_mode = preset
            return
        if state.open_turn is None:
            if event.type == "user/message":
                prompt = human_prompt(event)
                if prompt is not None:
                    state.prompts.append(prompt)
            elif event.type == "turn/start":
                prompts = state.prompts
                state.prompts = []
                number = (
                    event.data.get("turn") if isinstance(event.data, dict) else None
                )
                number = number if isinstance(number, int) else None
                run_id = (
                    f"{state.session_id}:{number if number is not None else event.seq}"
                )
                state.open_turn = OpenTurn(
                    turn=number,
                    start_seq=prompts[0].seq if prompts else event.seq,
                    end_seq=event.seq,
                    prompt_via_gateway=any(prompt.via_gateway for prompt in prompts),
                    permission_mode=(
                        state.conversation.permission_mode
                        if state.conversation is not None
                        else None
                    ),
                    accumulator=DeepseekRunAccumulator(
                        context_window=state.context_window
                    ),
                )
                state.open_turn.native = await NativeTurn.open(
                    run_id=run_id,
                    recorded=state.recorded,
                    conversations=self.conversation_manager,
                    threads=self.thread_manager,
                    locks=self.locks,
                    address=state.address,
                    sender=state.sender,
                    impulses=state.impulses,
                    messages=state.open_turn.accumulator.messages,
                )
                if state.open_turn.native is None:
                    return
                for prompt in prompts:
                    await self.record_prompt(state, state.open_turn, prompt)
                await self.fold(state.open_turn, state, entry)
            return
        turn = state.open_turn
        if turn.native is None:
            if event.type == "turn/end":
                state.open_turn = None
                await state.compactions.record_memberships()
            return
        if event.type == "user/message":
            prompt = human_prompt(event)
            if prompt is not None:
                await self.record_prompt(state, turn, prompt)
                turn.prompt_via_gateway = turn.prompt_via_gateway or prompt.via_gateway
        await self.fold(turn, state, entry)
        if turn.accumulator.turn_ended:
            state.open_turn = None
            end = turn_end_of(event)
            if end is not None and end.turn is not None:
                turn.turn = end.turn
            await self.commit_turn(state, turn)

    async def record_prompt(
        self, state: TailState, turn: OpenTurn, prompt: PendingPrompt
    ) -> None:
        """Keep each human input where it occurs, including mid-turn steering.

        The event seq is stable across reconnects, even before dsh reports a turn
        number. Its ledger row grants access while the turn is still streaming.
        """
        assert turn.native is not None
        await turn.native.prompt(
            message_id=f"{state.session_id}:message:{prompt.seq}",
            text=prompt.text,
            timestamp=prompt.time,
            metadata=deepseek_metadata([prompt.event.model_dump(mode="json")]),
        )

    async def fold(self, turn: OpenTurn, state: TailState, entry: HistoryEntry) -> None:
        """Fold and publish one entry, dating messages by the log's clock.

        Committed seqs never reach the fold. The native thread receives only run
        brackets, with the end delivered after its ledger binding commits.
        Re-streaming an open turn starts it again without waking a reflex.
        """
        accumulator = turn.accumulator
        written = len(accumulator.messages)
        frame = SessionEventFrame(
            type="session/event",
            session_id=state.session_id,
            event=entry.event,
            view=entry.view,
        )
        assert turn.native is not None
        await turn.native.fold(accumulator.consume(frame))
        stamp(accumulator.messages[written:], event_time(entry.event))
        turn.end_seq = entry.event.seq

    async def commit_turn(self, state: TailState, turn: OpenTurn) -> None:
        session_id = state.session_id
        run_key = turn.turn if turn.turn is not None else turn.start_seq
        run_id = f"{session_id}:{run_key}"
        if turn.native is None:
            return
        messages = turn.accumulator.messages
        conversation = state.conversation
        assert conversation is not None
        with deepseek_logfire.span(
            "deepseek.tailer.commit_turn {run_id} [{session_id}]",
            run_id=run_id,
            session_id=session_id,
            start_seq=turn.start_seq,
            end_seq=turn.end_seq,
            messages=len(messages),
        ) as span:
            async with self.locks.hold(session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT):
                run = await self.conversation_manager.record_external_run(
                    conversation,
                    run_id=run_id,
                    messages=messages,
                    name=self.agent_tentacle_id,
                    model_name=(
                        turn.accumulator.route.model
                        if turn.accumulator.route is not None
                        else None
                    ),
                    context_window=turn.accumulator.context_window,
                    context_used=turn.accumulator.context_used,
                    permission_mode=turn.permission_mode,
                    cwd=Path(state.cwd) if state.cwd else None,
                    native_session_id=session_id,
                    source="gateway" if turn.prompt_via_gateway else "local",
                    start_offset=turn.start_seq,
                    end_offset=turn.end_seq,
                )
                span.set_attribute("committed", run is not None)
                if state.compactions is not None:
                    await state.compactions.record_memberships()
                await turn.native.close(
                    run, run_id=run_id, answer=turn.accumulator.result_text
                )
                state.floor = max(state.floor, turn.end_seq)
                state.commit_pulse.set()
                logger.info(
                    "session %s: turn %s synced — %d messages, seqs %d-%d",
                    session_id,
                    run_id,
                    len(messages),
                    turn.start_seq,
                    turn.end_seq,
                )

    async def record_permission_mode(
        self, state: TailState, preset: str | None
    ) -> None:
        """Keep the conversation's posture at what the session log last said.
        Observed names are retained even when absent from the driven catalog."""
        conversation = state.conversation
        if conversation is None or preset is None:
            return
        if preset == conversation.permission_mode:
            return
        await self.conversation_manager.set_permission_mode(conversation, preset)

agent_tentacle_id instance-attribute

agent_tentacle_id: str = agent_tentacle_id

conversation_manager instance-attribute

conversation_manager = conversation_manager

thread_manager instance-attribute

thread_manager = thread_manager

locks instance-attribute

locks = locks if locks is not None else SessionLocks()

sessions instance-attribute

sessions: dict[str, TailState] = {}

attach_remote async

attach_remote(
    session_id: str,
    transcript_path: Path,
    cwd: str,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]

Register a streamed session and answer where it resumes: the seq after the committed floor, recomputed from the durable runs — the client holds no cursor of its own. A lingering registration (its client died without a close) is replaced; the dead route keeps feeding the state it attached, and its commits are idempotent.

Source code in octomate/tentacles/deepseek/tailer.py
async def attach_remote(
    self,
    session_id: str,
    transcript_path: Path,
    cwd: str,
    sender: UserProfile,
    address: ChannelAddress,
    impulses: ObjectSendStream[Impulse],
) -> tuple[TailState, dict[UUID7, int]]:
    """Register a streamed session and answer where it resumes: the seq
    after the committed floor, recomputed from the durable runs — the
    client holds no cursor of its own. A lingering registration (its
    client died without a close) is replaced; the dead route keeps feeding
    the state it attached, and its commits are idempotent."""
    state = TailState(
        session_id, transcript_path, cwd, asyncio.Event(), sender, address, impulses
    )
    thread = await self.session_thread(session_id)
    state.conversation = await self.conversation_manager.ensure(
        thread.id, agent_tentacle_id=self.agent_tentacle_id, native=True
    )
    state.recorded = state.conversation.native_run_ids
    state.compactions = DeepseekCompactions(
        self.conversation_manager,
        state.conversation,
        session_id,
        source=str(transcript_path),
    )
    state.context_window = await self.conversation_manager.latest_context_window(
        state.conversation.id
    )
    state.floor = committed_floor(state.conversation)
    self.sessions[session_id] = state
    logger.info("session %s: remote tail attached", session_id)
    return state, {state.conversation.id: state.floor + 1}

feed_remote async

feed_remote(state: TailState, raw: str) -> None

Fold one history entry; the route validates the sequence framing.

Source code in octomate/tentacles/deepseek/tailer.py
async def feed_remote(self, state: TailState, raw: str) -> None:
    """Fold one history entry; the route validates the sequence framing."""
    try:
        entry = history_entry_adapter.validate_json(raw)
    except ValidationError:
        logger.debug("skipping unparseable dsh history entry")
        return
    await self.process_entry(state, entry)

detach_remote

detach_remote(state: TailState) -> None

Drop a streamed session's registration. Nothing commits on the way out — a dsh turn closes on its own turn/end line, so a turn still open here is mid-flight, and the next connect re-streams it whole from the committed floor.

Source code in octomate/tentacles/deepseek/tailer.py
def detach_remote(self, state: TailState) -> None:
    """Drop a streamed session's registration. Nothing commits on the way
    out — a dsh turn closes on its own `turn/end` line, so a turn still
    open here is mid-flight, and the next connect re-streams it whole from
    the committed floor."""
    if self.sessions.get(state.session_id) is state:
        del self.sessions[state.session_id]

stop_turn async

stop_turn(session_id: str) -> None

The turn just stopped — its Stop hook fired: wait for the stopped turn's streamed close to commit, then ask the drain. Runs detached from the hook (dsh's stopping seam waits on the hook serially, ahead of the very turn/end this waits for). A session no stream covers has nothing to settle: its turns land at the next connect.

Source code in octomate/tentacles/deepseek/tailer.py
async def stop_turn(self, session_id: str) -> None:
    """The turn just stopped — its `Stop` hook fired: wait for the stopped
    turn's streamed close to commit, then ask the drain. Runs detached
    from the hook (dsh's stopping seam waits on the hook serially, ahead
    of the very `turn/end` this waits for). A session no stream covers has
    nothing to settle: its turns land at the next connect."""
    state = self.sessions.get(session_id)
    if state is None:
        return
    state.commit_pulse.clear()
    with contextlib.suppress(TimeoutError):
        await asyncio.wait_for(state.commit_pulse.wait(), STOP_SETTLE_TIMEOUT)
    state.stop_event.set()

shutdown async

shutdown() -> None
Source code in octomate/tentacles/deepseek/tailer.py
async def shutdown(self) -> None:
    self.sessions.clear()

session_thread async

session_thread(session_id: str) -> Thread

Reuse the session thread attributed at authenticated entry.

Source code in octomate/tentacles/deepseek/tailer.py
async def session_thread(self, session_id: str) -> Thread:
    """Reuse the session thread attributed at authenticated entry."""
    return await self.thread_manager.ensure(
        ThreadKey(
            channel_tentacle_id=self.agent_tentacle_id,
            chat_type="thread",
            chat_id=session_id,
        ),
        native=True,
    )

process_entry async

process_entry(
    state: TailState, entry: HistoryEntry
) -> None
Source code in octomate/tentacles/deepseek/tailer.py
async def process_entry(self, state: TailState, entry: HistoryEntry) -> None:
    event = entry.event
    assert state.compactions is not None
    await state.compactions.consume(event)
    if event.type == "compaction/end" and state.open_turn is None:
        await state.compactions.record_memberships()
    if event.seq <= state.floor:
        return
    if event.type == "request/context":
        context = request_route_of(event)
        if context is not None:
            state.context_window = context.context_window
    if event.type == "session/title":
        try:
            name = SessionTitle.model_validate(event.data).title
        except ValidationError:
            return
        if not name or not name.strip():
            return
        conversation = state.conversation
        assert conversation is not None
        async with self.locks.hold(state.session_id):
            await self.conversation_manager.set_name(conversation, name)
            thread = await self.session_thread(state.session_id)
            await self.thread_manager.rename(thread, name)
        return
    if event.type == "permission/preset":
        preset = permission_preset_of(event)
        await self.record_permission_mode(state, preset)
        if state.open_turn is not None and preset is not None:
            state.open_turn.permission_mode = preset
        return
    if state.open_turn is None:
        if event.type == "user/message":
            prompt = human_prompt(event)
            if prompt is not None:
                state.prompts.append(prompt)
        elif event.type == "turn/start":
            prompts = state.prompts
            state.prompts = []
            number = (
                event.data.get("turn") if isinstance(event.data, dict) else None
            )
            number = number if isinstance(number, int) else None
            run_id = (
                f"{state.session_id}:{number if number is not None else event.seq}"
            )
            state.open_turn = OpenTurn(
                turn=number,
                start_seq=prompts[0].seq if prompts else event.seq,
                end_seq=event.seq,
                prompt_via_gateway=any(prompt.via_gateway for prompt in prompts),
                permission_mode=(
                    state.conversation.permission_mode
                    if state.conversation is not None
                    else None
                ),
                accumulator=DeepseekRunAccumulator(
                    context_window=state.context_window
                ),
            )
            state.open_turn.native = await NativeTurn.open(
                run_id=run_id,
                recorded=state.recorded,
                conversations=self.conversation_manager,
                threads=self.thread_manager,
                locks=self.locks,
                address=state.address,
                sender=state.sender,
                impulses=state.impulses,
                messages=state.open_turn.accumulator.messages,
            )
            if state.open_turn.native is None:
                return
            for prompt in prompts:
                await self.record_prompt(state, state.open_turn, prompt)
            await self.fold(state.open_turn, state, entry)
        return
    turn = state.open_turn
    if turn.native is None:
        if event.type == "turn/end":
            state.open_turn = None
            await state.compactions.record_memberships()
        return
    if event.type == "user/message":
        prompt = human_prompt(event)
        if prompt is not None:
            await self.record_prompt(state, turn, prompt)
            turn.prompt_via_gateway = turn.prompt_via_gateway or prompt.via_gateway
    await self.fold(turn, state, entry)
    if turn.accumulator.turn_ended:
        state.open_turn = None
        end = turn_end_of(event)
        if end is not None and end.turn is not None:
            turn.turn = end.turn
        await self.commit_turn(state, turn)

record_prompt async

record_prompt(
    state: TailState, turn: OpenTurn, prompt: PendingPrompt
) -> None

Keep each human input where it occurs, including mid-turn steering.

The event seq is stable across reconnects, even before dsh reports a turn number. Its ledger row grants access while the turn is still streaming.

Source code in octomate/tentacles/deepseek/tailer.py
async def record_prompt(
    self, state: TailState, turn: OpenTurn, prompt: PendingPrompt
) -> None:
    """Keep each human input where it occurs, including mid-turn steering.

    The event seq is stable across reconnects, even before dsh reports a turn
    number. Its ledger row grants access while the turn is still streaming.
    """
    assert turn.native is not None
    await turn.native.prompt(
        message_id=f"{state.session_id}:message:{prompt.seq}",
        text=prompt.text,
        timestamp=prompt.time,
        metadata=deepseek_metadata([prompt.event.model_dump(mode="json")]),
    )

fold async

fold(
    turn: OpenTurn, state: TailState, entry: HistoryEntry
) -> None

Fold and publish one entry, dating messages by the log's clock.

Committed seqs never reach the fold. The native thread receives only run brackets, with the end delivered after its ledger binding commits. Re-streaming an open turn starts it again without waking a reflex.

Source code in octomate/tentacles/deepseek/tailer.py
async def fold(self, turn: OpenTurn, state: TailState, entry: HistoryEntry) -> None:
    """Fold and publish one entry, dating messages by the log's clock.

    Committed seqs never reach the fold. The native thread receives only run
    brackets, with the end delivered after its ledger binding commits.
    Re-streaming an open turn starts it again without waking a reflex.
    """
    accumulator = turn.accumulator
    written = len(accumulator.messages)
    frame = SessionEventFrame(
        type="session/event",
        session_id=state.session_id,
        event=entry.event,
        view=entry.view,
    )
    assert turn.native is not None
    await turn.native.fold(accumulator.consume(frame))
    stamp(accumulator.messages[written:], event_time(entry.event))
    turn.end_seq = entry.event.seq

commit_turn async

commit_turn(state: TailState, turn: OpenTurn) -> None
Source code in octomate/tentacles/deepseek/tailer.py
async def commit_turn(self, state: TailState, turn: OpenTurn) -> None:
    session_id = state.session_id
    run_key = turn.turn if turn.turn is not None else turn.start_seq
    run_id = f"{session_id}:{run_key}"
    if turn.native is None:
        return
    messages = turn.accumulator.messages
    conversation = state.conversation
    assert conversation is not None
    with deepseek_logfire.span(
        "deepseek.tailer.commit_turn {run_id} [{session_id}]",
        run_id=run_id,
        session_id=session_id,
        start_seq=turn.start_seq,
        end_seq=turn.end_seq,
        messages=len(messages),
    ) as span:
        async with self.locks.hold(session_id, acquire_timeout=COMMIT_LOCK_TIMEOUT):
            run = await self.conversation_manager.record_external_run(
                conversation,
                run_id=run_id,
                messages=messages,
                name=self.agent_tentacle_id,
                model_name=(
                    turn.accumulator.route.model
                    if turn.accumulator.route is not None
                    else None
                ),
                context_window=turn.accumulator.context_window,
                context_used=turn.accumulator.context_used,
                permission_mode=turn.permission_mode,
                cwd=Path(state.cwd) if state.cwd else None,
                native_session_id=session_id,
                source="gateway" if turn.prompt_via_gateway else "local",
                start_offset=turn.start_seq,
                end_offset=turn.end_seq,
            )
            span.set_attribute("committed", run is not None)
            if state.compactions is not None:
                await state.compactions.record_memberships()
            await turn.native.close(
                run, run_id=run_id, answer=turn.accumulator.result_text
            )
            state.floor = max(state.floor, turn.end_seq)
            state.commit_pulse.set()
            logger.info(
                "session %s: turn %s synced — %d messages, seqs %d-%d",
                session_id,
                run_id,
                len(messages),
                turn.start_seq,
                turn.end_seq,
            )

record_permission_mode async

record_permission_mode(
    state: TailState, preset: str | None
) -> None

Keep the conversation's posture at what the session log last said. Observed names are retained even when absent from the driven catalog.

Source code in octomate/tentacles/deepseek/tailer.py
async def record_permission_mode(
    self, state: TailState, preset: str | None
) -> None:
    """Keep the conversation's posture at what the session log last said.
    Observed names are retained even when absent from the driven catalog."""
    conversation = state.conversation
    if conversation is None or preset is None:
        return
    if preset == conversation.permission_mode:
        return
    await self.conversation_manager.set_permission_mode(conversation, preset)

committed_floor

committed_floor(conversation: Conversation) -> int

The highest event seq any committed turn covers — the stream resumes at the seq after it.

Source code in octomate/tentacles/deepseek/tailer.py
def committed_floor(conversation: Conversation) -> int:
    """The highest event seq any committed turn covers — the stream resumes at
    the seq after it."""
    return max(
        (
            run.end_offset
            for run in conversation.runs
            if isinstance(run, ExternalAgentRun) and run.end_offset is not None
        ),
        default=-1,
    )

event_time

event_time(event: SessionEvent) -> datetime

A session event's own clock — time is epoch milliseconds.

Source code in octomate/tentacles/deepseek/tailer.py
def event_time(event: SessionEvent) -> datetime:
    """A session event's own clock — `time` is epoch milliseconds."""
    return datetime.fromtimestamp(event.time / 1000, tz=UTC)

stamp

stamp(
    messages: list[ModelMessage], timestamp: datetime
) -> None

Date the messages an event produced by that event's own clock — the accumulator stamps now, which is wrong for a turn replayed off the log (AgentRun.started_at and ordering both read from these).

Source code in octomate/tentacles/deepseek/tailer.py
def stamp(messages: list[ModelMessage], timestamp: datetime) -> None:
    """Date the messages an event produced by that event's own clock — the
    accumulator stamps `now`, which is wrong for a turn replayed off the log
    (`AgentRun.started_at` and ordering both read from these)."""
    for message in messages:
        message.timestamp = timestamp

human_prompt

human_prompt(event: SessionEvent) -> PendingPrompt | None

The human's own words in a user/message, or None. dsh logs injected user-role messages in the same turn — agent-instructions, plugin runtime context — which are the harness talking, not the ledger's prompt; human prompts and late question replies are the person's input.

Source code in octomate/tentacles/deepseek/tailer.py
def human_prompt(event: SessionEvent) -> PendingPrompt | None:
    """The human's own words in a `user/message`, or None. dsh logs injected
    user-role messages in the same turn — `agent-instructions`, `plugin`
    runtime context — which are the harness talking, not the ledger's prompt;
    human prompts and late question replies are the person's input."""
    message = user_message_of(event)
    if message is None or message.source.kind not in {"user", "user-question-reply"}:
        return None
    text = text_of(message.content)
    if not text:
        return None
    return PendingPrompt(
        text=text,
        time=event_time(event),
        seq=event.seq,
        via_gateway=message.source.rpc_id is not None,
        event=event,
    )