Skip to content

Graph, state and dependencies

octomate.reflex.graph

Wiring for the reflex graph.

The nodes live one per module under nodes/; this is where they are assembled into a runnable graph. Names the rest of the project imports from octomate.reflex.graph are re-exported here so the split stays invisible to callers.

ReflexEntryT module-attribute

ReflexEntryT = TypeVar(
    "ReflexEntryT",
    bound="BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]",
)

ResponseTargetMode module-attribute

ResponseTargetMode = Literal['main', 'sub']

reflex_graph module-attribute

reflex_graph = build_reflex_graph()

ReflexGraphResult

ReflexGraphResult = (
    ReflexResult | DeferredResult | CommandOutcome
)

Awake dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

The entry node: explicit commands dispatch, batch replies resume, native handoffs land, independent work initializes and enters React, and user messages go to Route with their admitted execution thread.

Source code in octomate/reflex/nodes/awake.py
@dataclass
class Awake(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """The entry node: explicit commands dispatch, batch replies resume, native
    handoffs land, independent work initializes and enters `React`, and user
    messages go to `Route` with their admitted execution thread."""

    signal: AwakeSignal

    @reflex_logfire.instrument("reflex.awake", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> (
        Command
        | Route
        | React
        | ResumeDeferred
        | Summon
        | Teleport
        | Scheme
        | End[ReflexGraphResult]
    ):
        if isinstance(self.signal, GatewaySignal):
            ctx.state.owner_id = self.signal.owner_id

        if isinstance(self.signal, CommandSignal):
            return Command(signal=self.signal)

        if isinstance(self.signal, DeferredActionBatchResponse):
            return ResumeDeferred(awake=self.signal)

        if isinstance(self.signal, ContinueSignal):
            signal = self.signal
            destination = signal.destination
            source = ctx.deps.resolve_target(signal.source_address)
            target = ctx.deps.resolve_target(destination, mode=signal.target_mode)
            ctx.state.source_target = source
            ctx.state.target = target
            ctx.state.user_profile = signal.user_profile
            ctx.state.decision = signal.decision
            ctx.state.run_name = signal.run_name
            ctx.state.command_request_id = signal.command_request_id
            ctx.state.handoff = PendingHandoff(
                source_agent_tentacle_id=signal.agent_id,
                source_conversation_id=signal.source_conversation_id,
                source_run_id=signal.source_run_id,
                source_model_message_id=signal.source_model_message_id,
            )
            ctx.state.user_prompt = signal.user_prompt
            ctx.state.source_thread_address = signal.source_thread_address
            ctx.state.source_thread_message_ids = signal.source_thread_message_ids
            if not signal.record_handoff:
                ctx.state.handoff = None
            return React(
                resume_batch_id=signal.resume_batch_id,
                tool_results=signal.tool_results,
            )

        if isinstance(self.signal, SummonSignal):
            signal = self.signal
            destination = signal.destination
            target = ctx.deps.resolve_target(destination, mode=signal.target_mode)
            ctx.state.source_target = ctx.state.target = target
            ctx.state.user_profile = signal.user_profile
            ctx.state.decision = signal.decision
            ctx.state.run_name = "summon"
            ctx.state.handoff = PendingHandoff(
                source_agent_tentacle_id=signal.agent_id,
                source_conversation_id=signal.source_conversation_id,
            )
            await ctx.deps.thread_manager.record_outbound(
                ctx.state.execution_thread,
                agent_tentacle_id=signal.agent_id,
                sender=signal.user_profile,
                actor_kind="system",
                segments=[MarkdownSegment(data={"text": signal.decision.hint})],
            )
            if signal.project is not None:
                project = await ctx.deps.workspaces.projects.get(
                    ctx.state.owner_id, name=signal.project
                )
                if project is None:
                    raise RuntimeError(
                        f"project {signal.project!r} vanished before summon"
                    )
                workspace = await ctx.deps.workspaces.resolve(
                    ctx.state.execution_thread.id,
                    project,
                    ctx.state.owner_id,
                    signal.ref,
                )
                ctx.state.thread = await ctx.deps.thread_manager.bind(
                    ctx.state.execution_thread.id, project
                )
                await ctx.deps.workspaces.prepare(workspace)
            await ctx.deps.impulses.send(
                Impulse(
                    GatewayEvent(action="summon", destination=destination), destination
                )
            )
            return React()

        if isinstance(self.signal, DrivenGatewaySignal):
            signal = self.signal
            return await self.thread_operation(
                ctx,
                signal.decision,
                agent_id=signal.agent_id,
                sender=signal.user_profile,
                source=signal.source,
                requested_from="Trunkline",
            )

        if isinstance(self.signal, NativeGatewaySignal):
            # A native session's spell, already validated at the gateway: enter
            # the graph where React's post-run consumption would have, with the
            # registered native agent endpoint as the source.
            source = self.signal.source
            if source is None:
                raise ValueError("a gateway handoff signal needs its source address")
            decision = self.signal.decision
            if isinstance(decision, TeleportDecision):
                return await self.thread_operation(
                    ctx,
                    decision,
                    agent_id=self.signal.agent_id,
                    sender=self.signal.user_profile,
                    source=source,
                    requested_from=self.signal.agent_id,
                )
            source_target = ctx.deps.resolve_target(source)
            ctx.state.source_target = source_target
            ctx.state.user_profile = self.signal.user_profile
            ctx.state.handoff = PendingHandoff(
                source_agent_tentacle_id=self.signal.agent_id
            )
            return Scheme(
                request=decision,
                origin=source_target,
                agent_id=self.signal.agent_id,
            )

        if not isinstance(self.signal, UserMessageSignal):
            raise ValueError("Unsupported awake signal")
        if not self.signal:
            reflex_logfire.info("awake short-circuit: empty signal")
            return End(
                ReflexResult(
                    decision=None,
                    target=ResponseTarget(channel_id=""),
                )
            )

        address = self.signal.address
        source_target = ctx.deps.resolve_target(address)
        ctx.state.source_target = source_target
        ctx.state.trigger_message = self.signal.trigger_message
        ctx.state.user_profile = self.signal.messages[-1].sender
        user_prompt = "\n\n".join(str(event) for event in self.signal.messages).strip()
        ctx.state.user_prompt = user_prompt
        if not user_prompt and self.signal.trigger_message is None:
            reflex_logfire.info(
                "awake short-circuit: empty prompt",
                channel_id=address.channel_tentacle_id,
                conversation_address=str(address),
            )
            return End(
                ReflexResult(
                    decision=None,
                    target=source_target,
                )
            )
        return Route(agent_id=self.signal.agent_id)

    async def thread_operation(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        decision: SummonDecision | TeleportDecision,
        *,
        agent_id: str,
        sender: UserProfile,
        source: ChannelAddress,
        requested_from: str,
    ) -> Summon | Teleport:
        """Enter an existing thread its owner acts on: the console's operation on
        any thread, or a native session's teleport of its own."""
        origin = ctx.deps.resolve_target(
            source,
            mode="sub" if source.channel_thread_id else "main",
        )
        # Set first, so a refusal below is still reported.
        ctx.state.source_target = origin
        thread = ctx.state.execution_thread
        if thread.active_agent_tentacle_id != agent_id:
            raise ValueError("The source thread changed; reload its operations.")
        ctx.state.user_profile = sender
        ctx.state.target = origin
        if isinstance(decision, TeleportDecision):
            agent = ctx.deps.agent(decision.agent_id)
            conversation = next(
                c
                for c in thread.conversations
                if c.agent_tentacle_id == agent_id and not c.subagent_id
            )
            stored = await ctx.deps.conversation_manager.get(conversation.id)
            if thread.kind == "native_thread":
                await agent.validate_fork(stored, sender=sender)
            model = stored.runs[-1].model_name if stored.runs else thread.active_model
            ctx.state.decision = SummonDecision(
                agent_id=agent.id,
                model=None if thread.kind == "native_thread" else model,
                reason=f"Teleport requested from {requested_from}",
                hint=decision.hint,
                brief="",
            )
            return Teleport(
                request=TeleportRequest(
                    tool_call_id=None,
                    hint=decision.hint,
                    destination=decision.destination,
                    new_thread=decision.new_thread,
                    project=decision.project,
                    ref=decision.ref,
                    resume=decision.resume,
                    prompt=decision.prompt,
                ),
                origin=origin,
                agent_id=agent.id,
            )
        ctx.state.decision = decision
        ctx.state.run_name = "summon"
        ctx.state.handoff = PendingHandoff(
            source_agent_tentacle_id=agent_id,
            source_conversation_id=next(
                (
                    c.id
                    for c in thread.conversations
                    if c.agent_tentacle_id == agent_id and not c.subagent_id
                ),
                None,
            ),
        )
        return Summon()

signal instance-attribute

signal: AwakeSignal

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> (
    Command
    | Route
    | React
    | ResumeDeferred
    | Summon
    | Teleport
    | Scheme
    | End[ReflexGraphResult]
)
Source code in octomate/reflex/nodes/awake.py
@reflex_logfire.instrument("reflex.awake", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> (
    Command
    | Route
    | React
    | ResumeDeferred
    | Summon
    | Teleport
    | Scheme
    | End[ReflexGraphResult]
):
    if isinstance(self.signal, GatewaySignal):
        ctx.state.owner_id = self.signal.owner_id

    if isinstance(self.signal, CommandSignal):
        return Command(signal=self.signal)

    if isinstance(self.signal, DeferredActionBatchResponse):
        return ResumeDeferred(awake=self.signal)

    if isinstance(self.signal, ContinueSignal):
        signal = self.signal
        destination = signal.destination
        source = ctx.deps.resolve_target(signal.source_address)
        target = ctx.deps.resolve_target(destination, mode=signal.target_mode)
        ctx.state.source_target = source
        ctx.state.target = target
        ctx.state.user_profile = signal.user_profile
        ctx.state.decision = signal.decision
        ctx.state.run_name = signal.run_name
        ctx.state.command_request_id = signal.command_request_id
        ctx.state.handoff = PendingHandoff(
            source_agent_tentacle_id=signal.agent_id,
            source_conversation_id=signal.source_conversation_id,
            source_run_id=signal.source_run_id,
            source_model_message_id=signal.source_model_message_id,
        )
        ctx.state.user_prompt = signal.user_prompt
        ctx.state.source_thread_address = signal.source_thread_address
        ctx.state.source_thread_message_ids = signal.source_thread_message_ids
        if not signal.record_handoff:
            ctx.state.handoff = None
        return React(
            resume_batch_id=signal.resume_batch_id,
            tool_results=signal.tool_results,
        )

    if isinstance(self.signal, SummonSignal):
        signal = self.signal
        destination = signal.destination
        target = ctx.deps.resolve_target(destination, mode=signal.target_mode)
        ctx.state.source_target = ctx.state.target = target
        ctx.state.user_profile = signal.user_profile
        ctx.state.decision = signal.decision
        ctx.state.run_name = "summon"
        ctx.state.handoff = PendingHandoff(
            source_agent_tentacle_id=signal.agent_id,
            source_conversation_id=signal.source_conversation_id,
        )
        await ctx.deps.thread_manager.record_outbound(
            ctx.state.execution_thread,
            agent_tentacle_id=signal.agent_id,
            sender=signal.user_profile,
            actor_kind="system",
            segments=[MarkdownSegment(data={"text": signal.decision.hint})],
        )
        if signal.project is not None:
            project = await ctx.deps.workspaces.projects.get(
                ctx.state.owner_id, name=signal.project
            )
            if project is None:
                raise RuntimeError(
                    f"project {signal.project!r} vanished before summon"
                )
            workspace = await ctx.deps.workspaces.resolve(
                ctx.state.execution_thread.id,
                project,
                ctx.state.owner_id,
                signal.ref,
            )
            ctx.state.thread = await ctx.deps.thread_manager.bind(
                ctx.state.execution_thread.id, project
            )
            await ctx.deps.workspaces.prepare(workspace)
        await ctx.deps.impulses.send(
            Impulse(
                GatewayEvent(action="summon", destination=destination), destination
            )
        )
        return React()

    if isinstance(self.signal, DrivenGatewaySignal):
        signal = self.signal
        return await self.thread_operation(
            ctx,
            signal.decision,
            agent_id=signal.agent_id,
            sender=signal.user_profile,
            source=signal.source,
            requested_from="Trunkline",
        )

    if isinstance(self.signal, NativeGatewaySignal):
        # A native session's spell, already validated at the gateway: enter
        # the graph where React's post-run consumption would have, with the
        # registered native agent endpoint as the source.
        source = self.signal.source
        if source is None:
            raise ValueError("a gateway handoff signal needs its source address")
        decision = self.signal.decision
        if isinstance(decision, TeleportDecision):
            return await self.thread_operation(
                ctx,
                decision,
                agent_id=self.signal.agent_id,
                sender=self.signal.user_profile,
                source=source,
                requested_from=self.signal.agent_id,
            )
        source_target = ctx.deps.resolve_target(source)
        ctx.state.source_target = source_target
        ctx.state.user_profile = self.signal.user_profile
        ctx.state.handoff = PendingHandoff(
            source_agent_tentacle_id=self.signal.agent_id
        )
        return Scheme(
            request=decision,
            origin=source_target,
            agent_id=self.signal.agent_id,
        )

    if not isinstance(self.signal, UserMessageSignal):
        raise ValueError("Unsupported awake signal")
    if not self.signal:
        reflex_logfire.info("awake short-circuit: empty signal")
        return End(
            ReflexResult(
                decision=None,
                target=ResponseTarget(channel_id=""),
            )
        )

    address = self.signal.address
    source_target = ctx.deps.resolve_target(address)
    ctx.state.source_target = source_target
    ctx.state.trigger_message = self.signal.trigger_message
    ctx.state.user_profile = self.signal.messages[-1].sender
    user_prompt = "\n\n".join(str(event) for event in self.signal.messages).strip()
    ctx.state.user_prompt = user_prompt
    if not user_prompt and self.signal.trigger_message is None:
        reflex_logfire.info(
            "awake short-circuit: empty prompt",
            channel_id=address.channel_tentacle_id,
            conversation_address=str(address),
        )
        return End(
            ReflexResult(
                decision=None,
                target=source_target,
            )
        )
    return Route(agent_id=self.signal.agent_id)

thread_operation async

thread_operation(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    decision: SummonDecision | TeleportDecision,
    *,
    agent_id: str,
    sender: UserProfile,
    source: ChannelAddress,
    requested_from: str,
) -> Summon | Teleport

Enter an existing thread its owner acts on: the console's operation on any thread, or a native session's teleport of its own.

Source code in octomate/reflex/nodes/awake.py
async def thread_operation(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    decision: SummonDecision | TeleportDecision,
    *,
    agent_id: str,
    sender: UserProfile,
    source: ChannelAddress,
    requested_from: str,
) -> Summon | Teleport:
    """Enter an existing thread its owner acts on: the console's operation on
    any thread, or a native session's teleport of its own."""
    origin = ctx.deps.resolve_target(
        source,
        mode="sub" if source.channel_thread_id else "main",
    )
    # Set first, so a refusal below is still reported.
    ctx.state.source_target = origin
    thread = ctx.state.execution_thread
    if thread.active_agent_tentacle_id != agent_id:
        raise ValueError("The source thread changed; reload its operations.")
    ctx.state.user_profile = sender
    ctx.state.target = origin
    if isinstance(decision, TeleportDecision):
        agent = ctx.deps.agent(decision.agent_id)
        conversation = next(
            c
            for c in thread.conversations
            if c.agent_tentacle_id == agent_id and not c.subagent_id
        )
        stored = await ctx.deps.conversation_manager.get(conversation.id)
        if thread.kind == "native_thread":
            await agent.validate_fork(stored, sender=sender)
        model = stored.runs[-1].model_name if stored.runs else thread.active_model
        ctx.state.decision = SummonDecision(
            agent_id=agent.id,
            model=None if thread.kind == "native_thread" else model,
            reason=f"Teleport requested from {requested_from}",
            hint=decision.hint,
            brief="",
        )
        return Teleport(
            request=TeleportRequest(
                tool_call_id=None,
                hint=decision.hint,
                destination=decision.destination,
                new_thread=decision.new_thread,
                project=decision.project,
                ref=decision.ref,
                resume=decision.resume,
                prompt=decision.prompt,
            ),
            origin=origin,
            agent_id=agent.id,
        )
    ctx.state.decision = decision
    ctx.state.run_name = "summon"
    ctx.state.handoff = PendingHandoff(
        source_agent_tentacle_id=agent_id,
        source_conversation_id=next(
            (
                c.id
                for c in thread.conversations
                if c.agent_tentacle_id == agent_id and not c.subagent_id
            ),
            None,
        ),
    )
    return Summon()

Command dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Own one command invocation through direct feedback or an ordinary agent stream.

Source code in octomate/reflex/nodes/command.py
@dataclass
class Command(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Own one command invocation through direct feedback or an ordinary agent stream."""

    signal: CommandSignal

    @reflex_logfire.instrument("reflex.command", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> Summon | Scheme | Teleport | End[ReflexGraphResult]:
        context = self.signal.context
        agent = ctx.deps.agent(context.agent_id)
        state = ctx.state
        target = ctx.deps.resolve_target(context.address)
        state.source_target = state.target = target
        state.run_name = "command"
        state.decision = None
        state.selection = AgentRouteKey(context.agent_id, context.model)
        conversation = context.conversation
        state.conversation_id = conversation.id if conversation else None
        runtime = ctx.deps.runtime
        session, suspender, capabilities = await runtime.resources(ctx)
        async with runtime.finalizing(ctx):
            async with AsyncExitStack() as stack:
                validated = await stack.enter_async_context(
                    agent.commands.validate(
                        agent,
                        context,
                        self.signal.intent,
                        delivery_id=self.signal.delivery_id,
                        session=session,
                    )
                )
                if isinstance(validated, CommandResult | CommandError):
                    await runtime.present_command(ctx, suspender, validated)
                    return End(validated)
                await runtime.prepare_user(
                    ctx,
                    validated.profile,
                    session=session,
                    suspender=suspender,
                    capabilities=capabilities,
                )
                state.interruption.check()
                output = await stack.enter_async_context(
                    agent.commands.execute(
                        agent,
                        context,
                        self.signal.intent,
                        validated,
                        delivery_id=self.signal.delivery_id,
                        interruption=state.interruption,
                        deferred_suspender=suspender,
                        capabilities=capabilities,
                    )
                )
                if isinstance(output, CommandResult | CommandError):
                    await runtime.present_command(ctx, suspender, output)
                    return End(output)
                state.decision = suspender.continuation_decision()
                result = await runtime.drive(ctx, suspender, output)
                return await runtime.finish(ctx, session, suspender, result)

signal instance-attribute

signal: CommandSignal

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> Summon | Scheme | Teleport | End[ReflexGraphResult]
Source code in octomate/reflex/nodes/command.py
@reflex_logfire.instrument("reflex.command", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> Summon | Scheme | Teleport | End[ReflexGraphResult]:
    context = self.signal.context
    agent = ctx.deps.agent(context.agent_id)
    state = ctx.state
    target = ctx.deps.resolve_target(context.address)
    state.source_target = state.target = target
    state.run_name = "command"
    state.decision = None
    state.selection = AgentRouteKey(context.agent_id, context.model)
    conversation = context.conversation
    state.conversation_id = conversation.id if conversation else None
    runtime = ctx.deps.runtime
    session, suspender, capabilities = await runtime.resources(ctx)
    async with runtime.finalizing(ctx):
        async with AsyncExitStack() as stack:
            validated = await stack.enter_async_context(
                agent.commands.validate(
                    agent,
                    context,
                    self.signal.intent,
                    delivery_id=self.signal.delivery_id,
                    session=session,
                )
            )
            if isinstance(validated, CommandResult | CommandError):
                await runtime.present_command(ctx, suspender, validated)
                return End(validated)
            await runtime.prepare_user(
                ctx,
                validated.profile,
                session=session,
                suspender=suspender,
                capabilities=capabilities,
            )
            state.interruption.check()
            output = await stack.enter_async_context(
                agent.commands.execute(
                    agent,
                    context,
                    self.signal.intent,
                    validated,
                    delivery_id=self.signal.delivery_id,
                    interruption=state.interruption,
                    deferred_suspender=suspender,
                    capabilities=capabilities,
                )
            )
            if isinstance(output, CommandResult | CommandError):
                await runtime.present_command(ctx, suspender, output)
                return End(output)
            state.decision = suspender.continuation_decision()
            result = await runtime.drive(ctx, suspender, output)
            return await runtime.finish(ctx, session, suspender, result)

React dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Runs the summoned agent on the target channel and acts on how the run ends: a reply, a spell to perform, or a deferral to park.

Source code in octomate/reflex/nodes/react.py
@dataclass
class React(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Runs the summoned agent on the target channel and acts on how the run ends:
    a reply, a spell to perform, or a deferral to park."""

    resume_batch_id: UUID7 | None = None
    # Set by Teleport to resume the same agent where it landed, with its pending
    # call resolved — against the forked history, or in place.
    tool_results: dict[str, str] | None = None

    @reflex_logfire.instrument("reflex.react", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React | Summon | Scheme | Teleport | End[ReflexGraphResult]:
        """Dispatch to the owning tentacle, then finalize only the run executed here."""
        decision = ctx.state.decision
        if (
            ctx.deps.executor is not None
            and decision is not None
            and ctx.deps.executor != decision.agent_id
        ):
            return End(
                await ctx.deps.handoff(
                    ctx.state,
                    resume_batch_id=self.resume_batch_id,
                    tool_results=self.tool_results,
                )
            )
        async with ctx.deps.runtime.finalizing(ctx):
            return await self.react(ctx)

    async def react(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React | Summon | Scheme | Teleport | End[ReflexGraphResult]:
        state = ctx.state
        decision = state.decision
        target = state.target
        source_target = state.source_target
        if (
            decision is None
            or target is None
            or target.address is None
            or source_target is None
            or source_target.address is None
        ):
            raise ValueError("React requires a decision and resolved target")
        if not isinstance(decision, SummonDecision):
            raise ValueError("React requires a summon decision")
        target_address = target.address
        # Against the channel the run will happen on, not the one it came from. A
        # spell that moves the turn to another channel leaves those two different,
        # and which agents serve a channel is that channel's own config — resolving
        # against the origin swaps in whatever the origin happens to list first.
        resolved = ctx.deps.resolve_agent(
            target.channel_id, decision.agent_id, decision.model
        )
        model = resolved.model
        decision = decision.model_copy(
            update={"agent_id": resolved.agent, "model": model}
        )
        state.decision = decision
        state.selection = decision.key
        state.conversation_id = None
        agent = ctx.deps.agent(resolved.agent)
        claim = state.handoff
        if state.thread is not None and claim is not None:
            await claim.land(ctx.deps, state.thread, decision)
            state.handoff = None
        runtime = ctx.deps.runtime
        if state.thread is None:
            raise ValueError("agent run requires a thread to own its conversation")
        conversation = await agent.resolve_conversation(
            state.thread.id, conversation_address=target_address
        )
        state.conversation_id = conversation.id
        session, suspender, capabilities = await runtime.resources(ctx)
        # A summon names the level it hands over at; every other turn runs at the
        # one the conversation was set to.
        effort = decision.effort
        if effort is None:
            effort = await agent.resolve_effort(conversation, model=model)
        await runtime.prepare_user(
            ctx,
            state.user_profile,
            session=session,
            suspender=suspender,
            capabilities=capabilities,
        )
        deferred_results = (
            DeferredToolResults(calls=self.tool_results)
            if self.tool_results is not None
            else None
        )
        if self.resume_batch_id is not None:
            batch = await ctx.deps.action_manager.get_batch(self.resume_batch_id)
            if batch.conversation_id != conversation.id:
                raise ValueError("Deferred batch belongs to another conversation")
            deferred_results = batch.build_results()
        user_prompt = (
            None
            if self.resume_batch_id is not None or self.tool_results is not None
            else decision.brief or str(state.user_prompt or "")
        )

        async def events() -> AsyncGenerator[ReactStreamEvent[ChannelOutput], None]:
            if state.thread is None:
                raise ValueError("React requires a resolved thread")
            yield HabitatPreparationEvent(phase="preparing")
            async with (
                agent.inhabit(
                    thread=state.thread,
                    interruption=state.interruption,
                    conversation=conversation,
                    owner_id=state.user_profile.user_id,
                ) as invocation,
                agent.run_stream_events(
                    user_prompt,
                    conversation_address=target_address,
                    invocation=invocation,
                    source_thread_address=state.source_thread_address,
                    source_thread_message_ids=state.source_thread_message_ids,
                    run_name=state.run_name,
                    model=agent.models[model] if model is not None else None,
                    effort=effort,
                    deferred_tool_results=deferred_results,
                    deferred_suspender=suspender,
                    capabilities=capabilities,
                ) as stream,
            ):
                yield HabitatPreparationEvent(phase="ready")
                async for event in stream:
                    yield event

        channel = ctx.deps.channels.get(target.channel_id)
        with reflex_logfire.span(
            "react",
            channel_id=target_address.channel_tentacle_id,
            agent_id=agent.id,
            conversation_address=str(target_address),
            streaming=channel.config.stream.enabled if channel is not None else True,
            resume_batch_id=str(self.resume_batch_id) if self.resume_batch_id else None,
        ) as span:
            async with ctx.deps.gateway.driving(
                session, conversation_id=state.conversation_id
            ):
                result = await runtime.drive(ctx, suspender, events())
                span.set_attribute("react.run_id", result.run_id)
                span.set_attribute(
                    "react.deferred", isinstance(result.output, DeferredToolRequests)
                )
                if self.resume_batch_id is not None:
                    await ctx.deps.action_manager.mark_batch(
                        self.resume_batch_id, "completed", completed=True
                    )
                return await runtime.finish(ctx, session, suspender, result)

resume_batch_id class-attribute instance-attribute

resume_batch_id: UUID7 | None = None

tool_results class-attribute instance-attribute

tool_results: dict[str, str] | None = None

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> (
    React
    | Summon
    | Scheme
    | Teleport
    | End[ReflexGraphResult]
)

Dispatch to the owning tentacle, then finalize only the run executed here.

Source code in octomate/reflex/nodes/react.py
@reflex_logfire.instrument("reflex.react", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | Summon | Scheme | Teleport | End[ReflexGraphResult]:
    """Dispatch to the owning tentacle, then finalize only the run executed here."""
    decision = ctx.state.decision
    if (
        ctx.deps.executor is not None
        and decision is not None
        and ctx.deps.executor != decision.agent_id
    ):
        return End(
            await ctx.deps.handoff(
                ctx.state,
                resume_batch_id=self.resume_batch_id,
                tool_results=self.tool_results,
            )
        )
    async with ctx.deps.runtime.finalizing(ctx):
        return await self.react(ctx)

react async

react(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> (
    React
    | Summon
    | Scheme
    | Teleport
    | End[ReflexGraphResult]
)
Source code in octomate/reflex/nodes/react.py
async def react(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | Summon | Scheme | Teleport | End[ReflexGraphResult]:
    state = ctx.state
    decision = state.decision
    target = state.target
    source_target = state.source_target
    if (
        decision is None
        or target is None
        or target.address is None
        or source_target is None
        or source_target.address is None
    ):
        raise ValueError("React requires a decision and resolved target")
    if not isinstance(decision, SummonDecision):
        raise ValueError("React requires a summon decision")
    target_address = target.address
    # Against the channel the run will happen on, not the one it came from. A
    # spell that moves the turn to another channel leaves those two different,
    # and which agents serve a channel is that channel's own config — resolving
    # against the origin swaps in whatever the origin happens to list first.
    resolved = ctx.deps.resolve_agent(
        target.channel_id, decision.agent_id, decision.model
    )
    model = resolved.model
    decision = decision.model_copy(
        update={"agent_id": resolved.agent, "model": model}
    )
    state.decision = decision
    state.selection = decision.key
    state.conversation_id = None
    agent = ctx.deps.agent(resolved.agent)
    claim = state.handoff
    if state.thread is not None and claim is not None:
        await claim.land(ctx.deps, state.thread, decision)
        state.handoff = None
    runtime = ctx.deps.runtime
    if state.thread is None:
        raise ValueError("agent run requires a thread to own its conversation")
    conversation = await agent.resolve_conversation(
        state.thread.id, conversation_address=target_address
    )
    state.conversation_id = conversation.id
    session, suspender, capabilities = await runtime.resources(ctx)
    # A summon names the level it hands over at; every other turn runs at the
    # one the conversation was set to.
    effort = decision.effort
    if effort is None:
        effort = await agent.resolve_effort(conversation, model=model)
    await runtime.prepare_user(
        ctx,
        state.user_profile,
        session=session,
        suspender=suspender,
        capabilities=capabilities,
    )
    deferred_results = (
        DeferredToolResults(calls=self.tool_results)
        if self.tool_results is not None
        else None
    )
    if self.resume_batch_id is not None:
        batch = await ctx.deps.action_manager.get_batch(self.resume_batch_id)
        if batch.conversation_id != conversation.id:
            raise ValueError("Deferred batch belongs to another conversation")
        deferred_results = batch.build_results()
    user_prompt = (
        None
        if self.resume_batch_id is not None or self.tool_results is not None
        else decision.brief or str(state.user_prompt or "")
    )

    async def events() -> AsyncGenerator[ReactStreamEvent[ChannelOutput], None]:
        if state.thread is None:
            raise ValueError("React requires a resolved thread")
        yield HabitatPreparationEvent(phase="preparing")
        async with (
            agent.inhabit(
                thread=state.thread,
                interruption=state.interruption,
                conversation=conversation,
                owner_id=state.user_profile.user_id,
            ) as invocation,
            agent.run_stream_events(
                user_prompt,
                conversation_address=target_address,
                invocation=invocation,
                source_thread_address=state.source_thread_address,
                source_thread_message_ids=state.source_thread_message_ids,
                run_name=state.run_name,
                model=agent.models[model] if model is not None else None,
                effort=effort,
                deferred_tool_results=deferred_results,
                deferred_suspender=suspender,
                capabilities=capabilities,
            ) as stream,
        ):
            yield HabitatPreparationEvent(phase="ready")
            async for event in stream:
                yield event

    channel = ctx.deps.channels.get(target.channel_id)
    with reflex_logfire.span(
        "react",
        channel_id=target_address.channel_tentacle_id,
        agent_id=agent.id,
        conversation_address=str(target_address),
        streaming=channel.config.stream.enabled if channel is not None else True,
        resume_batch_id=str(self.resume_batch_id) if self.resume_batch_id else None,
    ) as span:
        async with ctx.deps.gateway.driving(
            session, conversation_id=state.conversation_id
        ):
            result = await runtime.drive(ctx, suspender, events())
            span.set_attribute("react.run_id", result.run_id)
            span.set_attribute(
                "react.deferred", isinstance(result.output, DeferredToolRequests)
            )
            if self.resume_batch_id is not None:
                await ctx.deps.action_manager.mark_batch(
                    self.resume_batch_id, "completed", completed=True
                )
            return await runtime.finish(ctx, session, suspender, result)

ResumeDeferred dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Resolves a batch from the user's reply and, once it is whole, resumes the suspended run through React.

Source code in octomate/reflex/nodes/resume_deferred.py
@dataclass
class ResumeDeferred(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Resolves a batch from the user's reply and, once it is whole, resumes the
    suspended run through `React`."""

    awake: DeferredActionBatchResponse

    @reflex_logfire.instrument("reflex.resume_deferred", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React | End[ReflexGraphResult]:
        state = ctx.state
        with reflex_logfire.span(
            "resume_deferred",
            batch_id=str(self.awake.batch_id),
        ) as span:
            batch = await ctx.deps.action_manager.get_batch(self.awake.batch_id)
            if batch.response_mode != "resume":
                raise ValueError("A live request cannot resume a suspended run")
            source = ctx.deps.resolve_target(batch.source_address)
            target = ctx.deps.resolve_target(
                batch.target_address, mode=batch.target_mode
            )
            ctx.deps.agent(batch.agent_tentacle_id)
            batch = await ctx.deps.action_manager.resolve_batch(self.awake)
            span.set_attribute("run_name", batch.run_name)
            span.set_attribute("batch_status", batch.status)
            span.set_attribute("completed", batch.completed)
        # For every reader still showing the batch's cards, before the run resumes.
        await ctx.deps.impulses.send(
            Impulse(ActionBatchAnsweredEvent.of(self.awake), batch.target_address)
        )
        state.target = target
        state.source_target = source

        if isinstance(batch.decision, SummonDecision):
            decision = batch.decision
        elif batch.decision:
            decision = SummonDecision.model_validate(batch.decision)
        else:
            resolved = ctx.deps.resolve_agent(
                batch.source_address.channel_tentacle_id,
                batch.agent_tentacle_id,
                None,
            )
            model = resolved.model
            decision = SummonDecision(
                action="summon",
                agent_id=resolved.agent,
                model=model,
                reason="Resuming deferred human input.",
                hint="Resuming deferred human input.",
                brief="",
            )
        if not isinstance(decision, SummonDecision):
            raise ValueError("react deferred batch requires a summon decision")
        decision = decision.model_copy(update={"agent_id": batch.agent_tentacle_id})
        state.decision = decision
        if batch.status in {"completed", "resuming"}:
            reflex_logfire.info("resume already completed", batch_id=str(batch.id))
            return End(ReflexResult(decision=decision, target=target))
        if not batch.completed:
            return End(
                DeferredResult(
                    requests=batch.requests,
                    target=target,
                    run_name=batch.run_name or "react",
                    result=AgentRunResult(batch.requests),
                    batch_id=batch.id,
                )
            )

        await ctx.deps.action_manager.mark_batch(batch.id, "resuming")
        # The resumed agent run continues the batch's conversation, so bind the
        # thread that owns it (React reads state.thread for the run's thread_id).
        # Through the conversation and not the address: a chat room's kick ran in a
        # sub-thread, and the address names the chat it was seen on, which would
        # answer the deferral in a context the suspended run never had.
        thread_id = await ctx.deps.conversation_manager.thread_id(batch.conversation_id)
        if thread_id is None:
            raise ValueError(
                f"deferred batch {batch.id} names conversation "
                f"{batch.conversation_id}, which does not exist"
            )
        thread = await ctx.deps.thread_manager.get(thread_id, with_messages=False)
        if thread is None:
            raise ValueError(
                f"conversation {batch.conversation_id} names thread {thread_id}, "
                "which does not exist"
            )
        state.thread = thread
        state.user_prompt = None
        state.run_name = "resume"
        reflex_logfire.info("resume routes to React", batch_id=str(batch.id))
        return React(resume_batch_id=batch.id)

awake instance-attribute

awake: DeferredActionBatchResponse

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]
Source code in octomate/reflex/nodes/resume_deferred.py
@reflex_logfire.instrument("reflex.resume_deferred", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]:
    state = ctx.state
    with reflex_logfire.span(
        "resume_deferred",
        batch_id=str(self.awake.batch_id),
    ) as span:
        batch = await ctx.deps.action_manager.get_batch(self.awake.batch_id)
        if batch.response_mode != "resume":
            raise ValueError("A live request cannot resume a suspended run")
        source = ctx.deps.resolve_target(batch.source_address)
        target = ctx.deps.resolve_target(
            batch.target_address, mode=batch.target_mode
        )
        ctx.deps.agent(batch.agent_tentacle_id)
        batch = await ctx.deps.action_manager.resolve_batch(self.awake)
        span.set_attribute("run_name", batch.run_name)
        span.set_attribute("batch_status", batch.status)
        span.set_attribute("completed", batch.completed)
    # For every reader still showing the batch's cards, before the run resumes.
    await ctx.deps.impulses.send(
        Impulse(ActionBatchAnsweredEvent.of(self.awake), batch.target_address)
    )
    state.target = target
    state.source_target = source

    if isinstance(batch.decision, SummonDecision):
        decision = batch.decision
    elif batch.decision:
        decision = SummonDecision.model_validate(batch.decision)
    else:
        resolved = ctx.deps.resolve_agent(
            batch.source_address.channel_tentacle_id,
            batch.agent_tentacle_id,
            None,
        )
        model = resolved.model
        decision = SummonDecision(
            action="summon",
            agent_id=resolved.agent,
            model=model,
            reason="Resuming deferred human input.",
            hint="Resuming deferred human input.",
            brief="",
        )
    if not isinstance(decision, SummonDecision):
        raise ValueError("react deferred batch requires a summon decision")
    decision = decision.model_copy(update={"agent_id": batch.agent_tentacle_id})
    state.decision = decision
    if batch.status in {"completed", "resuming"}:
        reflex_logfire.info("resume already completed", batch_id=str(batch.id))
        return End(ReflexResult(decision=decision, target=target))
    if not batch.completed:
        return End(
            DeferredResult(
                requests=batch.requests,
                target=target,
                run_name=batch.run_name or "react",
                result=AgentRunResult(batch.requests),
                batch_id=batch.id,
            )
        )

    await ctx.deps.action_manager.mark_batch(batch.id, "resuming")
    # The resumed agent run continues the batch's conversation, so bind the
    # thread that owns it (React reads state.thread for the run's thread_id).
    # Through the conversation and not the address: a chat room's kick ran in a
    # sub-thread, and the address names the chat it was seen on, which would
    # answer the deferral in a context the suspended run never had.
    thread_id = await ctx.deps.conversation_manager.thread_id(batch.conversation_id)
    if thread_id is None:
        raise ValueError(
            f"deferred batch {batch.id} names conversation "
            f"{batch.conversation_id}, which does not exist"
        )
    thread = await ctx.deps.thread_manager.get(thread_id, with_messages=False)
    if thread is None:
        raise ValueError(
            f"conversation {batch.conversation_id} names thread {thread_id}, "
            "which does not exist"
        )
    state.thread = thread
    state.user_prompt = None
    state.run_name = "resume"
    reflex_logfire.info("resume routes to React", batch_id=str(batch.id))
    return React(resume_batch_id=batch.id)

Route dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Choose an agent for an inbound message, then enter React.

Source code in octomate/reflex/nodes/route.py
@dataclass
class Route(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Choose an agent for an inbound message, then enter `React`."""

    agent_id: str | None = (
        None  # Explicit caller choice takes precedence over ownership.
    )

    @reflex_logfire.instrument("reflex.route", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React:
        state = ctx.state
        source_target = state.source_target
        if source_target is None or source_target.address is None:
            raise ValueError("Route requires a resolved source target")

        owner_id = state.user_profile.user_id
        if owner_id is None:
            raise PermissionError("An agent task requires a registered owner")
        source_address = source_target.address
        await ctx.deps.impulses.send(
            Impulse(ReflexPhaseChangedEvent(phase="routing"), source_address)
        )
        starts_task = source_target.starts_task
        message = state.trigger_message
        previous = None
        if starts_task and message is not None and message.reply_id:
            surface = state.execution_thread
            previous = await ctx.deps.thread_manager.quoted_task(
                surface, message.reply_id, owner_id
            )
        chat = previous if starts_task else state.thread
        active_agent_id = chat.active_agent_tentacle_id if chat is not None else None
        agent_id = self.agent_id
        model = None
        hint = ""
        state.handoff = None
        if agent_id is not None:
            reason = "The caller selected this agent for the turn."
        elif chat is not None and active_agent_id is not None:
            agent_id = active_agent_id
            model = chat.active_model
            reason = hint = "Continuing with the active thread owner."
        elif (
            source_address.channel_thread_id
            and source_target.thread_strategy == "flat_thread"
        ):
            reflex_logfire.info(
                "route: flat-thread, skipping triage",
                channel_id=source_address.channel_tentacle_id,
                conversation_address=str(source_address),
            )
            reason = hint = "Continuing in the current thread."
            state.handoff = PendingHandoff()
        else:
            reason = "Entry agent."

        resolved = ctx.deps.resolve_agent(
            source_address.channel_tentacle_id, agent_id, model
        )
        await ctx.deps.load_pending_prompt(
            state, resolved.agent, include_recap=previous is None
        )
        state.decision = SummonDecision(
            action="summon",
            agent_id=resolved.agent,
            model=resolved.model,
            reason=reason,
            hint=hint,
            brief="",
        )
        state.target = replace(
            source_target, mode="sub" if source_address.channel_thread_id else "main"
        )
        if not starts_task:
            return React()
        channel = ctx.deps.channel(source_target)
        if not channel.accepts_sub_thread(source_address):
            state.thread = previous or await ctx.deps.thread_manager.open_sub_thread(
                state.execution_thread,
                owner_id=owner_id,
                entry_message_id=message.id if message is not None else None,
            )
            state.handoff = PendingHandoff()
            return React()
        if message is None:
            raise ValueError("A new task needs its triggering message")
        opened = await channel.start_thread(
            source_address,
            message.message_text or "",
            root_message=message,
        )
        state.thread = await ctx.deps.thread_manager.ensure(
            opened,
            owner_id=owner_id,
            entry_message_id=message.id,
        )
        if previous is not None:
            agent = ctx.deps.agent(resolved.agent)
            source = await ctx.deps.conversation_manager.ensure(
                previous.id, agent_tentacle_id=agent.id, with_runs=False
            )
            async with ctx.deps.gateway.driving(None, conversation_id=source.id):
                state.thread = await agent.fork(
                    source,
                    ThreadKey.model_validate(opened),
                    sender=state.user_profile,
                    model=resolved.model,
                )
        state.target = replace(source_target, address=opened, mode="sub")
        state.handoff = PendingHandoff()
        return React()

agent_id class-attribute instance-attribute

agent_id: str | None = None

run async

run(ctx: GraphRunContext[ReflexState, ReflexDeps]) -> React
Source code in octomate/reflex/nodes/route.py
@reflex_logfire.instrument("reflex.route", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React:
    state = ctx.state
    source_target = state.source_target
    if source_target is None or source_target.address is None:
        raise ValueError("Route requires a resolved source target")

    owner_id = state.user_profile.user_id
    if owner_id is None:
        raise PermissionError("An agent task requires a registered owner")
    source_address = source_target.address
    await ctx.deps.impulses.send(
        Impulse(ReflexPhaseChangedEvent(phase="routing"), source_address)
    )
    starts_task = source_target.starts_task
    message = state.trigger_message
    previous = None
    if starts_task and message is not None and message.reply_id:
        surface = state.execution_thread
        previous = await ctx.deps.thread_manager.quoted_task(
            surface, message.reply_id, owner_id
        )
    chat = previous if starts_task else state.thread
    active_agent_id = chat.active_agent_tentacle_id if chat is not None else None
    agent_id = self.agent_id
    model = None
    hint = ""
    state.handoff = None
    if agent_id is not None:
        reason = "The caller selected this agent for the turn."
    elif chat is not None and active_agent_id is not None:
        agent_id = active_agent_id
        model = chat.active_model
        reason = hint = "Continuing with the active thread owner."
    elif (
        source_address.channel_thread_id
        and source_target.thread_strategy == "flat_thread"
    ):
        reflex_logfire.info(
            "route: flat-thread, skipping triage",
            channel_id=source_address.channel_tentacle_id,
            conversation_address=str(source_address),
        )
        reason = hint = "Continuing in the current thread."
        state.handoff = PendingHandoff()
    else:
        reason = "Entry agent."

    resolved = ctx.deps.resolve_agent(
        source_address.channel_tentacle_id, agent_id, model
    )
    await ctx.deps.load_pending_prompt(
        state, resolved.agent, include_recap=previous is None
    )
    state.decision = SummonDecision(
        action="summon",
        agent_id=resolved.agent,
        model=resolved.model,
        reason=reason,
        hint=hint,
        brief="",
    )
    state.target = replace(
        source_target, mode="sub" if source_address.channel_thread_id else "main"
    )
    if not starts_task:
        return React()
    channel = ctx.deps.channel(source_target)
    if not channel.accepts_sub_thread(source_address):
        state.thread = previous or await ctx.deps.thread_manager.open_sub_thread(
            state.execution_thread,
            owner_id=owner_id,
            entry_message_id=message.id if message is not None else None,
        )
        state.handoff = PendingHandoff()
        return React()
    if message is None:
        raise ValueError("A new task needs its triggering message")
    opened = await channel.start_thread(
        source_address,
        message.message_text or "",
        root_message=message,
    )
    state.thread = await ctx.deps.thread_manager.ensure(
        opened,
        owner_id=owner_id,
        entry_message_id=message.id,
    )
    if previous is not None:
        agent = ctx.deps.agent(resolved.agent)
        source = await ctx.deps.conversation_manager.ensure(
            previous.id, agent_tentacle_id=agent.id, with_runs=False
        )
        async with ctx.deps.gateway.driving(None, conversation_id=source.id):
            state.thread = await agent.fork(
                source,
                ThreadKey.model_validate(opened),
                sender=state.user_profile,
                model=resolved.model,
            )
    state.target = replace(source_target, address=opened, mode="sub")
    state.handoff = PendingHandoff()
    return React()

Scheme dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

A scheme call: hand this turn's brief to the asking user's direct messages.

The receiver is whoever already owns that DM, or the channel's default agent when nobody does — never an agent this run picked, so a group can't point someone's private assistant somewhere. From there it is an ordinary handoff: the brief becomes the receiving agent's prompt and the handoff is recorded on the DM's own thread, the same way Route re-enters React with a decision it resolved itself.

Source code in octomate/reflex/nodes/scheme.py
@dataclass
class Scheme(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """A `scheme` call: hand this turn's brief to the asking user's direct messages.

    The receiver is whoever already owns that DM, or the channel's default agent when
    nobody does — never an agent this run picked, so a group can't point someone's
    private assistant somewhere. From there it is an ordinary handoff: the brief becomes
    the receiving agent's prompt and the handoff is recorded on the DM's own thread, the
    same way `Route` re-enters `React` with a decision it resolved itself.
    """

    request: SchemeDecision
    origin: ResponseTarget
    agent_id: str

    @reflex_logfire.instrument("reflex.scheme", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React | End[ReflexGraphResult]:
        state = ctx.state
        origin = self.origin
        if origin.address is None:
            raise ValueError("Scheme requires a resolved origin")
        await ctx.deps.impulses.send(
            Impulse(
                ReflexPhaseChangedEvent(phase="moving", spell="scheme"),
                origin.address,
            )
        )
        # Where the gate resolved this to: this channel's direct messages, or another
        # channel's, with the account there taken from the identity registry.
        target = self.request.destination
        channel = ctx.deps.channel(target.channel_tentacle_id)

        # The hint opens it, the way a teleport's does the sub-thread it lands in: on a
        # channel that can only be run inside a thread it is the message that thread
        # hangs from, and it is written to be read. The brief is not — that goes to
        # whoever answers, as their prompt.
        dm_address = await channel.open_dm(target.user_id, self.request.hint)
        if dm_address is None:
            # The gate refused the cases we can know in advance, so this is the platform
            # failing at the moment of asking. Nothing has moved: leave the turn where
            # it is, with the origin agent's own reply already delivered.
            logger.warning(
                "Channel %s could not open a DM with %s; leaving the turn here",
                target.channel_tentacle_id,
                target.user_id,
            )
            return End(ReflexResult(decision=None, target=origin))

        dm_thread = await ctx.deps.thread_manager.ensure(
            dm_address, owner_id=state.owner_id
        )
        receiver = dm_thread.active_agent_tentacle_id
        # Resolved against the *target* channel: which agents serve a channel is that
        # channel's own config, so a cross-channel move lands on an agent configured
        # there rather than one carried over from where the request came from.
        resolved = ctx.deps.resolve_agent(
            target.channel_tentacle_id,
            receiver,
            dm_thread.active_model if receiver else None,
        )
        state.run_name = "summon"
        state.thread = await ctx.deps.thread_manager.enter(
            dm_address,
            current=state.thread,
            owner_id=state.owner_id,
        )
        state.target = ctx.deps.resolve_target(dm_address)
        await ctx.deps.impulses.send(
            Impulse(
                GatewayEvent(action="scheme", destination=dm_address), origin.address
            )
        )
        state.decision = SummonDecision(
            action="summon",
            agent_id=resolved.agent,
            model=resolved.model,
            reason="Continuing with this user privately.",
            hint=self.request.hint,
            brief=self.request.brief,
        )
        return React()

request instance-attribute

request: SchemeDecision

origin instance-attribute

origin: ResponseTarget

agent_id instance-attribute

agent_id: str

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]
Source code in octomate/reflex/nodes/scheme.py
@reflex_logfire.instrument("reflex.scheme", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]:
    state = ctx.state
    origin = self.origin
    if origin.address is None:
        raise ValueError("Scheme requires a resolved origin")
    await ctx.deps.impulses.send(
        Impulse(
            ReflexPhaseChangedEvent(phase="moving", spell="scheme"),
            origin.address,
        )
    )
    # Where the gate resolved this to: this channel's direct messages, or another
    # channel's, with the account there taken from the identity registry.
    target = self.request.destination
    channel = ctx.deps.channel(target.channel_tentacle_id)

    # The hint opens it, the way a teleport's does the sub-thread it lands in: on a
    # channel that can only be run inside a thread it is the message that thread
    # hangs from, and it is written to be read. The brief is not — that goes to
    # whoever answers, as their prompt.
    dm_address = await channel.open_dm(target.user_id, self.request.hint)
    if dm_address is None:
        # The gate refused the cases we can know in advance, so this is the platform
        # failing at the moment of asking. Nothing has moved: leave the turn where
        # it is, with the origin agent's own reply already delivered.
        logger.warning(
            "Channel %s could not open a DM with %s; leaving the turn here",
            target.channel_tentacle_id,
            target.user_id,
        )
        return End(ReflexResult(decision=None, target=origin))

    dm_thread = await ctx.deps.thread_manager.ensure(
        dm_address, owner_id=state.owner_id
    )
    receiver = dm_thread.active_agent_tentacle_id
    # Resolved against the *target* channel: which agents serve a channel is that
    # channel's own config, so a cross-channel move lands on an agent configured
    # there rather than one carried over from where the request came from.
    resolved = ctx.deps.resolve_agent(
        target.channel_tentacle_id,
        receiver,
        dm_thread.active_model if receiver else None,
    )
    state.run_name = "summon"
    state.thread = await ctx.deps.thread_manager.enter(
        dm_address,
        current=state.thread,
        owner_id=state.owner_id,
    )
    state.target = ctx.deps.resolve_target(dm_address)
    await ctx.deps.impulses.send(
        Impulse(
            GatewayEvent(action="scheme", destination=dm_address), origin.address
        )
    )
    state.decision = SummonDecision(
        action="summon",
        agent_id=resolved.agent,
        model=resolved.model,
        reason="Continuing with this user privately.",
        hint=self.request.hint,
        brief=self.request.brief,
    )
    return React()

Summon dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Performs a summon: takes the surface over in place for the agent the decision names, then re-enters React there.

Source code in octomate/reflex/nodes/summon.py
@dataclass
class Summon(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Performs a summon: takes the surface over in place for the agent the decision
    names, then re-enters `React` there."""

    @reflex_logfire.instrument("reflex.summon", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React:
        state = ctx.state
        decision = state.decision
        target = state.target
        source_target = state.source_target
        if (
            decision is None
            or target is None
            or source_target is None
            or source_target.address is None
        ):
            raise ValueError("Summon requires a decision and source target")
        if not isinstance(decision, SummonDecision):
            raise ValueError("Summon requires a summon decision")
        await ctx.deps.impulses.send(
            Impulse(
                ReflexPhaseChangedEvent(phase="moving", spell="summon"),
                source_target.address,
            )
        )
        source_address = source_target.address
        target_address = target.address
        if target_address is None:
            target_address = ChannelAddress(
                channel_tentacle_id=target.channel_id,
                chat_type=source_address.chat_type,
                chat_id=source_address.chat_id,
                user_id=source_address.user_id,
                channel_thread_id=None,
                shared=source_address.shared,
            )
            target = replace(target, address=target_address)

        state.target = target
        if state.thread is not None:
            state.thread = await ctx.deps.thread_manager.enter(
                target_address,
                current=state.thread,
                owner_id=state.owner_id,
            )
        await ctx.deps.impulses.send(
            Impulse(
                GatewayEvent(action="summon", destination=target_address),
                target_address,
            )
        )
        return React()

run async

run(ctx: GraphRunContext[ReflexState, ReflexDeps]) -> React
Source code in octomate/reflex/nodes/summon.py
@reflex_logfire.instrument("reflex.summon", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React:
    state = ctx.state
    decision = state.decision
    target = state.target
    source_target = state.source_target
    if (
        decision is None
        or target is None
        or source_target is None
        or source_target.address is None
    ):
        raise ValueError("Summon requires a decision and source target")
    if not isinstance(decision, SummonDecision):
        raise ValueError("Summon requires a summon decision")
    await ctx.deps.impulses.send(
        Impulse(
            ReflexPhaseChangedEvent(phase="moving", spell="summon"),
            source_target.address,
        )
    )
    source_address = source_target.address
    target_address = target.address
    if target_address is None:
        target_address = ChannelAddress(
            channel_tentacle_id=target.channel_id,
            chat_type=source_address.chat_type,
            chat_id=source_address.chat_id,
            user_id=source_address.user_id,
            channel_thread_id=None,
            shared=source_address.shared,
        )
        target = replace(target, address=target_address)

    state.target = target
    if state.thread is not None:
        state.thread = await ctx.deps.thread_manager.enter(
            target_address,
            current=state.thread,
            owner_id=state.owner_id,
        )
    await ctx.deps.impulses.send(
        Impulse(
            GatewayEvent(action="summon", destination=target_address),
            target_address,
        )
    )
    return React()

Teleport dataclass

Bases: BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]

Create a thread at the prepared address, copy history and resume the agent.

An in-place move binds a project without creating a thread and always resumes the agent. A failed creation refuses the move before any history is copied.

Source code in octomate/reflex/nodes/teleport.py
@dataclass
class Teleport(BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]):
    """Create a thread at the prepared address, copy history and resume the agent.

    An in-place move binds a project without creating a thread and always resumes
    the agent. A failed creation refuses the move before any history is copied.
    """

    request: TeleportRequest
    origin: ResponseTarget
    agent_id: str

    @reflex_logfire.instrument("reflex.teleport", extract_args=False)
    async def run(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> React | End[ReflexGraphResult]:
        state = ctx.state
        state.run_name = "teleport"
        origin = self.origin
        if origin.address is None or state.thread is None:
            raise ValueError("Teleport requires a resolved origin and thread")
        origin_address = origin.address
        await ctx.deps.impulses.send(
            Impulse(
                ReflexPhaseChangedEvent(phase="moving", spell="teleport"),
                origin_address,
            )
        )
        source = state.thread
        hint = self.request.hint or "Octomate is continuing this request here."
        sentence = "Continuing the conversation here."

        new_target = origin
        opened = None
        if self.request.new_thread:
            opened = await open_crossing(
                ctx, self.request.destination, origin_address, hint, self.agent_id
            )
            if opened is not None:
                new_target = ctx.deps.resolve_target(opened, mode="sub")

        new_address = new_target.address
        if self.request.new_thread and new_address == origin_address:
            raise ValueError(
                "The destination could not create a thread; nothing was teleported."
            )
        source_conversation = None
        if new_address is None or new_address == origin_address:
            # The current conversation already holds the trailing teleport
            # deferral. An explicit workspace move may still fork its runtime.
            state.target = origin
            state.handoff = None
            landed = state.thread
            conversation = await ctx.deps.conversation_manager.ensure(
                landed.id, agent_tentacle_id=self.agent_id
            )
        else:
            # Move: fork the origin conversation into the new sub-thread, claim it
            # for the same agent so follow-ups continue there, and resume against
            # the fork. The runtime prepares its destination handle after the
            # destination workspace is ready.
            if state.thread.kind == "native_thread":
                source_agent_id = state.thread.active_agent_tentacle_id
                if state.decision is None or source_agent_id is None:
                    raise ValueError(
                        "Native teleport requires its requesting user and agent."
                    )
                source = await ctx.deps.conversation_manager.ensure(
                    state.thread.id,
                    agent_tentacle_id=source_agent_id,
                )
                agent = ctx.deps.agent(self.agent_id)
                landed = await agent.fork(
                    source,
                    ThreadKey.model_validate(new_address),
                    sender=state.user_profile,
                )
                copied = await ctx.deps.conversation_manager.ensure(
                    landed.id, agent_tentacle_id=agent.id
                )
                state.decision = state.decision.model_copy(
                    update={"model": copied.runs[-1].model_name}
                )
                state.thread = landed
                state.target = new_target
                state.handoff = None
                await announce_crossing(
                    ctx,
                    self.request.destination,
                    new_address,
                    origin_address,
                    hint,
                    self.agent_id,
                )
                if self.request.prompt is None and not self.request.resume:
                    return await self.land(ctx)
                return await self.carry_on(ctx, sentence)
            landed = await ctx.deps.thread_manager.enter(
                new_address,
                current=state.thread,
                owner_id=state.owner_id,
            )
            source_conversation = await ctx.deps.conversation_manager.ensure(
                state.thread.id, agent_tentacle_id=self.agent_id
            )
            target_conversation = await ctx.deps.conversation_manager.ensure(
                landed.id, agent_tentacle_id=self.agent_id
            )
            conversation = target_conversation
            state.thread = landed
            state.target = new_target
            state.handoff = PendingHandoff(
                source_agent_tentacle_id=self.agent_id,
                source_conversation_id=source_conversation.id,
            )

        project = self.request.project
        carried = (
            await ctx.deps.workspaces.projects.get(state.owner_id, thread=source)
            if project is None and landed.id != source.id
            else None
        )
        if project is not None:
            state.thread = await self.bind(ctx, landed, project)
            sentence = (
                f"Continuing the conversation here, in the workspace of {project!r}."
            )
        elif carried is not None:
            # The conversation was about a project, and its history is of work in
            # that tree: the thread it lands in is about the same one, as it stands.
            state.thread = await ctx.deps.thread_manager.bind(landed.id, carried)
            await ctx.deps.workspaces.carry(source, state.thread, state.owner_id)
            sentence = (
                "Continuing the conversation here, in a workspace of "
                f"{carried.name!r} that holds your work as you left it."
            )
        # The agent resumes in another directory either way — a new thread's own
        # workspace, or the project's — and a runtime session may be filed under
        # the one it ran in. Ink owns the move; the graph chooses when.
        agent = ctx.deps.agent(self.agent_id)
        if not agent.supports_session_fork:
            raise NotImplementedError(
                f"Agent {agent.id!r} does not support session forking"
            )
        source_session_id = (source_conversation or conversation).external_id
        async with agent.inhabit(
            thread=state.thread,
            conversation=conversation,
            owner_id=state.owner_id,
            interruption=state.interruption,
        ) as invocation:
            external_id = await agent.ink.fork_session(
                source_session_id,
                cwd=invocation.cwd,
                habitat=invocation.habitat,
                env=invocation.environment,
            )
            if source_conversation is not None:
                carry = (
                    external_id is not None
                    and external_id == source_conversation.external_id
                )
                await ctx.deps.conversation_manager.fork(
                    source_conversation,
                    conversation,
                    carry_external_id=carry,
                    external_id=None if carry else external_id,
                )
            elif external_id is not None and external_id != conversation.external_id:
                await ctx.deps.conversation_manager.set_external_id(
                    conversation, external_id
                )
                conversation = await ctx.deps.conversation_manager.get(
                    conversation.id, with_runs=False
                )
            await agent.ink.relocate_session(
                conversation.external_id,
                cwd=invocation.cwd,
                habitat=invocation.habitat,
            )
            if source_conversation is not None:
                state.thread = await ctx.deps.thread_manager.rename(
                    state.thread,
                    ctx.deps.thread_manager.fork_title(source_conversation, source),
                )
        if opened is not None:
            await announce_crossing(
                ctx,
                self.request.destination,
                opened,
                origin_address,
                hint,
                self.agent_id,
            )
        if (
            self.request.new_thread
            and self.request.prompt is None
            and not self.request.resume
        ):
            return await self.land(ctx)
        return await self.carry_on(ctx, sentence)

    async def carry_on(
        self, ctx: GraphRunContext[ReflexState, ReflexDeps], sentence: str
    ) -> React:
        """Run the agent where the move landed: on the user's prompt, recorded there
        as their message, or on its own call answered by where it now is."""
        state = ctx.state
        address = state.target.address if state.target is not None else None
        if address is None:
            raise ValueError("Teleport carries on only where the move landed")
        prompt = self.request.prompt
        if prompt is None:
            # The pending call resolves into the resumed run, whichever runtime cast it.
            if self.request.tool_call_id is None:
                state.user_prompt = f"{sentence}\nCurrent channel address: {address}"
                return React()
            return React(tool_results={self.request.tool_call_id: sentence})
        channel = ctx.deps.channel(address.channel_tentacle_id)
        message = await ctx.deps.thread_manager.record_inbound(
            MessageEvent(
                tentacle_id=channel.id,
                chat_type=address.chat_type,
                chat_id=address.chat_id,
                user_id=address.user_id,
                channel_thread_id=address.channel_thread_id,
                shared=address.shared,
                self_id=channel.self_profile.channel_user_id,
                sender=state.user_profile,
                segments=[TextSegment(data={"text": prompt})],
                raw=prompt,
            )
        )
        state.source_target = state.target
        state.trigger_message = message
        await ctx.deps.load_pending_prompt(state, self.agent_id)
        return React()

    async def land(
        self, ctx: GraphRunContext[ReflexState, ReflexDeps]
    ) -> End[ReflexGraphResult]:
        """End the move where it landed, for the next message there to carry on:
        the handoff is recorded, as a turn's end would."""
        state = ctx.state
        if state.decision is None or state.target is None or state.thread is None:
            raise ValueError("Teleport lands with a decision, a target and a thread")
        async with ctx.deps.runtime.finalizing(ctx):
            resolved = ctx.deps.resolve_agent(
                state.target.channel_id, state.decision.agent_id, state.decision.model
            )
            state.decision = state.decision.model_copy(
                update={"agent_id": resolved.agent, "model": resolved.model}
            )
            if state.handoff is not None:
                await state.handoff.land(ctx.deps, state.thread, state.decision)
                state.handoff = None
            return End(
                ReflexResult(
                    decision=state.decision, target=state.target, outcome="handed_off"
                )
            )

    async def bind(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        thread: Thread,
        name: str,
    ) -> Thread:
        """Bind the thread landed in to the project the request names, and fork
        its workspace, so the resumed run starts in the project's code. The gate
        validated the project and the ref; a project missing here is a wiring
        bug. Answers the bound thread, re-read: the state's copy predates the
        binding, and the turn-end save reads the project off it."""
        project = await ctx.deps.workspaces.projects.get(ctx.state.owner_id, name=name)
        if project is None:
            raise RuntimeError(
                f"project {name!r} vanished between the gate and the move"
            )
        workspace = await ctx.deps.workspaces.resolve(
            thread.id,
            project,
            ctx.state.owner_id,
            self.request.ref,
        )
        await ctx.deps.workspaces.prepare(workspace)
        return await ctx.deps.thread_manager.bind(thread.id, project)

request instance-attribute

request: TeleportRequest

origin instance-attribute

origin: ResponseTarget

agent_id instance-attribute

agent_id: str

run async

run(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]
Source code in octomate/reflex/nodes/teleport.py
@reflex_logfire.instrument("reflex.teleport", extract_args=False)
async def run(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> React | End[ReflexGraphResult]:
    state = ctx.state
    state.run_name = "teleport"
    origin = self.origin
    if origin.address is None or state.thread is None:
        raise ValueError("Teleport requires a resolved origin and thread")
    origin_address = origin.address
    await ctx.deps.impulses.send(
        Impulse(
            ReflexPhaseChangedEvent(phase="moving", spell="teleport"),
            origin_address,
        )
    )
    source = state.thread
    hint = self.request.hint or "Octomate is continuing this request here."
    sentence = "Continuing the conversation here."

    new_target = origin
    opened = None
    if self.request.new_thread:
        opened = await open_crossing(
            ctx, self.request.destination, origin_address, hint, self.agent_id
        )
        if opened is not None:
            new_target = ctx.deps.resolve_target(opened, mode="sub")

    new_address = new_target.address
    if self.request.new_thread and new_address == origin_address:
        raise ValueError(
            "The destination could not create a thread; nothing was teleported."
        )
    source_conversation = None
    if new_address is None or new_address == origin_address:
        # The current conversation already holds the trailing teleport
        # deferral. An explicit workspace move may still fork its runtime.
        state.target = origin
        state.handoff = None
        landed = state.thread
        conversation = await ctx.deps.conversation_manager.ensure(
            landed.id, agent_tentacle_id=self.agent_id
        )
    else:
        # Move: fork the origin conversation into the new sub-thread, claim it
        # for the same agent so follow-ups continue there, and resume against
        # the fork. The runtime prepares its destination handle after the
        # destination workspace is ready.
        if state.thread.kind == "native_thread":
            source_agent_id = state.thread.active_agent_tentacle_id
            if state.decision is None or source_agent_id is None:
                raise ValueError(
                    "Native teleport requires its requesting user and agent."
                )
            source = await ctx.deps.conversation_manager.ensure(
                state.thread.id,
                agent_tentacle_id=source_agent_id,
            )
            agent = ctx.deps.agent(self.agent_id)
            landed = await agent.fork(
                source,
                ThreadKey.model_validate(new_address),
                sender=state.user_profile,
            )
            copied = await ctx.deps.conversation_manager.ensure(
                landed.id, agent_tentacle_id=agent.id
            )
            state.decision = state.decision.model_copy(
                update={"model": copied.runs[-1].model_name}
            )
            state.thread = landed
            state.target = new_target
            state.handoff = None
            await announce_crossing(
                ctx,
                self.request.destination,
                new_address,
                origin_address,
                hint,
                self.agent_id,
            )
            if self.request.prompt is None and not self.request.resume:
                return await self.land(ctx)
            return await self.carry_on(ctx, sentence)
        landed = await ctx.deps.thread_manager.enter(
            new_address,
            current=state.thread,
            owner_id=state.owner_id,
        )
        source_conversation = await ctx.deps.conversation_manager.ensure(
            state.thread.id, agent_tentacle_id=self.agent_id
        )
        target_conversation = await ctx.deps.conversation_manager.ensure(
            landed.id, agent_tentacle_id=self.agent_id
        )
        conversation = target_conversation
        state.thread = landed
        state.target = new_target
        state.handoff = PendingHandoff(
            source_agent_tentacle_id=self.agent_id,
            source_conversation_id=source_conversation.id,
        )

    project = self.request.project
    carried = (
        await ctx.deps.workspaces.projects.get(state.owner_id, thread=source)
        if project is None and landed.id != source.id
        else None
    )
    if project is not None:
        state.thread = await self.bind(ctx, landed, project)
        sentence = (
            f"Continuing the conversation here, in the workspace of {project!r}."
        )
    elif carried is not None:
        # The conversation was about a project, and its history is of work in
        # that tree: the thread it lands in is about the same one, as it stands.
        state.thread = await ctx.deps.thread_manager.bind(landed.id, carried)
        await ctx.deps.workspaces.carry(source, state.thread, state.owner_id)
        sentence = (
            "Continuing the conversation here, in a workspace of "
            f"{carried.name!r} that holds your work as you left it."
        )
    # The agent resumes in another directory either way — a new thread's own
    # workspace, or the project's — and a runtime session may be filed under
    # the one it ran in. Ink owns the move; the graph chooses when.
    agent = ctx.deps.agent(self.agent_id)
    if not agent.supports_session_fork:
        raise NotImplementedError(
            f"Agent {agent.id!r} does not support session forking"
        )
    source_session_id = (source_conversation or conversation).external_id
    async with agent.inhabit(
        thread=state.thread,
        conversation=conversation,
        owner_id=state.owner_id,
        interruption=state.interruption,
    ) as invocation:
        external_id = await agent.ink.fork_session(
            source_session_id,
            cwd=invocation.cwd,
            habitat=invocation.habitat,
            env=invocation.environment,
        )
        if source_conversation is not None:
            carry = (
                external_id is not None
                and external_id == source_conversation.external_id
            )
            await ctx.deps.conversation_manager.fork(
                source_conversation,
                conversation,
                carry_external_id=carry,
                external_id=None if carry else external_id,
            )
        elif external_id is not None and external_id != conversation.external_id:
            await ctx.deps.conversation_manager.set_external_id(
                conversation, external_id
            )
            conversation = await ctx.deps.conversation_manager.get(
                conversation.id, with_runs=False
            )
        await agent.ink.relocate_session(
            conversation.external_id,
            cwd=invocation.cwd,
            habitat=invocation.habitat,
        )
        if source_conversation is not None:
            state.thread = await ctx.deps.thread_manager.rename(
                state.thread,
                ctx.deps.thread_manager.fork_title(source_conversation, source),
            )
    if opened is not None:
        await announce_crossing(
            ctx,
            self.request.destination,
            opened,
            origin_address,
            hint,
            self.agent_id,
        )
    if (
        self.request.new_thread
        and self.request.prompt is None
        and not self.request.resume
    ):
        return await self.land(ctx)
    return await self.carry_on(ctx, sentence)

carry_on async

carry_on(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    sentence: str,
) -> React

Run the agent where the move landed: on the user's prompt, recorded there as their message, or on its own call answered by where it now is.

Source code in octomate/reflex/nodes/teleport.py
async def carry_on(
    self, ctx: GraphRunContext[ReflexState, ReflexDeps], sentence: str
) -> React:
    """Run the agent where the move landed: on the user's prompt, recorded there
    as their message, or on its own call answered by where it now is."""
    state = ctx.state
    address = state.target.address if state.target is not None else None
    if address is None:
        raise ValueError("Teleport carries on only where the move landed")
    prompt = self.request.prompt
    if prompt is None:
        # The pending call resolves into the resumed run, whichever runtime cast it.
        if self.request.tool_call_id is None:
            state.user_prompt = f"{sentence}\nCurrent channel address: {address}"
            return React()
        return React(tool_results={self.request.tool_call_id: sentence})
    channel = ctx.deps.channel(address.channel_tentacle_id)
    message = await ctx.deps.thread_manager.record_inbound(
        MessageEvent(
            tentacle_id=channel.id,
            chat_type=address.chat_type,
            chat_id=address.chat_id,
            user_id=address.user_id,
            channel_thread_id=address.channel_thread_id,
            shared=address.shared,
            self_id=channel.self_profile.channel_user_id,
            sender=state.user_profile,
            segments=[TextSegment(data={"text": prompt})],
            raw=prompt,
        )
    )
    state.source_target = state.target
    state.trigger_message = message
    await ctx.deps.load_pending_prompt(state, self.agent_id)
    return React()

land async

land(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> End[ReflexGraphResult]

End the move where it landed, for the next message there to carry on: the handoff is recorded, as a turn's end would.

Source code in octomate/reflex/nodes/teleport.py
async def land(
    self, ctx: GraphRunContext[ReflexState, ReflexDeps]
) -> End[ReflexGraphResult]:
    """End the move where it landed, for the next message there to carry on:
    the handoff is recorded, as a turn's end would."""
    state = ctx.state
    if state.decision is None or state.target is None or state.thread is None:
        raise ValueError("Teleport lands with a decision, a target and a thread")
    async with ctx.deps.runtime.finalizing(ctx):
        resolved = ctx.deps.resolve_agent(
            state.target.channel_id, state.decision.agent_id, state.decision.model
        )
        state.decision = state.decision.model_copy(
            update={"agent_id": resolved.agent, "model": resolved.model}
        )
        if state.handoff is not None:
            await state.handoff.land(ctx.deps, state.thread, state.decision)
            state.handoff = None
        return End(
            ReflexResult(
                decision=state.decision, target=state.target, outcome="handed_off"
            )
        )

bind async

bind(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    thread: Thread,
    name: str,
) -> Thread

Bind the thread landed in to the project the request names, and fork its workspace, so the resumed run starts in the project's code. The gate validated the project and the ref; a project missing here is a wiring bug. Answers the bound thread, re-read: the state's copy predates the binding, and the turn-end save reads the project off it.

Source code in octomate/reflex/nodes/teleport.py
async def bind(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    thread: Thread,
    name: str,
) -> Thread:
    """Bind the thread landed in to the project the request names, and fork
    its workspace, so the resumed run starts in the project's code. The gate
    validated the project and the ref; a project missing here is a wiring
    bug. Answers the bound thread, re-read: the state's copy predates the
    binding, and the turn-end save reads the project off it."""
    project = await ctx.deps.workspaces.projects.get(ctx.state.owner_id, name=name)
    if project is None:
        raise RuntimeError(
            f"project {name!r} vanished between the gate and the move"
        )
    workspace = await ctx.deps.workspaces.resolve(
        thread.id,
        project,
        ctx.state.owner_id,
        self.request.ref,
    )
    await ctx.deps.workspaces.prepare(workspace)
    return await ctx.deps.thread_manager.bind(thread.id, project)

DeferredResult dataclass

A turn that stopped on deferred requests, and the batch they were parked as.

Source code in octomate/reflex/state.py
@dataclass
class DeferredResult:
    """A turn that stopped on deferred requests, and the batch they were parked
    as."""

    requests: DeferredToolRequests
    target: ResponseTarget
    # The name of the run that deferred — carried for observability. `str`, not
    # `RunName`, because on a re-present it is read back from the persisted batch.
    run_name: str
    result: AgentRunResult[Any]
    batch_id: UUID7 | None = None

requests instance-attribute

requests: DeferredToolRequests

target instance-attribute

target: ResponseTarget

run_name instance-attribute

run_name: str

result instance-attribute

result: AgentRunResult[Any]

batch_id class-attribute instance-attribute

batch_id: UUID7 | None = None

ReflexDeps dataclass

The host's registries and managers a reflex run reaches through.

Source code in octomate/reflex/state.py
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
@dataclass
class ReflexDeps:
    """The host's registries and managers a reflex run reaches through."""

    tentacles: dict[str, Tentacle]
    # No defaults for the managers: a deps object must carry the host's own — the
    # ledger, the conversations, the deferred actions, the gateway's live-session
    # registry — never private ones with their own identity or state.
    thread_manager: ThreadManager
    # For the bookkeeping a finished turn owes and the agent has no part in:
    # leaving the thread's workspace somewhere losing the directory cannot cost it.
    workspaces: WorkspaceManager
    conversation_manager: ConversationManager
    action_manager: DeferredActionManager
    gateway: GatewayManager
    # The graph's end of the nerve: what the kick does, sent as impulses.
    impulses: ObjectSendStream[Impulse]
    executor: str | None = (
        None  # Owning tentacle; None when exercising graph nodes directly.
    )
    origin: ChannelAddress | None = (
        None  # Surface whose kick owns this reflex's lifetime.
    )

    @property
    def channels(self) -> dict[str, ChannelTentacle]:
        return {
            id: tentacle
            for id, tentacle in self.tentacles.items()
            if isinstance(tentacle, ChannelTentacle)
        }

    @property
    def agents(self) -> dict[str, AgentTentacle]:
        return {
            id: tentacle
            for id, tentacle in self.tentacles.items()
            if isinstance(tentacle, AgentTentacle)
        }

    def resolve_target(
        self, address: ChannelAddress, *, mode: ResponseTargetMode = "main"
    ) -> ResponseTarget:
        """Resolve registered IM policies or a direct native/ACP endpoint."""
        match self.tentacles.get(address.channel_tentacle_id):
            case ChannelTentacle() as channel:
                return ResponseTarget(
                    channel_id=channel.id,
                    address=address,
                    dm_strategy=channel.dm_strategy,
                    thread_strategy=channel.thread_strategy,
                    mode=mode,
                )
            case AgentTentacle() | AcpChannelTentacle():
                return ResponseTarget(
                    channel_id=address.channel_tentacle_id,
                    address=address,
                    dm_strategy="continuous",
                    thread_strategy="main_only",
                    mode=mode,
                )
            case None:
                raise ValueError(
                    f"unknown response endpoint {address.channel_tentacle_id!r}"
                )
            case _:
                raise ValueError(
                    f"tentacle {address.channel_tentacle_id!r} cannot receive agent responses"
                )

    async def admit(
        self, signal: AwakeSignal, *, owner_id: UUID7 | None
    ) -> Thread | None:
        """Resolve and authorize an execution target before entering the graph."""
        match signal:
            case UserMessageSignal():
                if not signal:
                    return None
                return await self.thread_manager.enter(
                    signal.address, owner_id=owner_id
                )
            case CommandSignal():
                conversation = signal.context.conversation
                if conversation is None:
                    return None
                thread: Thread | UUID7 | ThreadKey = conversation.thread_id
            case ContinueSignal() | DrivenGatewaySignal():
                thread = signal.thread_id
            case SummonSignal():
                thread = await self.thread_manager.ensure(
                    signal.destination, owner_id=owner_id
                )
            case NativeGatewaySignal(decision=TeleportDecision()):
                if signal.source is None:
                    raise ValueError("A native teleport requires its source address")
                thread = ThreadKey.model_validate(signal.source)
            case NativeGatewaySignal() | DeferredActionBatchResponse():
                return None
            case _:
                raise ValueError("Unsupported awake signal")
        if not isinstance(thread, Thread):
            found = await self.thread_manager.get(thread, with_messages=False)
            if found is None:
                raise ValueError("The task thread is unavailable")
            thread = found
        if thread.owner_id is None or thread.owner_id != owner_id:
            raise PermissionError("Only the thread owner may control this task")
        return thread

    @cached_property
    def runtime(self) -> ReflexRuntime:
        """Stateless orchestration shared by this graph's execution entries."""
        return ReflexRuntime()

    @overload
    def channel(self, target: ResponseTarget) -> ChannelTentacle: ...

    @overload
    def channel(self, target: str) -> ChannelTentacle: ...

    def channel(self, target: ResponseTarget | str) -> ChannelTentacle:
        channel_id = target.channel_id if isinstance(target, ResponseTarget) else target
        channel = self.tentacles.get(channel_id)
        if not isinstance(channel, ChannelTentacle):
            raise ValueError(f"unknown channel {channel_id!r}")
        return channel

    def agent(self, agent_id: str) -> AgentTentacle:
        agent = self.tentacles.get(agent_id)
        if not isinstance(agent, AgentTentacle):
            raise ValueError(f"unknown agent {agent_id!r}")
        return agent

    async def handoff(
        self,
        state: ReflexState,
        *,
        resume_batch_id: UUID7 | None,
        tool_results: dict[str, str] | None,
    ) -> ReflexGraphResult:
        """Continue this reflex on its selected agent through the signal nerve."""
        state.interruption.check()
        target = state.target
        source = state.source_target
        decision = state.decision
        if (
            self.origin is None
            or self.executor is None
            or state.thread is None
            or target is None
            or target.address is None
            or source is None
            or source.address is None
            or decision is None
        ):
            raise ValueError(
                "A handoff requires an owned reflex with resolved addresses and thread"
            )
        agent = self.agent(decision.agent_id)
        claim = state.handoff
        signal = ContinueSignal(
            decision=decision,
            destination=target.address,
            agent_id=claim.source_agent_tentacle_id or self.executor
            if claim
            else self.executor,
            user_profile=state.user_profile,
            source_conversation_id=claim.source_conversation_id if claim else None,
            source_run_id=claim.source_run_id if claim else None,
            source_model_message_id=claim.source_model_message_id if claim else None,
            thread_id=state.thread.id,
            origin=self.origin,
            woke_at=agent.octomate.awake_since[ThreadKey.model_validate(self.origin)],
            source_address=source.address,
            target_mode=target.mode,
            run_name=state.run_name,
            user_prompt=decision.brief or str(state.user_prompt or ""),
            source_thread_address=state.source_thread_address,
            source_thread_message_ids=state.source_thread_message_ids,
            record_handoff=claim is not None,
            resume_batch_id=resume_batch_id,
            tool_results=tool_results,
            command_request_id=state.command_request_id,
        )

        agent.nerves.signals.dispatch(AgentTopic(agent.id), signal)
        state.dispatched = True
        return ReflexResult(decision=decision, target=target, outcome="handed_off")

    @cached_property
    def gateway_agents(self) -> frozenset[str]:
        """The agents whose driven turns offer the gateway spells: each agent's own
        flag, settled at startup and read once. A turn of any other agent builds no
        session, so external callers find nothing live for it."""
        return frozenset(id for id, agent in self.agents.items() if agent.gateway)

    async def octomate_session(
        self,
        agent: AgentTentacle,
        *,
        user_profile: UserProfile,
        thread_id: UUID7 | None,
        conversation_address: ChannelAddress,
        conversation_id: uuid.UUID | None = None,
    ) -> OctomateSession | None:
        """One turn's gateway for `agent`, or None for an agent whose flag is off.

        Built from the host's own registries, every channel's and not just this
        one's: a spell that crosses lands where another channel's config decides who
        runs, so the gateway offers — and checks against — that channel's routes,
        and reads `surfaces` off it to know whether `scheme` can land. The agents
        are what the accomplice spells run; without a thread there is nowhere for
        a child conversation to live, and the gateway then does not offer them.
        """
        if agent.id not in self.gateway_agents:
            return None
        session = OctomateSession(
            channel_routes=self.available_routes,
            current_agent_id=agent.id,
            channels=self.channels,
            users=self.thread_manager.users,
            user_profile=user_profile,
            agents=self.agents,
            thread_id=thread_id,
            conversation_address=conversation_address,
            threads=self.thread_manager,
            workspaces=self.workspaces,
            impulses=self.impulses,
            nerves=agent.nerves,
        )
        if conversation_id is not None:
            session.conversation_id = conversation_id
        elif thread_id is not None:
            # The same (thread, agent) key the run resolves internally, so an
            # external runtime's tool call finds this turn's session by the
            # conversation it already knows.
            conversation = await self.conversation_manager.ensure(
                thread_id, agent_tentacle_id=agent.id, with_runs=False
            )
            session.conversation_id = conversation.id
        return session

    @property
    def available_routes(self) -> dict[str, list[AgentRoute]]:
        return self.gateway.available_routes(self.channels, self.agents)

    def resolve_agent(
        self,
        channel_id: str,
        agent_id: str | None,
        model: AgentRouteModelName | None,
    ) -> AgentModelConfig:
        """Resolve a channel route, or an explicitly selected executor without a channel."""
        channel = self.channels.get(channel_id)
        if channel is not None:
            agent_ids = channel.agent_ids
        elif agent_id is not None:
            agent_ids = [agent_id]
        else:
            raise ValueError(f"unknown channel {channel_id!r}")
        if agent_id is None:
            agent_id = agent_ids[0]
        if agent_id not in agent_ids:
            raise ValueError(
                f"agent {agent_id!r} is not bound to channel {channel_id!r}"
            )

        agent = self.agent(agent_id)
        if model is None:
            return AgentModelConfig(agent=agent_id, model=agent.resolve_model())
        served = agent.served_model(model)
        if served is None:
            raise ValueError(f"agent {agent_id!r} does not serve model {model!r}")
        return AgentModelConfig(agent=agent_id, model=served)

    async def render_chat(
        self, messages: list[ThreadMessage], *, ceiling: int = 0
    ) -> str:
        """The ledger rows as one transcript: who spoke, under which identities, and
        the `#msg:<id>` handle a brief would cite them by.

        Each message is its segments, as they render themselves — the same body an
        inbound event shows. `message_text` would be the shorter route and the wrong
        one: it keeps only text and markdown, so a message that was a picture or a
        quoted reply arrives as nothing at all.

        `ceiling` cuts each message. It is 0 for the messages a turn must answer —
        those are the work — and set for the chat behind them, where one pasted log
        would otherwise be the whole slice.
        """
        parts: list[str] = []
        for message in messages:
            if message.kind != "message":
                continue
            text = "\n".join(str(segment) for segment in message.segments)
            if not text:
                continue
            if ceiling and len(text) > ceiling:
                text = f"{text[:ceiling]}…"
            sender = await message.sender
            display_name = (
                (sender.name or sender.nickname or "anonymous")
                if sender is not None
                else "anonymous"
            )
            owner = sender.user.peek() if sender is not None else None
            ids = (
                f"{message.user_id}, user:{owner.username}"
                if owner is not None
                else message.user_id
            )
            platform_id = (
                f" #msg:{message.platform_message_id}"
                if message.platform_message_id
                else ""
            )
            parts.append(f"{display_name} ({ids}){platform_id}:\n{text}")
        return "\n\n".join(parts)

    async def report(self, state: ReflexState, error: Exception) -> None:
        """Publish that the turn failed, on the thread it came from. A turn that
        failed before it knew its source has nobody to tell."""
        source = state.source_target.address if state.source_target else None
        if source is None:
            return
        trace_id = format(trace.get_current_span().get_span_context().trace_id, "032x")
        failure = RunErrorEvent(message=str(error), trace_id=trace_id)
        await self.impulses.send(Impulse(failure, source))

    async def carry(
        self,
        address: ChannelAddress,
        stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
    ) -> None:
        """Send a run's stream on the nerve at `address` as wire events, item by
        item, until it ends."""
        async for item in stream:
            wire = to_wire(item)
            if wire is not None:
                await self.impulses.send(Impulse(wire, address))

    async def record_move(
        self,
        address: ChannelAddress,
        text: str,
        *,
        agent_tentacle_id: str,
        platform_message_id: str | None = None,
    ) -> ThreadMessage:
        """Write the line a move leaves behind to the ledger of the chat it left.

        A person already sees it — the channel posted it, and a thread opened here
        hangs off it. The turn that comes next does not: a chat room's recap is built
        from the ledger, and a move nobody recorded leaves a chat in which the work
        simply stops. An agent reading that answers what was carried away ten minutes
        ago.

        The row carries the opener's own platform id, so the ledger and the platform
        name the same message rather than two; a line still to be posted gets its id
        from the channel that posts it.
        """
        return await self.thread_manager.record_outbound(
            address,
            agent_tentacle_id=agent_tentacle_id,
            segments=[MarkdownSegment(data={"text": text})],
            sender=self.channel(address.channel_tentacle_id).self_profile,
            platform_message_id=platform_message_id,
            message_text=text,
            raw=text,
        )

    async def load_pending_prompt(
        self,
        state: ReflexState,
        active_agent_id: str,
        *,
        include_recap: bool = True,
    ) -> None:
        source_target = state.source_target
        if (
            state.thread is None
            or state.trigger_message is None
            or source_target is None
            or source_target.address is None
        ):
            return
        # Tasks consume their pending ledger messages; a new main-chat task takes
        # its triggering request and receives earlier chat through the recap.
        messages = await self.thread_manager.pending_prompt_messages(
            state.thread,
            state.trigger_message.id,
            active_agent_id,
            trigger_only=source_target.starts_task,
        )
        if not messages:
            return
        if not source_target.starts_task:
            state.source_thread_address = source_target.address
            state.source_thread_message_ids = [message.id for message in messages]

        asked = await self.render_chat(messages)
        if not asked:
            return
        recap = await self.chat_recap(state, messages[0]) if include_recap else ""
        # The messages the turn must answer are the body, unmarked. What was said
        # before them is the system's addition and stands in a tag.
        state.user_prompt = f"{recap}\n\n{asked}" if recap else asked

    async def chat_recap(self, state: ReflexState, earliest: ThreadMessage) -> str:
        """What was said in this chat room before the messages the turn must answer.

        Only a new task invoked from a main chat needs a preceding window.
        Continuous DMs and platform subthreads consume all pending messages as
        input, without a separate recap window.

        Read the main ledger before opening the task destination. The channel
        bounds how many human messages and how much of each to include.
        """
        thread = state.thread
        source_target = state.source_target
        if thread is None or source_target is None or not source_target.starts_task:
            return ""
        recap = self.channel(source_target).config.recap
        if not recap.messages:
            return ""
        messages = await self.thread_manager.chat_messages_before(
            thread.parent_thread_id or thread.id,
            earliest.id,
            limit=recap.messages,
            actor_kind="human",
        )
        rendered = await self.render_chat(messages, ceiling=recap.characters)
        return tagged("chat_recap", f"{RECAP_HEADER}\n\n{rendered}" if rendered else "")

tentacles instance-attribute

tentacles: dict[str, Tentacle]

thread_manager instance-attribute

thread_manager: ThreadManager

workspaces instance-attribute

workspaces: WorkspaceManager

conversation_manager instance-attribute

conversation_manager: ConversationManager

action_manager instance-attribute

action_manager: DeferredActionManager

gateway instance-attribute

gateway: GatewayManager

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

executor class-attribute instance-attribute

executor: str | None = None

origin class-attribute instance-attribute

origin: ChannelAddress | None = None

channels property

channels: dict[str, ChannelTentacle]

agents property

agents: dict[str, AgentTentacle]

runtime cached property

runtime: ReflexRuntime

Stateless orchestration shared by this graph's execution entries.

gateway_agents cached property

gateway_agents: frozenset[str]

The agents whose driven turns offer the gateway spells: each agent's own flag, settled at startup and read once. A turn of any other agent builds no session, so external callers find nothing live for it.

available_routes property

available_routes: dict[str, list[AgentRoute]]

resolve_target

resolve_target(
    address: ChannelAddress,
    *,
    mode: ResponseTargetMode = "main",
) -> ResponseTarget

Resolve registered IM policies or a direct native/ACP endpoint.

Source code in octomate/reflex/state.py
def resolve_target(
    self, address: ChannelAddress, *, mode: ResponseTargetMode = "main"
) -> ResponseTarget:
    """Resolve registered IM policies or a direct native/ACP endpoint."""
    match self.tentacles.get(address.channel_tentacle_id):
        case ChannelTentacle() as channel:
            return ResponseTarget(
                channel_id=channel.id,
                address=address,
                dm_strategy=channel.dm_strategy,
                thread_strategy=channel.thread_strategy,
                mode=mode,
            )
        case AgentTentacle() | AcpChannelTentacle():
            return ResponseTarget(
                channel_id=address.channel_tentacle_id,
                address=address,
                dm_strategy="continuous",
                thread_strategy="main_only",
                mode=mode,
            )
        case None:
            raise ValueError(
                f"unknown response endpoint {address.channel_tentacle_id!r}"
            )
        case _:
            raise ValueError(
                f"tentacle {address.channel_tentacle_id!r} cannot receive agent responses"
            )

admit async

admit(
    signal: AwakeSignal, *, owner_id: UUID7 | None
) -> Thread | None

Resolve and authorize an execution target before entering the graph.

Source code in octomate/reflex/state.py
async def admit(
    self, signal: AwakeSignal, *, owner_id: UUID7 | None
) -> Thread | None:
    """Resolve and authorize an execution target before entering the graph."""
    match signal:
        case UserMessageSignal():
            if not signal:
                return None
            return await self.thread_manager.enter(
                signal.address, owner_id=owner_id
            )
        case CommandSignal():
            conversation = signal.context.conversation
            if conversation is None:
                return None
            thread: Thread | UUID7 | ThreadKey = conversation.thread_id
        case ContinueSignal() | DrivenGatewaySignal():
            thread = signal.thread_id
        case SummonSignal():
            thread = await self.thread_manager.ensure(
                signal.destination, owner_id=owner_id
            )
        case NativeGatewaySignal(decision=TeleportDecision()):
            if signal.source is None:
                raise ValueError("A native teleport requires its source address")
            thread = ThreadKey.model_validate(signal.source)
        case NativeGatewaySignal() | DeferredActionBatchResponse():
            return None
        case _:
            raise ValueError("Unsupported awake signal")
    if not isinstance(thread, Thread):
        found = await self.thread_manager.get(thread, with_messages=False)
        if found is None:
            raise ValueError("The task thread is unavailable")
        thread = found
    if thread.owner_id is None or thread.owner_id != owner_id:
        raise PermissionError("Only the thread owner may control this task")
    return thread

channel

channel(target: ResponseTarget) -> ChannelTentacle
channel(target: str) -> ChannelTentacle
channel(target: ResponseTarget | str) -> ChannelTentacle
Source code in octomate/reflex/state.py
def channel(self, target: ResponseTarget | str) -> ChannelTentacle:
    channel_id = target.channel_id if isinstance(target, ResponseTarget) else target
    channel = self.tentacles.get(channel_id)
    if not isinstance(channel, ChannelTentacle):
        raise ValueError(f"unknown channel {channel_id!r}")
    return channel

agent

agent(agent_id: str) -> AgentTentacle
Source code in octomate/reflex/state.py
def agent(self, agent_id: str) -> AgentTentacle:
    agent = self.tentacles.get(agent_id)
    if not isinstance(agent, AgentTentacle):
        raise ValueError(f"unknown agent {agent_id!r}")
    return agent

handoff async

handoff(
    state: ReflexState,
    *,
    resume_batch_id: UUID7 | None,
    tool_results: dict[str, str] | None,
) -> ReflexGraphResult

Continue this reflex on its selected agent through the signal nerve.

Source code in octomate/reflex/state.py
async def handoff(
    self,
    state: ReflexState,
    *,
    resume_batch_id: UUID7 | None,
    tool_results: dict[str, str] | None,
) -> ReflexGraphResult:
    """Continue this reflex on its selected agent through the signal nerve."""
    state.interruption.check()
    target = state.target
    source = state.source_target
    decision = state.decision
    if (
        self.origin is None
        or self.executor is None
        or state.thread is None
        or target is None
        or target.address is None
        or source is None
        or source.address is None
        or decision is None
    ):
        raise ValueError(
            "A handoff requires an owned reflex with resolved addresses and thread"
        )
    agent = self.agent(decision.agent_id)
    claim = state.handoff
    signal = ContinueSignal(
        decision=decision,
        destination=target.address,
        agent_id=claim.source_agent_tentacle_id or self.executor
        if claim
        else self.executor,
        user_profile=state.user_profile,
        source_conversation_id=claim.source_conversation_id if claim else None,
        source_run_id=claim.source_run_id if claim else None,
        source_model_message_id=claim.source_model_message_id if claim else None,
        thread_id=state.thread.id,
        origin=self.origin,
        woke_at=agent.octomate.awake_since[ThreadKey.model_validate(self.origin)],
        source_address=source.address,
        target_mode=target.mode,
        run_name=state.run_name,
        user_prompt=decision.brief or str(state.user_prompt or ""),
        source_thread_address=state.source_thread_address,
        source_thread_message_ids=state.source_thread_message_ids,
        record_handoff=claim is not None,
        resume_batch_id=resume_batch_id,
        tool_results=tool_results,
        command_request_id=state.command_request_id,
    )

    agent.nerves.signals.dispatch(AgentTopic(agent.id), signal)
    state.dispatched = True
    return ReflexResult(decision=decision, target=target, outcome="handed_off")

octomate_session async

octomate_session(
    agent: AgentTentacle,
    *,
    user_profile: UserProfile,
    thread_id: UUID7 | None,
    conversation_address: ChannelAddress,
    conversation_id: UUID | None = None,
) -> OctomateSession | None

One turn's gateway for agent, or None for an agent whose flag is off.

Built from the host's own registries, every channel's and not just this one's: a spell that crosses lands where another channel's config decides who runs, so the gateway offers — and checks against — that channel's routes, and reads surfaces off it to know whether scheme can land. The agents are what the accomplice spells run; without a thread there is nowhere for a child conversation to live, and the gateway then does not offer them.

Source code in octomate/reflex/state.py
async def octomate_session(
    self,
    agent: AgentTentacle,
    *,
    user_profile: UserProfile,
    thread_id: UUID7 | None,
    conversation_address: ChannelAddress,
    conversation_id: uuid.UUID | None = None,
) -> OctomateSession | None:
    """One turn's gateway for `agent`, or None for an agent whose flag is off.

    Built from the host's own registries, every channel's and not just this
    one's: a spell that crosses lands where another channel's config decides who
    runs, so the gateway offers — and checks against — that channel's routes,
    and reads `surfaces` off it to know whether `scheme` can land. The agents
    are what the accomplice spells run; without a thread there is nowhere for
    a child conversation to live, and the gateway then does not offer them.
    """
    if agent.id not in self.gateway_agents:
        return None
    session = OctomateSession(
        channel_routes=self.available_routes,
        current_agent_id=agent.id,
        channels=self.channels,
        users=self.thread_manager.users,
        user_profile=user_profile,
        agents=self.agents,
        thread_id=thread_id,
        conversation_address=conversation_address,
        threads=self.thread_manager,
        workspaces=self.workspaces,
        impulses=self.impulses,
        nerves=agent.nerves,
    )
    if conversation_id is not None:
        session.conversation_id = conversation_id
    elif thread_id is not None:
        # The same (thread, agent) key the run resolves internally, so an
        # external runtime's tool call finds this turn's session by the
        # conversation it already knows.
        conversation = await self.conversation_manager.ensure(
            thread_id, agent_tentacle_id=agent.id, with_runs=False
        )
        session.conversation_id = conversation.id
    return session

resolve_agent

resolve_agent(
    channel_id: str,
    agent_id: str | None,
    model: AgentRouteModelName | None,
) -> AgentModelConfig

Resolve a channel route, or an explicitly selected executor without a channel.

Source code in octomate/reflex/state.py
def resolve_agent(
    self,
    channel_id: str,
    agent_id: str | None,
    model: AgentRouteModelName | None,
) -> AgentModelConfig:
    """Resolve a channel route, or an explicitly selected executor without a channel."""
    channel = self.channels.get(channel_id)
    if channel is not None:
        agent_ids = channel.agent_ids
    elif agent_id is not None:
        agent_ids = [agent_id]
    else:
        raise ValueError(f"unknown channel {channel_id!r}")
    if agent_id is None:
        agent_id = agent_ids[0]
    if agent_id not in agent_ids:
        raise ValueError(
            f"agent {agent_id!r} is not bound to channel {channel_id!r}"
        )

    agent = self.agent(agent_id)
    if model is None:
        return AgentModelConfig(agent=agent_id, model=agent.resolve_model())
    served = agent.served_model(model)
    if served is None:
        raise ValueError(f"agent {agent_id!r} does not serve model {model!r}")
    return AgentModelConfig(agent=agent_id, model=served)

render_chat async

render_chat(
    messages: list[ThreadMessage], *, ceiling: int = 0
) -> str

The ledger rows as one transcript: who spoke, under which identities, and the #msg:<id> handle a brief would cite them by.

Each message is its segments, as they render themselves — the same body an inbound event shows. message_text would be the shorter route and the wrong one: it keeps only text and markdown, so a message that was a picture or a quoted reply arrives as nothing at all.

ceiling cuts each message. It is 0 for the messages a turn must answer — those are the work — and set for the chat behind them, where one pasted log would otherwise be the whole slice.

Source code in octomate/reflex/state.py
async def render_chat(
    self, messages: list[ThreadMessage], *, ceiling: int = 0
) -> str:
    """The ledger rows as one transcript: who spoke, under which identities, and
    the `#msg:<id>` handle a brief would cite them by.

    Each message is its segments, as they render themselves — the same body an
    inbound event shows. `message_text` would be the shorter route and the wrong
    one: it keeps only text and markdown, so a message that was a picture or a
    quoted reply arrives as nothing at all.

    `ceiling` cuts each message. It is 0 for the messages a turn must answer —
    those are the work — and set for the chat behind them, where one pasted log
    would otherwise be the whole slice.
    """
    parts: list[str] = []
    for message in messages:
        if message.kind != "message":
            continue
        text = "\n".join(str(segment) for segment in message.segments)
        if not text:
            continue
        if ceiling and len(text) > ceiling:
            text = f"{text[:ceiling]}…"
        sender = await message.sender
        display_name = (
            (sender.name or sender.nickname or "anonymous")
            if sender is not None
            else "anonymous"
        )
        owner = sender.user.peek() if sender is not None else None
        ids = (
            f"{message.user_id}, user:{owner.username}"
            if owner is not None
            else message.user_id
        )
        platform_id = (
            f" #msg:{message.platform_message_id}"
            if message.platform_message_id
            else ""
        )
        parts.append(f"{display_name} ({ids}){platform_id}:\n{text}")
    return "\n\n".join(parts)

report async

report(state: ReflexState, error: Exception) -> None

Publish that the turn failed, on the thread it came from. A turn that failed before it knew its source has nobody to tell.

Source code in octomate/reflex/state.py
async def report(self, state: ReflexState, error: Exception) -> None:
    """Publish that the turn failed, on the thread it came from. A turn that
    failed before it knew its source has nobody to tell."""
    source = state.source_target.address if state.source_target else None
    if source is None:
        return
    trace_id = format(trace.get_current_span().get_span_context().trace_id, "032x")
    failure = RunErrorEvent(message=str(error), trace_id=trace_id)
    await self.impulses.send(Impulse(failure, source))

carry async

carry(
    address: ChannelAddress,
    stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
) -> None

Send a run's stream on the nerve at address as wire events, item by item, until it ends.

Source code in octomate/reflex/state.py
async def carry(
    self,
    address: ChannelAddress,
    stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
) -> None:
    """Send a run's stream on the nerve at `address` as wire events, item by
    item, until it ends."""
    async for item in stream:
        wire = to_wire(item)
        if wire is not None:
            await self.impulses.send(Impulse(wire, address))

record_move async

record_move(
    address: ChannelAddress,
    text: str,
    *,
    agent_tentacle_id: str,
    platform_message_id: str | None = None,
) -> ThreadMessage

Write the line a move leaves behind to the ledger of the chat it left.

A person already sees it — the channel posted it, and a thread opened here hangs off it. The turn that comes next does not: a chat room's recap is built from the ledger, and a move nobody recorded leaves a chat in which the work simply stops. An agent reading that answers what was carried away ten minutes ago.

The row carries the opener's own platform id, so the ledger and the platform name the same message rather than two; a line still to be posted gets its id from the channel that posts it.

Source code in octomate/reflex/state.py
async def record_move(
    self,
    address: ChannelAddress,
    text: str,
    *,
    agent_tentacle_id: str,
    platform_message_id: str | None = None,
) -> ThreadMessage:
    """Write the line a move leaves behind to the ledger of the chat it left.

    A person already sees it — the channel posted it, and a thread opened here
    hangs off it. The turn that comes next does not: a chat room's recap is built
    from the ledger, and a move nobody recorded leaves a chat in which the work
    simply stops. An agent reading that answers what was carried away ten minutes
    ago.

    The row carries the opener's own platform id, so the ledger and the platform
    name the same message rather than two; a line still to be posted gets its id
    from the channel that posts it.
    """
    return await self.thread_manager.record_outbound(
        address,
        agent_tentacle_id=agent_tentacle_id,
        segments=[MarkdownSegment(data={"text": text})],
        sender=self.channel(address.channel_tentacle_id).self_profile,
        platform_message_id=platform_message_id,
        message_text=text,
        raw=text,
    )

load_pending_prompt async

load_pending_prompt(
    state: ReflexState,
    active_agent_id: str,
    *,
    include_recap: bool = True,
) -> None
Source code in octomate/reflex/state.py
async def load_pending_prompt(
    self,
    state: ReflexState,
    active_agent_id: str,
    *,
    include_recap: bool = True,
) -> None:
    source_target = state.source_target
    if (
        state.thread is None
        or state.trigger_message is None
        or source_target is None
        or source_target.address is None
    ):
        return
    # Tasks consume their pending ledger messages; a new main-chat task takes
    # its triggering request and receives earlier chat through the recap.
    messages = await self.thread_manager.pending_prompt_messages(
        state.thread,
        state.trigger_message.id,
        active_agent_id,
        trigger_only=source_target.starts_task,
    )
    if not messages:
        return
    if not source_target.starts_task:
        state.source_thread_address = source_target.address
        state.source_thread_message_ids = [message.id for message in messages]

    asked = await self.render_chat(messages)
    if not asked:
        return
    recap = await self.chat_recap(state, messages[0]) if include_recap else ""
    # The messages the turn must answer are the body, unmarked. What was said
    # before them is the system's addition and stands in a tag.
    state.user_prompt = f"{recap}\n\n{asked}" if recap else asked

chat_recap async

chat_recap(
    state: ReflexState, earliest: ThreadMessage
) -> str

What was said in this chat room before the messages the turn must answer.

Only a new task invoked from a main chat needs a preceding window. Continuous DMs and platform subthreads consume all pending messages as input, without a separate recap window.

Read the main ledger before opening the task destination. The channel bounds how many human messages and how much of each to include.

Source code in octomate/reflex/state.py
async def chat_recap(self, state: ReflexState, earliest: ThreadMessage) -> str:
    """What was said in this chat room before the messages the turn must answer.

    Only a new task invoked from a main chat needs a preceding window.
    Continuous DMs and platform subthreads consume all pending messages as
    input, without a separate recap window.

    Read the main ledger before opening the task destination. The channel
    bounds how many human messages and how much of each to include.
    """
    thread = state.thread
    source_target = state.source_target
    if thread is None or source_target is None or not source_target.starts_task:
        return ""
    recap = self.channel(source_target).config.recap
    if not recap.messages:
        return ""
    messages = await self.thread_manager.chat_messages_before(
        thread.parent_thread_id or thread.id,
        earliest.id,
        limit=recap.messages,
        actor_kind="human",
    )
    rendered = await self.render_chat(messages, ceiling=recap.characters)
    return tagged("chat_recap", f"{RECAP_HEADER}\n\n{rendered}" if rendered else "")

ReflexResult dataclass

A finished turn: the decision it ran on, where it answered, and the agent's result.

Source code in octomate/reflex/state.py
@dataclass
class ReflexResult:
    """A finished turn: the decision it ran on, where it answered, and the agent's
    result."""

    decision: SummonDecision | None
    target: ResponseTarget
    result: AgentRunResult[ChannelOutput] | None = None
    outcome: Literal["completed", "handed_off"] = "completed"

decision instance-attribute

decision: SummonDecision | None

target instance-attribute

target: ResponseTarget

result class-attribute instance-attribute

result: AgentRunResult[ChannelOutput] | None = None

outcome class-attribute instance-attribute

outcome: Literal['completed', 'handed_off'] = 'completed'

ReflexState dataclass

All run-wide context for one reflex graph run.

Admission resolves the execution thread before the graph starts. Nodes read that thread from state and carry only transition discriminators.

Source code in octomate/reflex/state.py
@dataclass
class ReflexState:
    """All run-wide context for one reflex graph run.

    Admission resolves the execution thread before the graph starts. Nodes read
    that thread from state and carry only transition discriminators.
    """

    user_profile: UserProfile  # The caller whose identity this run carries.
    owner_id: UUID7 = field(
        init=False, repr=False
    )  # Set from a validated Gateway signal or session before an owned operation.

    source_target: ResponseTarget | None = None
    target: ResponseTarget | None = None
    run_name: RunName = "react"
    decision: SummonDecision | None = None
    selection: AgentRouteKey | None = None  # Selected agent and model.
    conversation_id: uuid.UUID | None = None  # Current invocation's conversation.
    targets: dict[str, ResponseTarget] = field(default_factory=dict)
    summon_routes: list[AgentRoute] = field(default_factory=list)
    thread: Thread | None = None
    trigger_message: ThreadMessage | None = None  # Persisted incoming message.
    source_thread_address: ChannelAddress | None = None
    source_thread_message_ids: list[UUID7] = field(default_factory=list)
    # The handoff the next React records when it lands, or None when it records
    # none.
    handoff: PendingHandoff | None = None
    user_prompt: str | Sequence[UserContent] | None = None
    command_request_id: UUID7 | None = (
        None  # Command whose completion this reflex owes.
    )
    dispatched: bool = False  # A receiving agent now owns the rest of this reflex.
    interruption: Interruption = field(default_factory=Interruption)

    @property
    def execution_thread(self) -> Thread:
        """The admitted thread for an operation that requires an existing task."""
        if self.thread is None:
            raise ValueError("This operation requires an admitted execution thread")
        return self.thread

user_profile instance-attribute

user_profile: UserProfile

owner_id class-attribute instance-attribute

owner_id: UUID7 = field(init=False, repr=False)

source_target class-attribute instance-attribute

source_target: ResponseTarget | None = None

target class-attribute instance-attribute

target: ResponseTarget | None = None

run_name class-attribute instance-attribute

run_name: RunName = 'react'

decision class-attribute instance-attribute

decision: SummonDecision | None = None

selection class-attribute instance-attribute

selection: AgentRouteKey | None = None

conversation_id class-attribute instance-attribute

conversation_id: UUID | None = None

targets class-attribute instance-attribute

targets: dict[str, ResponseTarget] = field(
    default_factory=dict
)

summon_routes class-attribute instance-attribute

summon_routes: list[AgentRoute] = field(
    default_factory=list
)

thread class-attribute instance-attribute

thread: Thread | None = None

trigger_message class-attribute instance-attribute

trigger_message: ThreadMessage | None = None

source_thread_address class-attribute instance-attribute

source_thread_address: ChannelAddress | None = None

source_thread_message_ids class-attribute instance-attribute

source_thread_message_ids: list[UUID7] = field(
    default_factory=list
)

handoff class-attribute instance-attribute

handoff: PendingHandoff | None = None

user_prompt class-attribute instance-attribute

user_prompt: str | Sequence[UserContent] | None = None

command_request_id class-attribute instance-attribute

command_request_id: UUID7 | None = None

dispatched class-attribute instance-attribute

dispatched: bool = False

interruption class-attribute instance-attribute

interruption: Interruption = field(
    default_factory=Interruption
)

execution_thread property

execution_thread: Thread

The admitted thread for an operation that requires an existing task.

ResponseTarget dataclass

Where a turn answers: the channel, the address on it, and how the reply is placed.

Source code in octomate/reflex/state.py
@dataclass(frozen=True)
class ResponseTarget:
    """Where a turn answers: the channel, the address on it, and how the reply is
    placed."""

    channel_id: str
    address: ChannelAddress | None = None
    dm_strategy: DMStrategy = "continuous"  # How a top-level DM starts work.
    # Routing only — how an inbound message is handled (`Route`). What this
    # channel can actually open lives on the channel itself, as `surfaces`.
    thread_strategy: ThreadStrategy = "main_only"
    mode: ResponseTargetMode = "main"

    @property
    def starts_task(self) -> bool:
        """Main-chat calls open tasks; continuous DMs reuse their conversation."""
        return self.address is not None and (
            self.address.chat_type == "group"
            or (self.address.chat_type == "dm" and self.dm_strategy == "thread")
        )

    def __str__(self) -> str:
        chat_type = self.address.chat_type if self.address else "unresolved"
        return (
            f"- {self.channel_id}: chat_type={chat_type}, mode={self.mode}, "
            f"dm_strategy={self.dm_strategy}, thread_strategy={self.thread_strategy}"
        )

channel_id instance-attribute

channel_id: str

address class-attribute instance-attribute

address: ChannelAddress | None = None

dm_strategy class-attribute instance-attribute

dm_strategy: DMStrategy = 'continuous'

thread_strategy class-attribute instance-attribute

thread_strategy: ThreadStrategy = 'main_only'

mode class-attribute instance-attribute

mode: ResponseTargetMode = 'main'

starts_task property

starts_task: bool

Main-chat calls open tasks; continuous DMs reuse their conversation.

SummonDecision pydantic-model

Bases: BaseModel

The selected agent and self-contained brief for a run or handoff.

Fields:

Source code in octomate/schemas/triage.py
class SummonDecision(BaseModel):
    """The selected agent and self-contained brief for a run or handoff."""

    action: Literal["summon"] = "summon"
    reason: str
    agent_id: str
    model: AgentRouteModelName | None = Field(
        description="Selected model, or null to use the harness's native default."
    )
    effort: str | None = None
    hint: str
    brief: str = Field(
        max_length=8_000,
        description="The receiver's whole opening prompt, refused over the cap rather "
        "than trimmed: what it leaves out, the receiver reads back through the "
        "handoff. Eight thousand characters is roughly two thousand tokens — the "
        "size a distilled handoff runs to, and well short of a pasted transcript.",
    )

    @property
    def key(self) -> AgentRouteKey:
        return AgentRouteKey(agent_id=self.agent_id, model=self.model)

action pydantic-field

action: Literal['summon'] = 'summon'

reason pydantic-field

reason: str

agent_id pydantic-field

agent_id: str

model pydantic-field

model: AgentRouteModelName | None

Selected model, or null to use the harness's native default.

effort pydantic-field

effort: str | None = None

hint pydantic-field

hint: str

brief pydantic-field

brief: str

The receiver's whole opening prompt, refused over the cap rather than trimmed: what it leaves out, the receiver reads back through the handoff. Eight thousand characters is roughly two thousand tokens — the size a distilled handoff runs to, and well short of a pasted transcript.

key property

key: AgentRouteKey

build_reflex_graph

build_reflex_graph(
    entry: type[ReflexEntryT] = Awake,
) -> Graph[
    ReflexState, ReflexDeps, ReflexEntryT, ReflexGraphResult
]

Wire the reflex nodes into a runnable graph, entered at entry.

Every edge comes from the nodes' own run return annotations, so the shape stays declared where the transition is written rather than in a second list here. A graph declares the one node it is entered at: a signal wakes the whole reflex, so that is Awake, and only a test wires the same nodes with a different door to exercise a stretch of them on its own.

Source code in octomate/reflex/graph.py
def build_reflex_graph(
    entry: type[ReflexEntryT] = Awake,
) -> Graph[ReflexState, ReflexDeps, ReflexEntryT, ReflexGraphResult]:
    """Wire the reflex nodes into a runnable graph, entered at `entry`.

    Every edge comes from the nodes' own `run` return annotations, so the shape
    stays declared where the transition is written rather than in a second list
    here. A graph declares the one node it is entered at: a signal wakes the
    whole reflex, so that is `Awake`, and only a test wires the same nodes with
    a different door to exercise a stretch of them on its own.
    """
    builder = GraphBuilder(
        name="reflex",
        state_type=ReflexState,
        deps_type=ReflexDeps,
        input_type=entry,
        # `TypeExpression` is pydantic-graph's stand-in for a union in a
        # `type[...]` position — the result may also be a direct command outcome.
        output_type=TypeExpression[ReflexGraphResult],
    )
    builder.add(
        builder.edge_from(builder.start_node).to(entry),
        builder.node(Awake),
        builder.node(Command),
        builder.node(Route),
        builder.node(Summon),
        builder.node(React),
        builder.node(Scheme),
        builder.node(Teleport),
        builder.node(ResumeDeferred),
    )
    # Entering anywhere but the top necessarily strands the nodes above it, so the
    # reachability check only means something for the real entry.
    return builder.build(validate_graph_structure=entry is Awake)

run_reflex async

run_reflex(
    signal: AwakeSignal,
    *,
    origin: ChannelAddress,
    state: ReflexState,
    deps: ReflexDeps,
) -> ReflexGraphResult

Wake the reflex with signal, and say so on the nerve before anything else. A failure is reported where the kick came from, and the reflex falls asleep last whatever happened.

Source code in octomate/reflex/graph.py
async def run_reflex(
    signal: AwakeSignal, *, origin: ChannelAddress, state: ReflexState, deps: ReflexDeps
) -> ReflexGraphResult:
    """Wake the reflex with `signal`, and say so on the nerve before anything
    else. A failure is reported where the kick came from, and the reflex falls
    asleep last whatever happened."""
    continuation = isinstance(signal, ContinueSignal)
    woke_at = (
        signal.woke_at
        if isinstance(signal, ContinueSignal) and signal.woke_at is not None
        else now_utc()
    )
    if isinstance(signal, CommandSignal):
        state.command_request_id = signal.request_id
    outcome: KickOutcome = "failed"
    command_outcome: CommandOutcome | None = None
    try:
        if not continuation:
            await deps.impulses.send(
                Impulse(ReflexAwakeEvent(request_id=state.command_request_id), origin)
            )
            await deps.impulses.send(
                Impulse(ReflexPhaseChangedEvent(phase="preparing"), origin)
            )
        state.interruption.check()
        state.thread = await deps.admit(signal, owner_id=state.user_profile.user_id)
        result = await reflex_graph.run(
            inputs=Awake(signal=signal), state=state, deps=deps
        )
        state.interruption.check()
        if isinstance(result, DeferredResult):
            outcome = "deferred"
        elif isinstance(result, ReflexResult):
            outcome = result.outcome
        elif not isinstance(result, CommandError):
            outcome = "completed"
        if not state.dispatched and state.command_request_id is not None:
            command_outcome = (
                result
                if isinstance(result, CommandError | CommandResult)
                else CommandResult()
            )
        return result
    except RunInterrupted:
        outcome = "cancelled"
        interrupted = CommandError(status="failed", message="Run interrupted.")
        if state.command_request_id is not None:
            command_outcome = interrupted
        return interrupted
    except asyncio.CancelledError:
        outcome = "cancelled"
        raise
    except Exception as error:
        await deps.report(state, error)
        raise
    finally:
        if not state.dispatched:
            try:
                # Filed before the reflex is heard asleep, so whoever reads the thread
                # again on that word finds how long the kick took.
                if state.thread is not None:
                    await deps.thread_manager.record_kick(
                        state.thread, woke_at=woke_at, outcome=outcome
                    )
                if command_outcome is not None:
                    await deps.impulses.send(
                        Impulse(
                            CommandOutcomeEvent(
                                outcome=command_outcome,
                                request_id=state.command_request_id,
                            ),
                            origin,
                        )
                    )
            finally:
                if deps.executor is not None:
                    deps.agent(deps.executor).octomate.awake_since.pop(
                        ThreadKey.model_validate(origin), None
                    )
                await deps.impulses.send(
                    Impulse(
                        ReflexAsleepEvent(
                            outcome=outcome, request_id=state.command_request_id
                        ),
                        state.target.address
                        if state.target and state.target.address
                        else origin,
                    )
                )

octomate.reflex.state

Graph state, dependencies and runtime orchestration.

The state and deps objects a node is handed, the runtime shared by execution entries, and the result variants a run ends in.

logger module-attribute

logger = logging.getLogger(__name__)

RECAP_HEADER module-attribute

RECAP_HEADER = "Recent messages in this chat. They are context and have been answered already — do not reply to them."

ReflexEntryT module-attribute

ReflexEntryT = TypeVar(
    "ReflexEntryT",
    bound="BaseNode[ReflexState, ReflexDeps, ReflexGraphResult]",
)

ReflexGraphResult

ReflexGraphResult = (
    ReflexResult | DeferredResult | CommandOutcome
)

ResponseTarget dataclass

Where a turn answers: the channel, the address on it, and how the reply is placed.

Source code in octomate/reflex/state.py
@dataclass(frozen=True)
class ResponseTarget:
    """Where a turn answers: the channel, the address on it, and how the reply is
    placed."""

    channel_id: str
    address: ChannelAddress | None = None
    dm_strategy: DMStrategy = "continuous"  # How a top-level DM starts work.
    # Routing only — how an inbound message is handled (`Route`). What this
    # channel can actually open lives on the channel itself, as `surfaces`.
    thread_strategy: ThreadStrategy = "main_only"
    mode: ResponseTargetMode = "main"

    @property
    def starts_task(self) -> bool:
        """Main-chat calls open tasks; continuous DMs reuse their conversation."""
        return self.address is not None and (
            self.address.chat_type == "group"
            or (self.address.chat_type == "dm" and self.dm_strategy == "thread")
        )

    def __str__(self) -> str:
        chat_type = self.address.chat_type if self.address else "unresolved"
        return (
            f"- {self.channel_id}: chat_type={chat_type}, mode={self.mode}, "
            f"dm_strategy={self.dm_strategy}, thread_strategy={self.thread_strategy}"
        )

channel_id instance-attribute

channel_id: str

address class-attribute instance-attribute

address: ChannelAddress | None = None

dm_strategy class-attribute instance-attribute

dm_strategy: DMStrategy = 'continuous'

thread_strategy class-attribute instance-attribute

thread_strategy: ThreadStrategy = 'main_only'

mode class-attribute instance-attribute

mode: ResponseTargetMode = 'main'

starts_task property

starts_task: bool

Main-chat calls open tasks; continuous DMs reuse their conversation.

PendingHandoff dataclass

A handoff one node decided, as far as it is known before it lands: the source side. The target is what landing resolves — the decision's route, as the agent is actually mounted — so it is read there when the row is recorded, and nothing here could name it without risking a second, drifting copy.

The source is who handed the conversation over, and where from as the row names it: the conversation the deciding turn ran in, the last model message in it and the run that left that message, read off the ledger rather than the run result because the row's foreign keys hold only for what was persisted. A native summon names its agent and nothing else, since the gateway cannot name the terminal session it came from; a route that pins a thread's owner names nobody.

Source code in octomate/reflex/state.py
@dataclass(frozen=True)
class PendingHandoff:
    """A handoff one node decided, as far as it is known before it lands: the source
    side. The target is what landing resolves — the decision's route, as the agent
    is actually mounted — so it is read there when the row is recorded, and
    nothing here could name it without risking a second, drifting copy.

    The source is who handed the conversation over, and where from as the row names
    it: the conversation the deciding turn ran in, the last model message in it and
    the run that left that message, read off the ledger rather than the run result
    because the row's foreign keys hold only for what was persisted. A native summon
    names its agent and nothing else, since the gateway cannot name the terminal
    session it came from; a route that pins a thread's owner names nobody."""

    source_agent_tentacle_id: str | None = None
    source_conversation_id: UUID7 | None = None
    source_run_id: str | None = None
    source_model_message_id: UUID7 | None = None

    async def land(
        self, deps: ReflexDeps, thread: Thread, decision: SummonDecision
    ) -> None:
        """Record this handoff on the chat `thread` belongs to, naming the agent
        and model `decision` resolved to, unless that chat already names them."""
        target_conversation = await deps.conversation_manager.ensure(
            thread.id, agent_tentacle_id=decision.agent_id, with_runs=False
        )
        chat = (
            thread
            if thread.kind == "group"
            else await deps.thread_manager.surface(thread)
        )
        latest = chat.latest_handoff
        if (
            latest is not None
            and latest.to_agent_tentacle_id == decision.agent_id
            and latest.to_model == decision.model
        ):
            return
        await deps.thread_manager.record_handoff(
            chat,
            source_agent_tentacle_id=self.source_agent_tentacle_id,
            to_agent_tentacle_id=decision.agent_id,
            to_model=decision.model,
            reason=decision.reason,
            hint=decision.hint,
            brief=decision.brief,
            source_conversation_id=self.source_conversation_id,
            target_conversation_id=target_conversation.id,
            source_run_id=self.source_run_id,
            source_model_message_id=self.source_model_message_id,
        )

source_agent_tentacle_id class-attribute instance-attribute

source_agent_tentacle_id: str | None = None

source_conversation_id class-attribute instance-attribute

source_conversation_id: UUID7 | None = None

source_run_id class-attribute instance-attribute

source_run_id: str | None = None

source_model_message_id class-attribute instance-attribute

source_model_message_id: UUID7 | None = None

land async

land(
    deps: ReflexDeps,
    thread: Thread,
    decision: SummonDecision,
) -> None

Record this handoff on the chat thread belongs to, naming the agent and model decision resolved to, unless that chat already names them.

Source code in octomate/reflex/state.py
async def land(
    self, deps: ReflexDeps, thread: Thread, decision: SummonDecision
) -> None:
    """Record this handoff on the chat `thread` belongs to, naming the agent
    and model `decision` resolved to, unless that chat already names them."""
    target_conversation = await deps.conversation_manager.ensure(
        thread.id, agent_tentacle_id=decision.agent_id, with_runs=False
    )
    chat = (
        thread
        if thread.kind == "group"
        else await deps.thread_manager.surface(thread)
    )
    latest = chat.latest_handoff
    if (
        latest is not None
        and latest.to_agent_tentacle_id == decision.agent_id
        and latest.to_model == decision.model
    ):
        return
    await deps.thread_manager.record_handoff(
        chat,
        source_agent_tentacle_id=self.source_agent_tentacle_id,
        to_agent_tentacle_id=decision.agent_id,
        to_model=decision.model,
        reason=decision.reason,
        hint=decision.hint,
        brief=decision.brief,
        source_conversation_id=self.source_conversation_id,
        target_conversation_id=target_conversation.id,
        source_run_id=self.source_run_id,
        source_model_message_id=self.source_model_message_id,
    )

ReflexResult dataclass

A finished turn: the decision it ran on, where it answered, and the agent's result.

Source code in octomate/reflex/state.py
@dataclass
class ReflexResult:
    """A finished turn: the decision it ran on, where it answered, and the agent's
    result."""

    decision: SummonDecision | None
    target: ResponseTarget
    result: AgentRunResult[ChannelOutput] | None = None
    outcome: Literal["completed", "handed_off"] = "completed"

decision instance-attribute

decision: SummonDecision | None

target instance-attribute

target: ResponseTarget

result class-attribute instance-attribute

result: AgentRunResult[ChannelOutput] | None = None

outcome class-attribute instance-attribute

outcome: Literal['completed', 'handed_off'] = 'completed'

DeferredResult dataclass

A turn that stopped on deferred requests, and the batch they were parked as.

Source code in octomate/reflex/state.py
@dataclass
class DeferredResult:
    """A turn that stopped on deferred requests, and the batch they were parked
    as."""

    requests: DeferredToolRequests
    target: ResponseTarget
    # The name of the run that deferred — carried for observability. `str`, not
    # `RunName`, because on a re-present it is read back from the persisted batch.
    run_name: str
    result: AgentRunResult[Any]
    batch_id: UUID7 | None = None

requests instance-attribute

requests: DeferredToolRequests

target instance-attribute

target: ResponseTarget

run_name instance-attribute

run_name: str

result instance-attribute

result: AgentRunResult[Any]

batch_id class-attribute instance-attribute

batch_id: UUID7 | None = None

ReflexState dataclass

All run-wide context for one reflex graph run.

Admission resolves the execution thread before the graph starts. Nodes read that thread from state and carry only transition discriminators.

Source code in octomate/reflex/state.py
@dataclass
class ReflexState:
    """All run-wide context for one reflex graph run.

    Admission resolves the execution thread before the graph starts. Nodes read
    that thread from state and carry only transition discriminators.
    """

    user_profile: UserProfile  # The caller whose identity this run carries.
    owner_id: UUID7 = field(
        init=False, repr=False
    )  # Set from a validated Gateway signal or session before an owned operation.

    source_target: ResponseTarget | None = None
    target: ResponseTarget | None = None
    run_name: RunName = "react"
    decision: SummonDecision | None = None
    selection: AgentRouteKey | None = None  # Selected agent and model.
    conversation_id: uuid.UUID | None = None  # Current invocation's conversation.
    targets: dict[str, ResponseTarget] = field(default_factory=dict)
    summon_routes: list[AgentRoute] = field(default_factory=list)
    thread: Thread | None = None
    trigger_message: ThreadMessage | None = None  # Persisted incoming message.
    source_thread_address: ChannelAddress | None = None
    source_thread_message_ids: list[UUID7] = field(default_factory=list)
    # The handoff the next React records when it lands, or None when it records
    # none.
    handoff: PendingHandoff | None = None
    user_prompt: str | Sequence[UserContent] | None = None
    command_request_id: UUID7 | None = (
        None  # Command whose completion this reflex owes.
    )
    dispatched: bool = False  # A receiving agent now owns the rest of this reflex.
    interruption: Interruption = field(default_factory=Interruption)

    @property
    def execution_thread(self) -> Thread:
        """The admitted thread for an operation that requires an existing task."""
        if self.thread is None:
            raise ValueError("This operation requires an admitted execution thread")
        return self.thread

user_profile instance-attribute

user_profile: UserProfile

owner_id class-attribute instance-attribute

owner_id: UUID7 = field(init=False, repr=False)

source_target class-attribute instance-attribute

source_target: ResponseTarget | None = None

target class-attribute instance-attribute

target: ResponseTarget | None = None

run_name class-attribute instance-attribute

run_name: RunName = 'react'

decision class-attribute instance-attribute

decision: SummonDecision | None = None

selection class-attribute instance-attribute

selection: AgentRouteKey | None = None

conversation_id class-attribute instance-attribute

conversation_id: UUID | None = None

targets class-attribute instance-attribute

targets: dict[str, ResponseTarget] = field(
    default_factory=dict
)

summon_routes class-attribute instance-attribute

summon_routes: list[AgentRoute] = field(
    default_factory=list
)

thread class-attribute instance-attribute

thread: Thread | None = None

trigger_message class-attribute instance-attribute

trigger_message: ThreadMessage | None = None

source_thread_address class-attribute instance-attribute

source_thread_address: ChannelAddress | None = None

source_thread_message_ids class-attribute instance-attribute

source_thread_message_ids: list[UUID7] = field(
    default_factory=list
)

handoff class-attribute instance-attribute

handoff: PendingHandoff | None = None

user_prompt class-attribute instance-attribute

user_prompt: str | Sequence[UserContent] | None = None

command_request_id class-attribute instance-attribute

command_request_id: UUID7 | None = None

dispatched class-attribute instance-attribute

dispatched: bool = False

interruption class-attribute instance-attribute

interruption: Interruption = field(
    default_factory=Interruption
)

execution_thread property

execution_thread: Thread

The admitted thread for an operation that requires an existing task.

ReflexDeps dataclass

The host's registries and managers a reflex run reaches through.

Source code in octomate/reflex/state.py
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
@dataclass
class ReflexDeps:
    """The host's registries and managers a reflex run reaches through."""

    tentacles: dict[str, Tentacle]
    # No defaults for the managers: a deps object must carry the host's own — the
    # ledger, the conversations, the deferred actions, the gateway's live-session
    # registry — never private ones with their own identity or state.
    thread_manager: ThreadManager
    # For the bookkeeping a finished turn owes and the agent has no part in:
    # leaving the thread's workspace somewhere losing the directory cannot cost it.
    workspaces: WorkspaceManager
    conversation_manager: ConversationManager
    action_manager: DeferredActionManager
    gateway: GatewayManager
    # The graph's end of the nerve: what the kick does, sent as impulses.
    impulses: ObjectSendStream[Impulse]
    executor: str | None = (
        None  # Owning tentacle; None when exercising graph nodes directly.
    )
    origin: ChannelAddress | None = (
        None  # Surface whose kick owns this reflex's lifetime.
    )

    @property
    def channels(self) -> dict[str, ChannelTentacle]:
        return {
            id: tentacle
            for id, tentacle in self.tentacles.items()
            if isinstance(tentacle, ChannelTentacle)
        }

    @property
    def agents(self) -> dict[str, AgentTentacle]:
        return {
            id: tentacle
            for id, tentacle in self.tentacles.items()
            if isinstance(tentacle, AgentTentacle)
        }

    def resolve_target(
        self, address: ChannelAddress, *, mode: ResponseTargetMode = "main"
    ) -> ResponseTarget:
        """Resolve registered IM policies or a direct native/ACP endpoint."""
        match self.tentacles.get(address.channel_tentacle_id):
            case ChannelTentacle() as channel:
                return ResponseTarget(
                    channel_id=channel.id,
                    address=address,
                    dm_strategy=channel.dm_strategy,
                    thread_strategy=channel.thread_strategy,
                    mode=mode,
                )
            case AgentTentacle() | AcpChannelTentacle():
                return ResponseTarget(
                    channel_id=address.channel_tentacle_id,
                    address=address,
                    dm_strategy="continuous",
                    thread_strategy="main_only",
                    mode=mode,
                )
            case None:
                raise ValueError(
                    f"unknown response endpoint {address.channel_tentacle_id!r}"
                )
            case _:
                raise ValueError(
                    f"tentacle {address.channel_tentacle_id!r} cannot receive agent responses"
                )

    async def admit(
        self, signal: AwakeSignal, *, owner_id: UUID7 | None
    ) -> Thread | None:
        """Resolve and authorize an execution target before entering the graph."""
        match signal:
            case UserMessageSignal():
                if not signal:
                    return None
                return await self.thread_manager.enter(
                    signal.address, owner_id=owner_id
                )
            case CommandSignal():
                conversation = signal.context.conversation
                if conversation is None:
                    return None
                thread: Thread | UUID7 | ThreadKey = conversation.thread_id
            case ContinueSignal() | DrivenGatewaySignal():
                thread = signal.thread_id
            case SummonSignal():
                thread = await self.thread_manager.ensure(
                    signal.destination, owner_id=owner_id
                )
            case NativeGatewaySignal(decision=TeleportDecision()):
                if signal.source is None:
                    raise ValueError("A native teleport requires its source address")
                thread = ThreadKey.model_validate(signal.source)
            case NativeGatewaySignal() | DeferredActionBatchResponse():
                return None
            case _:
                raise ValueError("Unsupported awake signal")
        if not isinstance(thread, Thread):
            found = await self.thread_manager.get(thread, with_messages=False)
            if found is None:
                raise ValueError("The task thread is unavailable")
            thread = found
        if thread.owner_id is None or thread.owner_id != owner_id:
            raise PermissionError("Only the thread owner may control this task")
        return thread

    @cached_property
    def runtime(self) -> ReflexRuntime:
        """Stateless orchestration shared by this graph's execution entries."""
        return ReflexRuntime()

    @overload
    def channel(self, target: ResponseTarget) -> ChannelTentacle: ...

    @overload
    def channel(self, target: str) -> ChannelTentacle: ...

    def channel(self, target: ResponseTarget | str) -> ChannelTentacle:
        channel_id = target.channel_id if isinstance(target, ResponseTarget) else target
        channel = self.tentacles.get(channel_id)
        if not isinstance(channel, ChannelTentacle):
            raise ValueError(f"unknown channel {channel_id!r}")
        return channel

    def agent(self, agent_id: str) -> AgentTentacle:
        agent = self.tentacles.get(agent_id)
        if not isinstance(agent, AgentTentacle):
            raise ValueError(f"unknown agent {agent_id!r}")
        return agent

    async def handoff(
        self,
        state: ReflexState,
        *,
        resume_batch_id: UUID7 | None,
        tool_results: dict[str, str] | None,
    ) -> ReflexGraphResult:
        """Continue this reflex on its selected agent through the signal nerve."""
        state.interruption.check()
        target = state.target
        source = state.source_target
        decision = state.decision
        if (
            self.origin is None
            or self.executor is None
            or state.thread is None
            or target is None
            or target.address is None
            or source is None
            or source.address is None
            or decision is None
        ):
            raise ValueError(
                "A handoff requires an owned reflex with resolved addresses and thread"
            )
        agent = self.agent(decision.agent_id)
        claim = state.handoff
        signal = ContinueSignal(
            decision=decision,
            destination=target.address,
            agent_id=claim.source_agent_tentacle_id or self.executor
            if claim
            else self.executor,
            user_profile=state.user_profile,
            source_conversation_id=claim.source_conversation_id if claim else None,
            source_run_id=claim.source_run_id if claim else None,
            source_model_message_id=claim.source_model_message_id if claim else None,
            thread_id=state.thread.id,
            origin=self.origin,
            woke_at=agent.octomate.awake_since[ThreadKey.model_validate(self.origin)],
            source_address=source.address,
            target_mode=target.mode,
            run_name=state.run_name,
            user_prompt=decision.brief or str(state.user_prompt or ""),
            source_thread_address=state.source_thread_address,
            source_thread_message_ids=state.source_thread_message_ids,
            record_handoff=claim is not None,
            resume_batch_id=resume_batch_id,
            tool_results=tool_results,
            command_request_id=state.command_request_id,
        )

        agent.nerves.signals.dispatch(AgentTopic(agent.id), signal)
        state.dispatched = True
        return ReflexResult(decision=decision, target=target, outcome="handed_off")

    @cached_property
    def gateway_agents(self) -> frozenset[str]:
        """The agents whose driven turns offer the gateway spells: each agent's own
        flag, settled at startup and read once. A turn of any other agent builds no
        session, so external callers find nothing live for it."""
        return frozenset(id for id, agent in self.agents.items() if agent.gateway)

    async def octomate_session(
        self,
        agent: AgentTentacle,
        *,
        user_profile: UserProfile,
        thread_id: UUID7 | None,
        conversation_address: ChannelAddress,
        conversation_id: uuid.UUID | None = None,
    ) -> OctomateSession | None:
        """One turn's gateway for `agent`, or None for an agent whose flag is off.

        Built from the host's own registries, every channel's and not just this
        one's: a spell that crosses lands where another channel's config decides who
        runs, so the gateway offers — and checks against — that channel's routes,
        and reads `surfaces` off it to know whether `scheme` can land. The agents
        are what the accomplice spells run; without a thread there is nowhere for
        a child conversation to live, and the gateway then does not offer them.
        """
        if agent.id not in self.gateway_agents:
            return None
        session = OctomateSession(
            channel_routes=self.available_routes,
            current_agent_id=agent.id,
            channels=self.channels,
            users=self.thread_manager.users,
            user_profile=user_profile,
            agents=self.agents,
            thread_id=thread_id,
            conversation_address=conversation_address,
            threads=self.thread_manager,
            workspaces=self.workspaces,
            impulses=self.impulses,
            nerves=agent.nerves,
        )
        if conversation_id is not None:
            session.conversation_id = conversation_id
        elif thread_id is not None:
            # The same (thread, agent) key the run resolves internally, so an
            # external runtime's tool call finds this turn's session by the
            # conversation it already knows.
            conversation = await self.conversation_manager.ensure(
                thread_id, agent_tentacle_id=agent.id, with_runs=False
            )
            session.conversation_id = conversation.id
        return session

    @property
    def available_routes(self) -> dict[str, list[AgentRoute]]:
        return self.gateway.available_routes(self.channels, self.agents)

    def resolve_agent(
        self,
        channel_id: str,
        agent_id: str | None,
        model: AgentRouteModelName | None,
    ) -> AgentModelConfig:
        """Resolve a channel route, or an explicitly selected executor without a channel."""
        channel = self.channels.get(channel_id)
        if channel is not None:
            agent_ids = channel.agent_ids
        elif agent_id is not None:
            agent_ids = [agent_id]
        else:
            raise ValueError(f"unknown channel {channel_id!r}")
        if agent_id is None:
            agent_id = agent_ids[0]
        if agent_id not in agent_ids:
            raise ValueError(
                f"agent {agent_id!r} is not bound to channel {channel_id!r}"
            )

        agent = self.agent(agent_id)
        if model is None:
            return AgentModelConfig(agent=agent_id, model=agent.resolve_model())
        served = agent.served_model(model)
        if served is None:
            raise ValueError(f"agent {agent_id!r} does not serve model {model!r}")
        return AgentModelConfig(agent=agent_id, model=served)

    async def render_chat(
        self, messages: list[ThreadMessage], *, ceiling: int = 0
    ) -> str:
        """The ledger rows as one transcript: who spoke, under which identities, and
        the `#msg:<id>` handle a brief would cite them by.

        Each message is its segments, as they render themselves — the same body an
        inbound event shows. `message_text` would be the shorter route and the wrong
        one: it keeps only text and markdown, so a message that was a picture or a
        quoted reply arrives as nothing at all.

        `ceiling` cuts each message. It is 0 for the messages a turn must answer —
        those are the work — and set for the chat behind them, where one pasted log
        would otherwise be the whole slice.
        """
        parts: list[str] = []
        for message in messages:
            if message.kind != "message":
                continue
            text = "\n".join(str(segment) for segment in message.segments)
            if not text:
                continue
            if ceiling and len(text) > ceiling:
                text = f"{text[:ceiling]}…"
            sender = await message.sender
            display_name = (
                (sender.name or sender.nickname or "anonymous")
                if sender is not None
                else "anonymous"
            )
            owner = sender.user.peek() if sender is not None else None
            ids = (
                f"{message.user_id}, user:{owner.username}"
                if owner is not None
                else message.user_id
            )
            platform_id = (
                f" #msg:{message.platform_message_id}"
                if message.platform_message_id
                else ""
            )
            parts.append(f"{display_name} ({ids}){platform_id}:\n{text}")
        return "\n\n".join(parts)

    async def report(self, state: ReflexState, error: Exception) -> None:
        """Publish that the turn failed, on the thread it came from. A turn that
        failed before it knew its source has nobody to tell."""
        source = state.source_target.address if state.source_target else None
        if source is None:
            return
        trace_id = format(trace.get_current_span().get_span_context().trace_id, "032x")
        failure = RunErrorEvent(message=str(error), trace_id=trace_id)
        await self.impulses.send(Impulse(failure, source))

    async def carry(
        self,
        address: ChannelAddress,
        stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
    ) -> None:
        """Send a run's stream on the nerve at `address` as wire events, item by
        item, until it ends."""
        async for item in stream:
            wire = to_wire(item)
            if wire is not None:
                await self.impulses.send(Impulse(wire, address))

    async def record_move(
        self,
        address: ChannelAddress,
        text: str,
        *,
        agent_tentacle_id: str,
        platform_message_id: str | None = None,
    ) -> ThreadMessage:
        """Write the line a move leaves behind to the ledger of the chat it left.

        A person already sees it — the channel posted it, and a thread opened here
        hangs off it. The turn that comes next does not: a chat room's recap is built
        from the ledger, and a move nobody recorded leaves a chat in which the work
        simply stops. An agent reading that answers what was carried away ten minutes
        ago.

        The row carries the opener's own platform id, so the ledger and the platform
        name the same message rather than two; a line still to be posted gets its id
        from the channel that posts it.
        """
        return await self.thread_manager.record_outbound(
            address,
            agent_tentacle_id=agent_tentacle_id,
            segments=[MarkdownSegment(data={"text": text})],
            sender=self.channel(address.channel_tentacle_id).self_profile,
            platform_message_id=platform_message_id,
            message_text=text,
            raw=text,
        )

    async def load_pending_prompt(
        self,
        state: ReflexState,
        active_agent_id: str,
        *,
        include_recap: bool = True,
    ) -> None:
        source_target = state.source_target
        if (
            state.thread is None
            or state.trigger_message is None
            or source_target is None
            or source_target.address is None
        ):
            return
        # Tasks consume their pending ledger messages; a new main-chat task takes
        # its triggering request and receives earlier chat through the recap.
        messages = await self.thread_manager.pending_prompt_messages(
            state.thread,
            state.trigger_message.id,
            active_agent_id,
            trigger_only=source_target.starts_task,
        )
        if not messages:
            return
        if not source_target.starts_task:
            state.source_thread_address = source_target.address
            state.source_thread_message_ids = [message.id for message in messages]

        asked = await self.render_chat(messages)
        if not asked:
            return
        recap = await self.chat_recap(state, messages[0]) if include_recap else ""
        # The messages the turn must answer are the body, unmarked. What was said
        # before them is the system's addition and stands in a tag.
        state.user_prompt = f"{recap}\n\n{asked}" if recap else asked

    async def chat_recap(self, state: ReflexState, earliest: ThreadMessage) -> str:
        """What was said in this chat room before the messages the turn must answer.

        Only a new task invoked from a main chat needs a preceding window.
        Continuous DMs and platform subthreads consume all pending messages as
        input, without a separate recap window.

        Read the main ledger before opening the task destination. The channel
        bounds how many human messages and how much of each to include.
        """
        thread = state.thread
        source_target = state.source_target
        if thread is None or source_target is None or not source_target.starts_task:
            return ""
        recap = self.channel(source_target).config.recap
        if not recap.messages:
            return ""
        messages = await self.thread_manager.chat_messages_before(
            thread.parent_thread_id or thread.id,
            earliest.id,
            limit=recap.messages,
            actor_kind="human",
        )
        rendered = await self.render_chat(messages, ceiling=recap.characters)
        return tagged("chat_recap", f"{RECAP_HEADER}\n\n{rendered}" if rendered else "")

tentacles instance-attribute

tentacles: dict[str, Tentacle]

thread_manager instance-attribute

thread_manager: ThreadManager

workspaces instance-attribute

workspaces: WorkspaceManager

conversation_manager instance-attribute

conversation_manager: ConversationManager

action_manager instance-attribute

action_manager: DeferredActionManager

gateway instance-attribute

gateway: GatewayManager

impulses instance-attribute

impulses: ObjectSendStream[Impulse]

executor class-attribute instance-attribute

executor: str | None = None

origin class-attribute instance-attribute

origin: ChannelAddress | None = None

channels property

channels: dict[str, ChannelTentacle]

agents property

agents: dict[str, AgentTentacle]

runtime cached property

runtime: ReflexRuntime

Stateless orchestration shared by this graph's execution entries.

gateway_agents cached property

gateway_agents: frozenset[str]

The agents whose driven turns offer the gateway spells: each agent's own flag, settled at startup and read once. A turn of any other agent builds no session, so external callers find nothing live for it.

available_routes property

available_routes: dict[str, list[AgentRoute]]

resolve_target

resolve_target(
    address: ChannelAddress,
    *,
    mode: ResponseTargetMode = "main",
) -> ResponseTarget

Resolve registered IM policies or a direct native/ACP endpoint.

Source code in octomate/reflex/state.py
def resolve_target(
    self, address: ChannelAddress, *, mode: ResponseTargetMode = "main"
) -> ResponseTarget:
    """Resolve registered IM policies or a direct native/ACP endpoint."""
    match self.tentacles.get(address.channel_tentacle_id):
        case ChannelTentacle() as channel:
            return ResponseTarget(
                channel_id=channel.id,
                address=address,
                dm_strategy=channel.dm_strategy,
                thread_strategy=channel.thread_strategy,
                mode=mode,
            )
        case AgentTentacle() | AcpChannelTentacle():
            return ResponseTarget(
                channel_id=address.channel_tentacle_id,
                address=address,
                dm_strategy="continuous",
                thread_strategy="main_only",
                mode=mode,
            )
        case None:
            raise ValueError(
                f"unknown response endpoint {address.channel_tentacle_id!r}"
            )
        case _:
            raise ValueError(
                f"tentacle {address.channel_tentacle_id!r} cannot receive agent responses"
            )

admit async

admit(
    signal: AwakeSignal, *, owner_id: UUID7 | None
) -> Thread | None

Resolve and authorize an execution target before entering the graph.

Source code in octomate/reflex/state.py
async def admit(
    self, signal: AwakeSignal, *, owner_id: UUID7 | None
) -> Thread | None:
    """Resolve and authorize an execution target before entering the graph."""
    match signal:
        case UserMessageSignal():
            if not signal:
                return None
            return await self.thread_manager.enter(
                signal.address, owner_id=owner_id
            )
        case CommandSignal():
            conversation = signal.context.conversation
            if conversation is None:
                return None
            thread: Thread | UUID7 | ThreadKey = conversation.thread_id
        case ContinueSignal() | DrivenGatewaySignal():
            thread = signal.thread_id
        case SummonSignal():
            thread = await self.thread_manager.ensure(
                signal.destination, owner_id=owner_id
            )
        case NativeGatewaySignal(decision=TeleportDecision()):
            if signal.source is None:
                raise ValueError("A native teleport requires its source address")
            thread = ThreadKey.model_validate(signal.source)
        case NativeGatewaySignal() | DeferredActionBatchResponse():
            return None
        case _:
            raise ValueError("Unsupported awake signal")
    if not isinstance(thread, Thread):
        found = await self.thread_manager.get(thread, with_messages=False)
        if found is None:
            raise ValueError("The task thread is unavailable")
        thread = found
    if thread.owner_id is None or thread.owner_id != owner_id:
        raise PermissionError("Only the thread owner may control this task")
    return thread

channel

channel(target: ResponseTarget) -> ChannelTentacle
channel(target: str) -> ChannelTentacle
channel(target: ResponseTarget | str) -> ChannelTentacle
Source code in octomate/reflex/state.py
def channel(self, target: ResponseTarget | str) -> ChannelTentacle:
    channel_id = target.channel_id if isinstance(target, ResponseTarget) else target
    channel = self.tentacles.get(channel_id)
    if not isinstance(channel, ChannelTentacle):
        raise ValueError(f"unknown channel {channel_id!r}")
    return channel

agent

agent(agent_id: str) -> AgentTentacle
Source code in octomate/reflex/state.py
def agent(self, agent_id: str) -> AgentTentacle:
    agent = self.tentacles.get(agent_id)
    if not isinstance(agent, AgentTentacle):
        raise ValueError(f"unknown agent {agent_id!r}")
    return agent

handoff async

handoff(
    state: ReflexState,
    *,
    resume_batch_id: UUID7 | None,
    tool_results: dict[str, str] | None,
) -> ReflexGraphResult

Continue this reflex on its selected agent through the signal nerve.

Source code in octomate/reflex/state.py
async def handoff(
    self,
    state: ReflexState,
    *,
    resume_batch_id: UUID7 | None,
    tool_results: dict[str, str] | None,
) -> ReflexGraphResult:
    """Continue this reflex on its selected agent through the signal nerve."""
    state.interruption.check()
    target = state.target
    source = state.source_target
    decision = state.decision
    if (
        self.origin is None
        or self.executor is None
        or state.thread is None
        or target is None
        or target.address is None
        or source is None
        or source.address is None
        or decision is None
    ):
        raise ValueError(
            "A handoff requires an owned reflex with resolved addresses and thread"
        )
    agent = self.agent(decision.agent_id)
    claim = state.handoff
    signal = ContinueSignal(
        decision=decision,
        destination=target.address,
        agent_id=claim.source_agent_tentacle_id or self.executor
        if claim
        else self.executor,
        user_profile=state.user_profile,
        source_conversation_id=claim.source_conversation_id if claim else None,
        source_run_id=claim.source_run_id if claim else None,
        source_model_message_id=claim.source_model_message_id if claim else None,
        thread_id=state.thread.id,
        origin=self.origin,
        woke_at=agent.octomate.awake_since[ThreadKey.model_validate(self.origin)],
        source_address=source.address,
        target_mode=target.mode,
        run_name=state.run_name,
        user_prompt=decision.brief or str(state.user_prompt or ""),
        source_thread_address=state.source_thread_address,
        source_thread_message_ids=state.source_thread_message_ids,
        record_handoff=claim is not None,
        resume_batch_id=resume_batch_id,
        tool_results=tool_results,
        command_request_id=state.command_request_id,
    )

    agent.nerves.signals.dispatch(AgentTopic(agent.id), signal)
    state.dispatched = True
    return ReflexResult(decision=decision, target=target, outcome="handed_off")

octomate_session async

octomate_session(
    agent: AgentTentacle,
    *,
    user_profile: UserProfile,
    thread_id: UUID7 | None,
    conversation_address: ChannelAddress,
    conversation_id: UUID | None = None,
) -> OctomateSession | None

One turn's gateway for agent, or None for an agent whose flag is off.

Built from the host's own registries, every channel's and not just this one's: a spell that crosses lands where another channel's config decides who runs, so the gateway offers — and checks against — that channel's routes, and reads surfaces off it to know whether scheme can land. The agents are what the accomplice spells run; without a thread there is nowhere for a child conversation to live, and the gateway then does not offer them.

Source code in octomate/reflex/state.py
async def octomate_session(
    self,
    agent: AgentTentacle,
    *,
    user_profile: UserProfile,
    thread_id: UUID7 | None,
    conversation_address: ChannelAddress,
    conversation_id: uuid.UUID | None = None,
) -> OctomateSession | None:
    """One turn's gateway for `agent`, or None for an agent whose flag is off.

    Built from the host's own registries, every channel's and not just this
    one's: a spell that crosses lands where another channel's config decides who
    runs, so the gateway offers — and checks against — that channel's routes,
    and reads `surfaces` off it to know whether `scheme` can land. The agents
    are what the accomplice spells run; without a thread there is nowhere for
    a child conversation to live, and the gateway then does not offer them.
    """
    if agent.id not in self.gateway_agents:
        return None
    session = OctomateSession(
        channel_routes=self.available_routes,
        current_agent_id=agent.id,
        channels=self.channels,
        users=self.thread_manager.users,
        user_profile=user_profile,
        agents=self.agents,
        thread_id=thread_id,
        conversation_address=conversation_address,
        threads=self.thread_manager,
        workspaces=self.workspaces,
        impulses=self.impulses,
        nerves=agent.nerves,
    )
    if conversation_id is not None:
        session.conversation_id = conversation_id
    elif thread_id is not None:
        # The same (thread, agent) key the run resolves internally, so an
        # external runtime's tool call finds this turn's session by the
        # conversation it already knows.
        conversation = await self.conversation_manager.ensure(
            thread_id, agent_tentacle_id=agent.id, with_runs=False
        )
        session.conversation_id = conversation.id
    return session

resolve_agent

resolve_agent(
    channel_id: str,
    agent_id: str | None,
    model: AgentRouteModelName | None,
) -> AgentModelConfig

Resolve a channel route, or an explicitly selected executor without a channel.

Source code in octomate/reflex/state.py
def resolve_agent(
    self,
    channel_id: str,
    agent_id: str | None,
    model: AgentRouteModelName | None,
) -> AgentModelConfig:
    """Resolve a channel route, or an explicitly selected executor without a channel."""
    channel = self.channels.get(channel_id)
    if channel is not None:
        agent_ids = channel.agent_ids
    elif agent_id is not None:
        agent_ids = [agent_id]
    else:
        raise ValueError(f"unknown channel {channel_id!r}")
    if agent_id is None:
        agent_id = agent_ids[0]
    if agent_id not in agent_ids:
        raise ValueError(
            f"agent {agent_id!r} is not bound to channel {channel_id!r}"
        )

    agent = self.agent(agent_id)
    if model is None:
        return AgentModelConfig(agent=agent_id, model=agent.resolve_model())
    served = agent.served_model(model)
    if served is None:
        raise ValueError(f"agent {agent_id!r} does not serve model {model!r}")
    return AgentModelConfig(agent=agent_id, model=served)

render_chat async

render_chat(
    messages: list[ThreadMessage], *, ceiling: int = 0
) -> str

The ledger rows as one transcript: who spoke, under which identities, and the #msg:<id> handle a brief would cite them by.

Each message is its segments, as they render themselves — the same body an inbound event shows. message_text would be the shorter route and the wrong one: it keeps only text and markdown, so a message that was a picture or a quoted reply arrives as nothing at all.

ceiling cuts each message. It is 0 for the messages a turn must answer — those are the work — and set for the chat behind them, where one pasted log would otherwise be the whole slice.

Source code in octomate/reflex/state.py
async def render_chat(
    self, messages: list[ThreadMessage], *, ceiling: int = 0
) -> str:
    """The ledger rows as one transcript: who spoke, under which identities, and
    the `#msg:<id>` handle a brief would cite them by.

    Each message is its segments, as they render themselves — the same body an
    inbound event shows. `message_text` would be the shorter route and the wrong
    one: it keeps only text and markdown, so a message that was a picture or a
    quoted reply arrives as nothing at all.

    `ceiling` cuts each message. It is 0 for the messages a turn must answer —
    those are the work — and set for the chat behind them, where one pasted log
    would otherwise be the whole slice.
    """
    parts: list[str] = []
    for message in messages:
        if message.kind != "message":
            continue
        text = "\n".join(str(segment) for segment in message.segments)
        if not text:
            continue
        if ceiling and len(text) > ceiling:
            text = f"{text[:ceiling]}…"
        sender = await message.sender
        display_name = (
            (sender.name or sender.nickname or "anonymous")
            if sender is not None
            else "anonymous"
        )
        owner = sender.user.peek() if sender is not None else None
        ids = (
            f"{message.user_id}, user:{owner.username}"
            if owner is not None
            else message.user_id
        )
        platform_id = (
            f" #msg:{message.platform_message_id}"
            if message.platform_message_id
            else ""
        )
        parts.append(f"{display_name} ({ids}){platform_id}:\n{text}")
    return "\n\n".join(parts)

report async

report(state: ReflexState, error: Exception) -> None

Publish that the turn failed, on the thread it came from. A turn that failed before it knew its source has nobody to tell.

Source code in octomate/reflex/state.py
async def report(self, state: ReflexState, error: Exception) -> None:
    """Publish that the turn failed, on the thread it came from. A turn that
    failed before it knew its source has nobody to tell."""
    source = state.source_target.address if state.source_target else None
    if source is None:
        return
    trace_id = format(trace.get_current_span().get_span_context().trace_id, "032x")
    failure = RunErrorEvent(message=str(error), trace_id=trace_id)
    await self.impulses.send(Impulse(failure, source))

carry async

carry(
    address: ChannelAddress,
    stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
) -> None

Send a run's stream on the nerve at address as wire events, item by item, until it ends.

Source code in octomate/reflex/state.py
async def carry(
    self,
    address: ChannelAddress,
    stream: AsyncIterator[ReactStreamEvent[ChannelOutput]],
) -> None:
    """Send a run's stream on the nerve at `address` as wire events, item by
    item, until it ends."""
    async for item in stream:
        wire = to_wire(item)
        if wire is not None:
            await self.impulses.send(Impulse(wire, address))

record_move async

record_move(
    address: ChannelAddress,
    text: str,
    *,
    agent_tentacle_id: str,
    platform_message_id: str | None = None,
) -> ThreadMessage

Write the line a move leaves behind to the ledger of the chat it left.

A person already sees it — the channel posted it, and a thread opened here hangs off it. The turn that comes next does not: a chat room's recap is built from the ledger, and a move nobody recorded leaves a chat in which the work simply stops. An agent reading that answers what was carried away ten minutes ago.

The row carries the opener's own platform id, so the ledger and the platform name the same message rather than two; a line still to be posted gets its id from the channel that posts it.

Source code in octomate/reflex/state.py
async def record_move(
    self,
    address: ChannelAddress,
    text: str,
    *,
    agent_tentacle_id: str,
    platform_message_id: str | None = None,
) -> ThreadMessage:
    """Write the line a move leaves behind to the ledger of the chat it left.

    A person already sees it — the channel posted it, and a thread opened here
    hangs off it. The turn that comes next does not: a chat room's recap is built
    from the ledger, and a move nobody recorded leaves a chat in which the work
    simply stops. An agent reading that answers what was carried away ten minutes
    ago.

    The row carries the opener's own platform id, so the ledger and the platform
    name the same message rather than two; a line still to be posted gets its id
    from the channel that posts it.
    """
    return await self.thread_manager.record_outbound(
        address,
        agent_tentacle_id=agent_tentacle_id,
        segments=[MarkdownSegment(data={"text": text})],
        sender=self.channel(address.channel_tentacle_id).self_profile,
        platform_message_id=platform_message_id,
        message_text=text,
        raw=text,
    )

load_pending_prompt async

load_pending_prompt(
    state: ReflexState,
    active_agent_id: str,
    *,
    include_recap: bool = True,
) -> None
Source code in octomate/reflex/state.py
async def load_pending_prompt(
    self,
    state: ReflexState,
    active_agent_id: str,
    *,
    include_recap: bool = True,
) -> None:
    source_target = state.source_target
    if (
        state.thread is None
        or state.trigger_message is None
        or source_target is None
        or source_target.address is None
    ):
        return
    # Tasks consume their pending ledger messages; a new main-chat task takes
    # its triggering request and receives earlier chat through the recap.
    messages = await self.thread_manager.pending_prompt_messages(
        state.thread,
        state.trigger_message.id,
        active_agent_id,
        trigger_only=source_target.starts_task,
    )
    if not messages:
        return
    if not source_target.starts_task:
        state.source_thread_address = source_target.address
        state.source_thread_message_ids = [message.id for message in messages]

    asked = await self.render_chat(messages)
    if not asked:
        return
    recap = await self.chat_recap(state, messages[0]) if include_recap else ""
    # The messages the turn must answer are the body, unmarked. What was said
    # before them is the system's addition and stands in a tag.
    state.user_prompt = f"{recap}\n\n{asked}" if recap else asked

chat_recap async

chat_recap(
    state: ReflexState, earliest: ThreadMessage
) -> str

What was said in this chat room before the messages the turn must answer.

Only a new task invoked from a main chat needs a preceding window. Continuous DMs and platform subthreads consume all pending messages as input, without a separate recap window.

Read the main ledger before opening the task destination. The channel bounds how many human messages and how much of each to include.

Source code in octomate/reflex/state.py
async def chat_recap(self, state: ReflexState, earliest: ThreadMessage) -> str:
    """What was said in this chat room before the messages the turn must answer.

    Only a new task invoked from a main chat needs a preceding window.
    Continuous DMs and platform subthreads consume all pending messages as
    input, without a separate recap window.

    Read the main ledger before opening the task destination. The channel
    bounds how many human messages and how much of each to include.
    """
    thread = state.thread
    source_target = state.source_target
    if thread is None or source_target is None or not source_target.starts_task:
        return ""
    recap = self.channel(source_target).config.recap
    if not recap.messages:
        return ""
    messages = await self.thread_manager.chat_messages_before(
        thread.parent_thread_id or thread.id,
        earliest.id,
        limit=recap.messages,
        actor_kind="human",
    )
    rendered = await self.render_chat(messages, ceiling=recap.characters)
    return tagged("chat_recap", f"{RECAP_HEADER}\n\n{rendered}" if rendered else "")

ReflexRuntime

Stateless orchestration in graph deps; invocation resources stay with callers.

Source code in octomate/reflex/state.py
class ReflexRuntime:
    """Stateless orchestration in graph deps; invocation resources stay with callers."""

    @asynccontextmanager
    async def finalizing(
        self, ctx: GraphRunContext[ReflexState, ReflexDeps]
    ) -> AsyncGenerator[None]:
        """Publish finalization, and save the registered work a failed turn left.

        A run that ends checkpoints its own volume. A failure outside the run closes
        it unsaved, and an unsaved tree is one the sweep never reclaims.
        """
        failed = False
        try:
            yield
        except Exception:
            failed = True
            raise
        finally:
            state = ctx.state
            await ctx.deps.impulses.send(
                Impulse(
                    ReflexPhaseChangedEvent(phase="finalizing"),
                    state.target.address if state.target is not None else None,
                )
            )
            profile = state.user_profile
            if failed and state.thread is not None and profile.user_id is not None:
                await ctx.deps.workspaces.save(state.thread, profile.user_id)

    async def resources(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
    ) -> tuple[OctomateSession | None, ReflexSuspender, list[AgentCapability[None]]]:
        """Build fresh gateway, approval and tool context for the selected invocation."""
        state = ctx.state
        target = state.target
        source = state.source_target
        selection = state.selection
        if (
            target is None
            or target.address is None
            or source is None
            or source.address is None
            or selection is None
        ):
            raise ValueError(
                "a Reflex run requires a selected agent and resolved source and target addresses"
            )
        agent = ctx.deps.agent(selection.agent_id)
        thread_id = state.thread.id if state.thread else None
        state.summon_routes = [
            route
            for route in ctx.deps.available_routes.get(target.channel_id, [])
            if route.agent_id != agent.id
        ]
        session = await ctx.deps.octomate_session(
            agent,
            user_profile=state.user_profile,
            thread_id=thread_id,
            conversation_address=target.address,
            conversation_id=state.conversation_id,
        )
        if session is not None:
            state.owner_id = session.owner_id
        capabilities: list[AgentCapability[None]] = []
        suspender = ReflexSuspender(
            action_manager=ctx.deps.action_manager,
            conversation_manager=ctx.deps.conversation_manager,
            agent_tentacle_id=agent.id,
            run_name=state.run_name,
            source_address=source.address,
            target_address=target.address,
            target_mode=target.mode,
            decision=state.decision,
            model=selection.model,
            thread_id=thread_id,
        )
        return session, suspender, capabilities

    async def prepare_user(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        profile: UserProfile,
        *,
        session: OctomateSession | None,
        suspender: ReflexSuspender,
        capabilities: list[AgentCapability[None]],
    ) -> None:
        """Mount capabilities belonging to the user authorized for this invocation."""
        ctx.state.user_profile = profile
        if session is not None:
            session.user_profile = profile
        agent = ctx.deps.agent(suspender.agent_tentacle_id)
        capabilities.extend(await agent.user_capabilities(profile))

    async def send(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        suspender: ReflexSuspender,
        event: MessageSentEvent,
    ) -> bool:
        """Deliver a gateway send to a person's direct messages, when possible:
        recorded there first, then published for that thread alone."""
        destination = event.destination
        if destination is None:
            return False
        channel = ctx.deps.channel(destination.channel_tentacle_id)
        dm = await channel.open_dm(destination.user_id)
        if dm is None:
            logger.warning(
                "Channel %s could not open a DM with %s; delivering the send to %s instead",
                destination.channel_tentacle_id,
                destination.user_id,
                suspender.target_address,
            )
            return False
        message = await ctx.deps.thread_manager.record_outbound(
            dm,
            agent_tentacle_id=suspender.agent_tentacle_id,
            segments=event.segments,
            sender=channel.self_profile,
            owner_id=ctx.state.owner_id,
        )
        sent = MessageSentEvent(
            segments=event.segments, destination=dm, thread_message_id=message.id
        )
        await ctx.deps.impulses.send(Impulse(sent, dm, private=True))
        return True

    async def drive(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        suspender: ReflexSuspender,
        source: AsyncGenerator[ReactStreamEvent[ChannelOutput], None],
    ) -> AgentRunResult[ChannelOutput]:
        """Run the native invocation onto the nerve, closing it before recording
        its reply: the run's start before anything it streams, and its end after,
        carrying the reply's ledger row, whatever happened."""
        results: list[AgentRunResult[ChannelOutput]] = []
        address = suspender.target_address

        async def events() -> AsyncGenerator[ReactStreamEvent[ChannelOutput], None]:
            async for event in source:
                if isinstance(event, AgentRunResultEvent):
                    results.append(event.result)
                if isinstance(event, MessageSentEvent) and await self.send(
                    ctx, suspender, event
                ):
                    continue
                yield event

        await ctx.deps.impulses.send(
            Impulse(
                RunStartedEvent(
                    address=address,
                    sender=ctx.state.user_profile,
                    agent_tentacle_id=suspender.agent_tentacle_id,
                ),
                address,
            )
        )
        ended = RunEndedEvent(outcome="failed")
        try:
            await ctx.deps.impulses.send(
                Impulse(RunActivityChangedEvent(activity="working"), address)
            )
            async with aclosing(source), aclosing(events()) as stream:
                await ctx.deps.carry(address, stream)
            if not results:
                raise RuntimeError(
                    f"react stream for {address} completed without a result"
                )
            ctx.state.interruption.check()
            reply = await self.record_reply(ctx, suspender, results[-1])
            ended.thread_message_id = reply.id if reply is not None else None
            ended.outcome = (
                "deferred"
                if isinstance(results[-1].output, DeferredToolRequests)
                else "completed"
            )
            return results[-1]
        except (asyncio.CancelledError, RunInterrupted):
            ended.outcome = "cancelled"
            raise
        finally:
            await ctx.deps.impulses.send(Impulse(ended, address))

    async def record_reply(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        suspender: ReflexSuspender,
        result: AgentRunResult[ChannelOutput],
    ) -> ThreadMessage | None:
        """Record and bind the run's reply, answering its row for the channel to
        mark with the platform id it renders the reply as."""
        output = result.output
        segments: list[MessageSegment]
        if isinstance(output, str):
            segments = [MarkdownSegment(data={"text": output})] if output else []
        elif isinstance(output, Iterable):
            segments = list(output)
        else:
            return None
        reply_to, body = split_reply(segments)
        message = None
        if body:
            channel = ctx.deps.channels.get(
                suspender.target_address.channel_tentacle_id
            )
            sender = (
                channel.self_profile if channel is not None else ctx.state.user_profile
            )
            message = await ctx.deps.thread_manager.record_outbound(
                suspender.target_address,
                agent_tentacle_id=suspender.agent_tentacle_id,
                segments=segments,
                reply_id=reply_to or "",
                sender=sender,
                raw=output
                if isinstance(output, str)
                else "\n\n".join(str(segment) for segment in body),
                message_text=output if isinstance(output, str) else None,
            )
        await ctx.deps.thread_manager.bind_assistant_replies(
            [message.id] if message is not None else [],
            run_id=result.run_id,
        )
        return message

    async def present_command(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        suspender: ReflexSuspender,
        outcome: CommandOutcome,
    ) -> None:
        """Publish direct feedback; its command receipt already owns the output."""
        segments: list[MessageSegment] = (
            [TextSegment(data={"text": outcome.message})]
            if isinstance(outcome, CommandError)
            else outcome.segments
        )
        if not segments:
            return
        await ctx.deps.impulses.send(
            Impulse(MessageSentEvent(segments=segments), suspender.target_address)
        )

    async def finish(
        self,
        ctx: GraphRunContext[ReflexState, ReflexDeps],
        session: OctomateSession | None,
        suspender: ReflexSuspender,
        run_result: AgentRunResult[ChannelOutput],
    ) -> Summon | Teleport | Scheme | End[ReflexGraphResult]:
        """Follow the gateway decision or deferral left by an actual agent run."""
        # These nodes import the graph types consumed by this runtime.
        from octomate.reflex.nodes.scheme import Scheme
        from octomate.reflex.nodes.summon import Summon
        from octomate.reflex.nodes.teleport import Teleport

        state = ctx.state
        target = state.target
        if target is None:
            raise ValueError("a Reflex run requires a resolved target")
        decision = state.decision
        agent_id = suspender.agent_tentacle_id
        thread_id = state.thread.id if state.thread else None
        output = run_result.output
        with reflex_logfire.span("reflex.finish", run_id=run_result.run_id) as span:
            if session is not None and session.dismissing and state.thread is not None:
                # The agent said this thread's work is done: its tree goes now
                # that the run is out of it, saved first and kept if that failed.
                result = await ctx.deps.workspaces.dismiss(state.thread, state.owner_id)
                span.set_attribute(
                    "react.dismissed",
                    result,
                )
            # `teleport` is resolved by the graph (fork + resume), not a human. The
            # suspender classified it by its declared metadata kind and stashed it,
            # so route on the typed request instead of re-scanning tool names.
            if (
                isinstance(output, DeferredToolRequests)
                and suspender.teleport is not None
            ):
                if session is None:
                    raise ValueError("Teleport requires an owned Gateway session")
                return Teleport(
                    request=suspender.teleport,
                    origin=target,
                    agent_id=agent_id,
                )
            if isinstance(output, DeferredToolRequests):
                return End(
                    DeferredResult(
                        requests=output,
                        target=target,
                        run_name=state.run_name,
                        result=run_result,
                        batch_id=suspender.suspended_batch_id,
                    )
                )

            gateway_decision = session.decision if session else None
            if isinstance(gateway_decision, SchemeDecision | SummonDecision):
                # Where this handoff came from, as the row records it: the
                # conversation this turn ran in, as of its last message.
                conversation = (
                    await ctx.deps.conversation_manager.ensure(
                        thread_id, agent_tentacle_id=agent_id, with_runs=False
                    )
                    if thread_id is not None
                    else None
                )
                history = (
                    await ctx.deps.conversation_manager.history(
                        conversation.id, limit=1
                    )
                    if conversation is not None
                    else []
                )
                last = history[-1] if history else None
                state.handoff = PendingHandoff(
                    source_agent_tentacle_id=agent_id,
                    source_conversation_id=conversation.id if conversation else None,
                    source_run_id=last.run_id if last else None,
                    source_model_message_id=last.id if last else None,
                )
            if session is not None and isinstance(gateway_decision, SchemeDecision):
                span.set_attribute("react.action", gateway_decision.action)
                reflex_logfire.info(
                    "react -> scheme into the asker's dm",
                    destination=str(gateway_decision.destination),
                )
                return Scheme(
                    request=gateway_decision,
                    origin=target,
                    agent_id=agent_id,
                )
            if session is not None and isinstance(gateway_decision, SummonDecision):
                state.decision = gateway_decision
                state.target = target
                state.run_name = "summon"
                span.set_attribute("react.action", gateway_decision.action)
                span.set_attribute("react.next_agent_id", gateway_decision.agent_id)
                reflex_logfire.info(
                    "react -> {action} agent={agent_id}",
                    action=gateway_decision.action,
                    agent_id=gateway_decision.agent_id,
                    reason=gateway_decision.reason,
                )
                return Summon()

            return End(
                ReflexResult(
                    decision=decision,
                    target=target,
                    result=run_result,
                )
            )

finalizing async

finalizing(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> AsyncGenerator[None]

Publish finalization, and save the registered work a failed turn left.

A run that ends checkpoints its own volume. A failure outside the run closes it unsaved, and an unsaved tree is one the sweep never reclaims.

Source code in octomate/reflex/state.py
@asynccontextmanager
async def finalizing(
    self, ctx: GraphRunContext[ReflexState, ReflexDeps]
) -> AsyncGenerator[None]:
    """Publish finalization, and save the registered work a failed turn left.

    A run that ends checkpoints its own volume. A failure outside the run closes
    it unsaved, and an unsaved tree is one the sweep never reclaims.
    """
    failed = False
    try:
        yield
    except Exception:
        failed = True
        raise
    finally:
        state = ctx.state
        await ctx.deps.impulses.send(
            Impulse(
                ReflexPhaseChangedEvent(phase="finalizing"),
                state.target.address if state.target is not None else None,
            )
        )
        profile = state.user_profile
        if failed and state.thread is not None and profile.user_id is not None:
            await ctx.deps.workspaces.save(state.thread, profile.user_id)

resources async

resources(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> tuple[
    OctomateSession | None,
    ReflexSuspender,
    list[AgentCapability[None]],
]

Build fresh gateway, approval and tool context for the selected invocation.

Source code in octomate/reflex/state.py
async def resources(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
) -> tuple[OctomateSession | None, ReflexSuspender, list[AgentCapability[None]]]:
    """Build fresh gateway, approval and tool context for the selected invocation."""
    state = ctx.state
    target = state.target
    source = state.source_target
    selection = state.selection
    if (
        target is None
        or target.address is None
        or source is None
        or source.address is None
        or selection is None
    ):
        raise ValueError(
            "a Reflex run requires a selected agent and resolved source and target addresses"
        )
    agent = ctx.deps.agent(selection.agent_id)
    thread_id = state.thread.id if state.thread else None
    state.summon_routes = [
        route
        for route in ctx.deps.available_routes.get(target.channel_id, [])
        if route.agent_id != agent.id
    ]
    session = await ctx.deps.octomate_session(
        agent,
        user_profile=state.user_profile,
        thread_id=thread_id,
        conversation_address=target.address,
        conversation_id=state.conversation_id,
    )
    if session is not None:
        state.owner_id = session.owner_id
    capabilities: list[AgentCapability[None]] = []
    suspender = ReflexSuspender(
        action_manager=ctx.deps.action_manager,
        conversation_manager=ctx.deps.conversation_manager,
        agent_tentacle_id=agent.id,
        run_name=state.run_name,
        source_address=source.address,
        target_address=target.address,
        target_mode=target.mode,
        decision=state.decision,
        model=selection.model,
        thread_id=thread_id,
    )
    return session, suspender, capabilities

prepare_user async

prepare_user(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    profile: UserProfile,
    *,
    session: OctomateSession | None,
    suspender: ReflexSuspender,
    capabilities: list[AgentCapability[None]],
) -> None

Mount capabilities belonging to the user authorized for this invocation.

Source code in octomate/reflex/state.py
async def prepare_user(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    profile: UserProfile,
    *,
    session: OctomateSession | None,
    suspender: ReflexSuspender,
    capabilities: list[AgentCapability[None]],
) -> None:
    """Mount capabilities belonging to the user authorized for this invocation."""
    ctx.state.user_profile = profile
    if session is not None:
        session.user_profile = profile
    agent = ctx.deps.agent(suspender.agent_tentacle_id)
    capabilities.extend(await agent.user_capabilities(profile))

send async

send(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    event: MessageSentEvent,
) -> bool

Deliver a gateway send to a person's direct messages, when possible: recorded there first, then published for that thread alone.

Source code in octomate/reflex/state.py
async def send(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    event: MessageSentEvent,
) -> bool:
    """Deliver a gateway send to a person's direct messages, when possible:
    recorded there first, then published for that thread alone."""
    destination = event.destination
    if destination is None:
        return False
    channel = ctx.deps.channel(destination.channel_tentacle_id)
    dm = await channel.open_dm(destination.user_id)
    if dm is None:
        logger.warning(
            "Channel %s could not open a DM with %s; delivering the send to %s instead",
            destination.channel_tentacle_id,
            destination.user_id,
            suspender.target_address,
        )
        return False
    message = await ctx.deps.thread_manager.record_outbound(
        dm,
        agent_tentacle_id=suspender.agent_tentacle_id,
        segments=event.segments,
        sender=channel.self_profile,
        owner_id=ctx.state.owner_id,
    )
    sent = MessageSentEvent(
        segments=event.segments, destination=dm, thread_message_id=message.id
    )
    await ctx.deps.impulses.send(Impulse(sent, dm, private=True))
    return True

drive async

drive(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    source: AsyncGenerator[
        ReactStreamEvent[ChannelOutput], None
    ],
) -> AgentRunResult[ChannelOutput]

Run the native invocation onto the nerve, closing it before recording its reply: the run's start before anything it streams, and its end after, carrying the reply's ledger row, whatever happened.

Source code in octomate/reflex/state.py
async def drive(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    source: AsyncGenerator[ReactStreamEvent[ChannelOutput], None],
) -> AgentRunResult[ChannelOutput]:
    """Run the native invocation onto the nerve, closing it before recording
    its reply: the run's start before anything it streams, and its end after,
    carrying the reply's ledger row, whatever happened."""
    results: list[AgentRunResult[ChannelOutput]] = []
    address = suspender.target_address

    async def events() -> AsyncGenerator[ReactStreamEvent[ChannelOutput], None]:
        async for event in source:
            if isinstance(event, AgentRunResultEvent):
                results.append(event.result)
            if isinstance(event, MessageSentEvent) and await self.send(
                ctx, suspender, event
            ):
                continue
            yield event

    await ctx.deps.impulses.send(
        Impulse(
            RunStartedEvent(
                address=address,
                sender=ctx.state.user_profile,
                agent_tentacle_id=suspender.agent_tentacle_id,
            ),
            address,
        )
    )
    ended = RunEndedEvent(outcome="failed")
    try:
        await ctx.deps.impulses.send(
            Impulse(RunActivityChangedEvent(activity="working"), address)
        )
        async with aclosing(source), aclosing(events()) as stream:
            await ctx.deps.carry(address, stream)
        if not results:
            raise RuntimeError(
                f"react stream for {address} completed without a result"
            )
        ctx.state.interruption.check()
        reply = await self.record_reply(ctx, suspender, results[-1])
        ended.thread_message_id = reply.id if reply is not None else None
        ended.outcome = (
            "deferred"
            if isinstance(results[-1].output, DeferredToolRequests)
            else "completed"
        )
        return results[-1]
    except (asyncio.CancelledError, RunInterrupted):
        ended.outcome = "cancelled"
        raise
    finally:
        await ctx.deps.impulses.send(Impulse(ended, address))

record_reply async

record_reply(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    result: AgentRunResult[ChannelOutput],
) -> ThreadMessage | None

Record and bind the run's reply, answering its row for the channel to mark with the platform id it renders the reply as.

Source code in octomate/reflex/state.py
async def record_reply(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    result: AgentRunResult[ChannelOutput],
) -> ThreadMessage | None:
    """Record and bind the run's reply, answering its row for the channel to
    mark with the platform id it renders the reply as."""
    output = result.output
    segments: list[MessageSegment]
    if isinstance(output, str):
        segments = [MarkdownSegment(data={"text": output})] if output else []
    elif isinstance(output, Iterable):
        segments = list(output)
    else:
        return None
    reply_to, body = split_reply(segments)
    message = None
    if body:
        channel = ctx.deps.channels.get(
            suspender.target_address.channel_tentacle_id
        )
        sender = (
            channel.self_profile if channel is not None else ctx.state.user_profile
        )
        message = await ctx.deps.thread_manager.record_outbound(
            suspender.target_address,
            agent_tentacle_id=suspender.agent_tentacle_id,
            segments=segments,
            reply_id=reply_to or "",
            sender=sender,
            raw=output
            if isinstance(output, str)
            else "\n\n".join(str(segment) for segment in body),
            message_text=output if isinstance(output, str) else None,
        )
    await ctx.deps.thread_manager.bind_assistant_replies(
        [message.id] if message is not None else [],
        run_id=result.run_id,
    )
    return message

present_command async

present_command(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    outcome: CommandOutcome,
) -> None

Publish direct feedback; its command receipt already owns the output.

Source code in octomate/reflex/state.py
async def present_command(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    suspender: ReflexSuspender,
    outcome: CommandOutcome,
) -> None:
    """Publish direct feedback; its command receipt already owns the output."""
    segments: list[MessageSegment] = (
        [TextSegment(data={"text": outcome.message})]
        if isinstance(outcome, CommandError)
        else outcome.segments
    )
    if not segments:
        return
    await ctx.deps.impulses.send(
        Impulse(MessageSentEvent(segments=segments), suspender.target_address)
    )

finish async

finish(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    session: OctomateSession | None,
    suspender: ReflexSuspender,
    run_result: AgentRunResult[ChannelOutput],
) -> Summon | Teleport | Scheme | End[ReflexGraphResult]

Follow the gateway decision or deferral left by an actual agent run.

Source code in octomate/reflex/state.py
async def finish(
    self,
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    session: OctomateSession | None,
    suspender: ReflexSuspender,
    run_result: AgentRunResult[ChannelOutput],
) -> Summon | Teleport | Scheme | End[ReflexGraphResult]:
    """Follow the gateway decision or deferral left by an actual agent run."""
    # These nodes import the graph types consumed by this runtime.
    from octomate.reflex.nodes.scheme import Scheme
    from octomate.reflex.nodes.summon import Summon
    from octomate.reflex.nodes.teleport import Teleport

    state = ctx.state
    target = state.target
    if target is None:
        raise ValueError("a Reflex run requires a resolved target")
    decision = state.decision
    agent_id = suspender.agent_tentacle_id
    thread_id = state.thread.id if state.thread else None
    output = run_result.output
    with reflex_logfire.span("reflex.finish", run_id=run_result.run_id) as span:
        if session is not None and session.dismissing and state.thread is not None:
            # The agent said this thread's work is done: its tree goes now
            # that the run is out of it, saved first and kept if that failed.
            result = await ctx.deps.workspaces.dismiss(state.thread, state.owner_id)
            span.set_attribute(
                "react.dismissed",
                result,
            )
        # `teleport` is resolved by the graph (fork + resume), not a human. The
        # suspender classified it by its declared metadata kind and stashed it,
        # so route on the typed request instead of re-scanning tool names.
        if (
            isinstance(output, DeferredToolRequests)
            and suspender.teleport is not None
        ):
            if session is None:
                raise ValueError("Teleport requires an owned Gateway session")
            return Teleport(
                request=suspender.teleport,
                origin=target,
                agent_id=agent_id,
            )
        if isinstance(output, DeferredToolRequests):
            return End(
                DeferredResult(
                    requests=output,
                    target=target,
                    run_name=state.run_name,
                    result=run_result,
                    batch_id=suspender.suspended_batch_id,
                )
            )

        gateway_decision = session.decision if session else None
        if isinstance(gateway_decision, SchemeDecision | SummonDecision):
            # Where this handoff came from, as the row records it: the
            # conversation this turn ran in, as of its last message.
            conversation = (
                await ctx.deps.conversation_manager.ensure(
                    thread_id, agent_tentacle_id=agent_id, with_runs=False
                )
                if thread_id is not None
                else None
            )
            history = (
                await ctx.deps.conversation_manager.history(
                    conversation.id, limit=1
                )
                if conversation is not None
                else []
            )
            last = history[-1] if history else None
            state.handoff = PendingHandoff(
                source_agent_tentacle_id=agent_id,
                source_conversation_id=conversation.id if conversation else None,
                source_run_id=last.run_id if last else None,
                source_model_message_id=last.id if last else None,
            )
        if session is not None and isinstance(gateway_decision, SchemeDecision):
            span.set_attribute("react.action", gateway_decision.action)
            reflex_logfire.info(
                "react -> scheme into the asker's dm",
                destination=str(gateway_decision.destination),
            )
            return Scheme(
                request=gateway_decision,
                origin=target,
                agent_id=agent_id,
            )
        if session is not None and isinstance(gateway_decision, SummonDecision):
            state.decision = gateway_decision
            state.target = target
            state.run_name = "summon"
            span.set_attribute("react.action", gateway_decision.action)
            span.set_attribute("react.next_agent_id", gateway_decision.agent_id)
            reflex_logfire.info(
                "react -> {action} agent={agent_id}",
                action=gateway_decision.action,
                agent_id=gateway_decision.agent_id,
                reason=gateway_decision.reason,
            )
            return Summon()

        return End(
            ReflexResult(
                decision=decision,
                target=target,
                result=run_result,
            )
        )

octomate.reflex.suspender

The reflex graph's deferred suspender: where a run's deferrals go — a teleport back to the graph, everything else to a human as a persisted batch.

TeleportRequest dataclass

A teleport for the graph to perform: carry the history and resume the agent in the new place. One shape for every runtime — an Inkling run defers the teleport call itself; a runtime a tool result cannot suspend is interrupted on the recorded decision and ends its turn as the same deferral — read off the deferred call by its metadata kind.

Source code in octomate/reflex/suspender.py
@dataclass(frozen=True)
class TeleportRequest:
    """A teleport for the graph to perform: carry the history and resume the agent
    in the new place. One shape for every runtime — an Inkling run defers the
    `teleport` call itself; a runtime a tool result cannot suspend is interrupted
    on the recorded decision and ends its turn as the same deferral — read off
    the deferred call by its metadata kind."""

    hint: str
    # The deferred call to resolve into the resumed run.
    tool_call_id: str | None
    # Where the move goes: the chat a new thread opens in, or this conversation.
    destination: ChannelAddress
    new_thread: bool = True
    # The project the thread landed in is bound to, and the ref its workspace starts
    # from; None carries the conversation only.
    project: str | None = None
    ref: str | None = None
    # Whether to resume in a new thread; in-place project binding always resumes.
    resume: bool = False
    # The user's next message where it lands, which the agent answers there.
    prompt: str | None = None

    @classmethod
    def of(cls, requests: DeferredToolRequests) -> TeleportRequest | None:
        """The teleport these requests carry."""
        for call in requests.calls:
            meta = requests.metadata.get(call.tool_call_id, {})
            if meta.get("kind") != TELEPORT_DEFER_KIND:
                continue
            destination = meta.get("destination")
            if not destination:
                raise ValueError("a teleport deferral names no destination")
            return cls(
                tool_call_id=call.tool_call_id,
                hint=str(meta.get("hint") or ""),
                new_thread=bool(meta.get("new_thread", True)),
                project=str(meta.get("project") or "") or None,
                ref=str(meta.get("ref") or "") or None,
                resume=bool(meta.get("resume", False)),
                # The address validates itself, being a pydantic dataclass.
                destination=ChannelAddress(**destination),
            )
        return None

hint instance-attribute

hint: str

tool_call_id instance-attribute

tool_call_id: str | None

destination instance-attribute

destination: ChannelAddress

new_thread class-attribute instance-attribute

new_thread: bool = True

project class-attribute instance-attribute

project: str | None = None

ref class-attribute instance-attribute

ref: str | None = None

resume class-attribute instance-attribute

resume: bool = False

prompt class-attribute instance-attribute

prompt: str | None = None

of classmethod

of(
    requests: DeferredToolRequests,
) -> TeleportRequest | None

The teleport these requests carry.

Source code in octomate/reflex/suspender.py
@classmethod
def of(cls, requests: DeferredToolRequests) -> TeleportRequest | None:
    """The teleport these requests carry."""
    for call in requests.calls:
        meta = requests.metadata.get(call.tool_call_id, {})
        if meta.get("kind") != TELEPORT_DEFER_KIND:
            continue
        destination = meta.get("destination")
        if not destination:
            raise ValueError("a teleport deferral names no destination")
        return cls(
            tool_call_id=call.tool_call_id,
            hint=str(meta.get("hint") or ""),
            new_thread=bool(meta.get("new_thread", True)),
            project=str(meta.get("project") or "") or None,
            ref=str(meta.get("ref") or "") or None,
            resume=bool(meta.get("resume", False)),
            # The address validates itself, being a pydantic dataclass.
            destination=ChannelAddress(**destination),
        )
    return None

ReflexSuspender dataclass

The reflex graph's DeferredSuspender: every deferral a run ends on comes through here once, and each kind goes where it is resolved — a teleport to the graph, which performs it and resumes the agent; anything else to a human, persisted as a batch whose event rides the run's stream, for the channel to present wherever it draws the run from. React builds it with the run's context; Inkling reaches it through ResolveDeferred, a runtime a tool result cannot suspend through the deferred_suspender its run was handed. A runtime that asks a human mid-run pauses here instead, and stays live.

Source code in octomate/reflex/suspender.py
@dataclass
class ReflexSuspender:
    """The reflex graph's `DeferredSuspender`: every deferral a run ends on comes
    through here once, and each kind goes where it is resolved — a `teleport` to
    the graph, which performs it and resumes the agent; anything else to a human,
    persisted as a batch whose event rides the run's stream, for the channel to
    present wherever it draws the run from. React builds it with the
    run's context; Inkling reaches it through `ResolveDeferred`, a runtime a tool
    result cannot suspend through the `deferred_suspender` its run was handed.
    A runtime that asks a human mid-run pauses here instead, and stays live.
    """

    action_manager: DeferredActionManager
    conversation_manager: ConversationManager
    agent_tentacle_id: str
    run_name: RunName
    source_address: ChannelAddress
    target_address: ChannelAddress
    target_mode: ResponseTargetMode
    decision: SummonDecision | None
    model: str | None = None  # Selected model when a command has no routing decision.
    thread_id: UUID7 | None = None
    suspended_batch_id: UUID7 | None = field(default=None, init=False)
    # The deferred `teleport`, for the graph to perform instead of a batch.
    teleport: TeleportRequest | None = field(default=None, init=False)

    def continuation_decision(self) -> SummonDecision:
        """Preserve an actual agent run's selection for resume and teleport."""
        if self.decision is None:
            self.decision = SummonDecision(
                agent_id=self.agent_tentacle_id,
                model=self.model,
                reason="Continue the selected agent run.",
                hint="",
                brief="",
            )
        return self.decision

    async def suspend(self, requests: DeferredToolRequests) -> ActionBatchEvent | None:
        """Record a deferral the caller ends its run on, for later continuation.

        Human actions become a resumable batch recorded in suspended_batch_id;
        a teleport is handed back to the graph without presenting a batch.
        """
        self.continuation_decision()
        teleport = TeleportRequest.of(requests)
        if teleport is not None:
            # The agent's own permission check already let the call through, so
            # nothing here asks: the graph moves it once the run ends.
            if len(requests.calls) + len(requests.approvals) > 1:
                raise RuntimeError("a teleport was deferred beside other calls")
            self.teleport = teleport
            return None
        with reflex_logfire.span(
            "suspend_for_review",
            run_name=self.run_name,
            agent_id=self.agent_tentacle_id,
            target_address=str(self.target_address),
            source_address=str(self.source_address),
        ) as span:
            batch = await self.persist(requests, response_mode="resume")
            self.suspended_batch_id = batch.id
            span.set_attribute("batch_id", str(batch.id))
            return ActionBatchEvent.from_batch(batch, blocks_run=True)

    async def pause(
        self, requests: DeferredToolRequests, *, batch_id: UUID7
    ) -> ActionBatchEvent:
        """Persist a live batch whose reply releases the caller's waiting run.

        The caller owns the waiter for batch_id and waits after presenting the
        returned event. The response continues that run without opening another.
        """
        with reflex_logfire.span(
            "pause_for_review",
            run_name=self.run_name,
            agent_id=self.agent_tentacle_id,
            target_address=str(self.target_address),
        ) as span:
            batch = await self.persist(
                requests, response_mode="live", batch_id=batch_id
            )
            span.set_attribute("batch_id", str(batch.id))
            return ActionBatchEvent.from_batch(batch, blocks_run=True)

    async def request(self, requests: DeferredToolRequests) -> ActionBatchEvent:
        """Persist a resumable batch while the caller keeps running.

        Leave the current run unsuspended; the completed response opens a later
        turn after this run finishes.
        """
        self.continuation_decision()
        batch = await self.persist(requests, response_mode="resume")
        return ActionBatchEvent.from_batch(batch, blocks_run=False)

    async def persist(
        self,
        requests: DeferredToolRequests,
        *,
        response_mode: DeferredResponseMode,
        batch_id: UUID7 | None = None,
    ) -> DeferredActionBatch:
        if self.thread_id is None:
            raise ValueError("deferred review requires a thread_id")
        conversation = await self.conversation_manager.ensure(
            self.thread_id,
            agent_tentacle_id=self.agent_tentacle_id,
        )
        return await self.action_manager.create_batch(
            response_mode=response_mode,
            batch_id=batch_id,
            conversation=conversation,
            agent_tentacle_id=self.agent_tentacle_id,
            run_name=self.run_name,
            source_address=self.source_address,
            target_address=self.target_address,
            target_mode=self.target_mode,
            decision=self.decision,
            requests=requests,
        )

action_manager instance-attribute

action_manager: DeferredActionManager

conversation_manager instance-attribute

conversation_manager: ConversationManager

agent_tentacle_id instance-attribute

agent_tentacle_id: str

run_name instance-attribute

run_name: RunName

source_address instance-attribute

source_address: ChannelAddress

target_address instance-attribute

target_address: ChannelAddress

target_mode instance-attribute

target_mode: ResponseTargetMode

decision instance-attribute

decision: SummonDecision | None

model class-attribute instance-attribute

model: str | None = None

thread_id class-attribute instance-attribute

thread_id: UUID7 | None = None

suspended_batch_id class-attribute instance-attribute

suspended_batch_id: UUID7 | None = field(
    default=None, init=False
)

teleport class-attribute instance-attribute

teleport: TeleportRequest | None = field(
    default=None, init=False
)

continuation_decision

continuation_decision() -> SummonDecision

Preserve an actual agent run's selection for resume and teleport.

Source code in octomate/reflex/suspender.py
def continuation_decision(self) -> SummonDecision:
    """Preserve an actual agent run's selection for resume and teleport."""
    if self.decision is None:
        self.decision = SummonDecision(
            agent_id=self.agent_tentacle_id,
            model=self.model,
            reason="Continue the selected agent run.",
            hint="",
            brief="",
        )
    return self.decision

suspend async

suspend(
    requests: DeferredToolRequests,
) -> ActionBatchEvent | None

Record a deferral the caller ends its run on, for later continuation.

Human actions become a resumable batch recorded in suspended_batch_id; a teleport is handed back to the graph without presenting a batch.

Source code in octomate/reflex/suspender.py
async def suspend(self, requests: DeferredToolRequests) -> ActionBatchEvent | None:
    """Record a deferral the caller ends its run on, for later continuation.

    Human actions become a resumable batch recorded in suspended_batch_id;
    a teleport is handed back to the graph without presenting a batch.
    """
    self.continuation_decision()
    teleport = TeleportRequest.of(requests)
    if teleport is not None:
        # The agent's own permission check already let the call through, so
        # nothing here asks: the graph moves it once the run ends.
        if len(requests.calls) + len(requests.approvals) > 1:
            raise RuntimeError("a teleport was deferred beside other calls")
        self.teleport = teleport
        return None
    with reflex_logfire.span(
        "suspend_for_review",
        run_name=self.run_name,
        agent_id=self.agent_tentacle_id,
        target_address=str(self.target_address),
        source_address=str(self.source_address),
    ) as span:
        batch = await self.persist(requests, response_mode="resume")
        self.suspended_batch_id = batch.id
        span.set_attribute("batch_id", str(batch.id))
        return ActionBatchEvent.from_batch(batch, blocks_run=True)

pause async

pause(
    requests: DeferredToolRequests, *, batch_id: UUID7
) -> ActionBatchEvent

Persist a live batch whose reply releases the caller's waiting run.

The caller owns the waiter for batch_id and waits after presenting the returned event. The response continues that run without opening another.

Source code in octomate/reflex/suspender.py
async def pause(
    self, requests: DeferredToolRequests, *, batch_id: UUID7
) -> ActionBatchEvent:
    """Persist a live batch whose reply releases the caller's waiting run.

    The caller owns the waiter for batch_id and waits after presenting the
    returned event. The response continues that run without opening another.
    """
    with reflex_logfire.span(
        "pause_for_review",
        run_name=self.run_name,
        agent_id=self.agent_tentacle_id,
        target_address=str(self.target_address),
    ) as span:
        batch = await self.persist(
            requests, response_mode="live", batch_id=batch_id
        )
        span.set_attribute("batch_id", str(batch.id))
        return ActionBatchEvent.from_batch(batch, blocks_run=True)

request async

request(requests: DeferredToolRequests) -> ActionBatchEvent

Persist a resumable batch while the caller keeps running.

Leave the current run unsuspended; the completed response opens a later turn after this run finishes.

Source code in octomate/reflex/suspender.py
async def request(self, requests: DeferredToolRequests) -> ActionBatchEvent:
    """Persist a resumable batch while the caller keeps running.

    Leave the current run unsuspended; the completed response opens a later
    turn after this run finishes.
    """
    self.continuation_decision()
    batch = await self.persist(requests, response_mode="resume")
    return ActionBatchEvent.from_batch(batch, blocks_run=False)

persist async

persist(
    requests: DeferredToolRequests,
    *,
    response_mode: DeferredResponseMode,
    batch_id: UUID7 | None = None,
) -> DeferredActionBatch
Source code in octomate/reflex/suspender.py
async def persist(
    self,
    requests: DeferredToolRequests,
    *,
    response_mode: DeferredResponseMode,
    batch_id: UUID7 | None = None,
) -> DeferredActionBatch:
    if self.thread_id is None:
        raise ValueError("deferred review requires a thread_id")
    conversation = await self.conversation_manager.ensure(
        self.thread_id,
        agent_tentacle_id=self.agent_tentacle_id,
    )
    return await self.action_manager.create_batch(
        response_mode=response_mode,
        batch_id=batch_id,
        conversation=conversation,
        agent_tentacle_id=self.agent_tentacle_id,
        run_name=self.run_name,
        source_address=self.source_address,
        target_address=self.target_address,
        target_mode=self.target_mode,
        decision=self.decision,
        requests=requests,
    )

octomate.reflex.crossing

Create a channel-owned destination and announce the move at its origin.

logger module-attribute

logger = logging.getLogger(__name__)

open_crossing async

open_crossing(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    destination: ChannelAddress,
    source_address: ChannelAddress,
    hint_text: str,
    agent_tentacle_id: str,
) -> ChannelAddress | None

Ask the destination channel to create an isolated thread.

The existing opener is recorded with its requesting user so the destination remains visible in their console. No fallback may reuse an existing chat.

Source code in octomate/reflex/crossing.py
async def open_crossing(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    destination: ChannelAddress,
    source_address: ChannelAddress,
    hint_text: str,
    agent_tentacle_id: str,
) -> ChannelAddress | None:
    """Ask the destination channel to create an isolated thread.

    The existing opener is recorded with its requesting user so the destination
    remains visible in their console. No fallback may reuse an existing chat.
    """
    channel = ctx.deps.channel(destination.channel_tentacle_id)
    profile = ctx.state.user_profile
    if profile.channel_tentacle_id != channel.id:
        linked = await ctx.deps.thread_manager.users.profile(
            channel.id, destination.user_id
        )
        if linked is not None and linked.user_id == profile.user_id:
            profile = linked
        elif channel.thread_user_id(profile) != destination.user_id:
            raise ValueError(
                "The destination profile is no longer linked to this user."
            )
    try:
        opened = await channel.start_thread(destination, hint_text)
    except Exception:
        logger.warning(
            "Channel %s could not create the destination thread",
            channel.id,
            exc_info=True,
        )
        return None
    if destination == source_address:
        return opened
    if profile.channel_tentacle_id != channel.id:
        profile = UserProfile(
            channel_tentacle_id=channel.id,
            channel_user_id=opened.user_id,
            user_id=profile.user_id,
            name=profile.name,
            nickname=profile.nickname,
        )
    ctx.state.user_profile = profile
    # Attribute the existing opener so the requesting user can find the destination.
    # Native teleport's transcript fork already publishes its attributed fork notice.
    native_fork = (
        ctx.state.run_name == "teleport"
        and ctx.state.thread is not None
        and ctx.state.thread.kind == "native_thread"
    )
    if not native_fork:
        await ctx.deps.thread_manager.record_outbound(
            opened,
            agent_tentacle_id=agent_tentacle_id,
            sender=ctx.state.user_profile,
            actor_kind="system",
            segments=[MarkdownSegment(data={"text": hint_text})],
        )
    return opened

announce_crossing async

announce_crossing(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    destination: ChannelAddress,
    opened: ChannelAddress,
    source_address: ChannelAddress,
    hint_text: str,
    agent_tentacle_id: str,
) -> None

Leave the move's line in the chat it left, and say where it landed.

Called once the history is carried: a fork shows the source's ledger as it stands, and the line is the source's own, not part of what moved.

Source code in octomate/reflex/crossing.py
async def announce_crossing(
    ctx: GraphRunContext[ReflexState, ReflexDeps],
    destination: ChannelAddress,
    opened: ChannelAddress,
    source_address: ChannelAddress,
    hint_text: str,
    agent_tentacle_id: str,
) -> None:
    """Leave the move's line in the chat it left, and say where it landed.

    Called once the history is carried: a fork shows the source's ledger as it
    stands, and the line is the source's own, not part of what moved.
    """
    if destination == source_address:
        await ctx.deps.record_move(
            source_address,
            hint_text,
            agent_tentacle_id=agent_tentacle_id,
            platform_message_id=opened.channel_thread_id,
        )
        # The thread hangs from its opener there, which is the move's line.
        await ctx.deps.impulses.send(
            Impulse(GatewayEvent(action="teleport", destination=opened), source_address)
        )
        return
    # A native session's pseudo-channel posts no line, and has no one to post it as.
    line = (
        await ctx.deps.record_move(
            source_address, hint_text, agent_tentacle_id=agent_tentacle_id
        )
        if source_address.channel_tentacle_id in ctx.deps.channels
        else None
    )
    await ctx.deps.impulses.send(
        Impulse(
            GatewayEvent(
                action="teleport",
                destination=opened,
                announcement=hint_text,
                thread_message_id=line.id if line is not None else None,
            ),
            source_address,
        )
    )