Skip to content

amphibious

Amphibious Agent Framework — dual-mode (LLM-driven + deterministic) agent orchestration with automatic fallback between the two.

Layers:

  • ContextContext (free-form, big-loop) + OTAContext (small-loop, framework-owned: the run's user_input + OTA round trace + tools). The OTA context declares the tools it carries via OTAContext.tool (decorator or call); nothing is auto-injected.
  • WorkerCognitiveWorker: one in-process observe-think-act cycle, anchored on a BaseLlm; subclass and implement its thinking template method. Symmetric peer: AgentWorker, one external-agent delegation, anchored on a BaseAgent (the external coding-agent abstraction; ClaudeCodeAgent and CodexAgent are the shipped drivers).
  • OrchestrationAmphibiousAutoma + yield primitives (ThinkUnit, ThinkAgent, EnterAgent, ActionCall, HumanCall, LLMCall, RETURN) + think_unit / think_agent descriptors.

class MyThink(CognitiveWorker): ... async def thinking(self, ota_context, context=None): ... return await self._llm.aselect_tool(messages=[...], tools=[...]) class MyAgent(AmphibiousAutoma[OTAContext, Context]): ... main_think = think_unit(MyThink(), max_attempts=20) ... async def on_agent(self, ota_ctx): ... yield ThinkUnit("main_think") ... answer = await MyAgent().arun(llm=llm, user_input="Complete the task")

Context

Bases: BaseModel

Base class for agent context — fields + an overridable summary.

Collapsed (per the small-loop redesign) to its essentials:

  • :meth:_raw_fields — the most primitive view: every field's raw value as {name: value} (no rendering, no filtering).
  • :meth:summary — the overridable method the framework injects with that raw dict. The default returns the dict unchanged; an override is handed the fields dict and composes whatever it wants (usually a str) — without fetching anything itself.

A bare Context is free-form cross-turn state (the big-loop half): declare fields and override summary, and that is all. Tools are not a base-context concern — they belong to the OTA loop that actually acts, so the tool registry (tools field + :meth:~OTAContext.tool / :meth:~OTAContext.add_tool) lives on :class:OTAContext.

Examples:

1
2
3
4
>>> class MyContext(Context):
...     goal: str = ""
...     def summary(self, fields):   # ``fields`` is auto-injected (the raw dict)
...         return f"Goal: {fields['goal']}"
Source code in bridgic/amphibious/_context.py
class Context(BaseModel):
    """
    Base class for agent context — fields + an overridable ``summary``.

    Collapsed (per the small-loop redesign) to its essentials:

    * :meth:`_raw_fields` — the most primitive view: every field's raw value
      as ``{name: value}`` (no rendering, no filtering).
    * :meth:`summary` — the **overridable** method the framework injects with
      that raw dict. The default returns the dict unchanged; an override is
      handed the ``fields`` dict and composes whatever it wants (usually a
      ``str``) — without fetching anything itself.

    A bare ``Context`` is free-form cross-turn state (the big-loop half):
    declare fields and override ``summary``, and that is all. Tools are **not**
    a base-context concern — they belong to the OTA loop that actually acts, so
    the tool registry (``tools`` field + :meth:`~OTAContext.tool` /
    :meth:`~OTAContext.add_tool`) lives on :class:`OTAContext`.

    Examples
    --------
    >>> class MyContext(Context):
    ...     goal: str = ""
    ...     def summary(self, fields):   # ``fields`` is auto-injected (the raw dict)
    ...         return f"Goal: {fields['goal']}"
    """
    model_config = ConfigDict(arbitrary_types_allowed=True)

    ############################################################################
    # Initialize Context
    ############################################################################

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        # A subclass that overrides ``summary`` uses ``fields`` directly.
        if "summary" in cls.__dict__:
            cls.summary = cls._summary_injecting(cls.__dict__["summary"])

    @staticmethod
    def _summary_injecting(user_summary: Callable) -> Callable:
        """
        Wrap an overridden ``summary`` so its ``fields`` argument is always
        the raw per-field dict (built via :meth:`_raw_fields` when omitted).
        """
        @functools.wraps(user_summary)
        def _wrapped(self, fields: Optional[Dict[str, Any]] = None) -> Any:
            if fields is None:
                fields = self._raw_fields()
            return user_summary(self, fields)
        return _wrapped

    def model_post_init(self, __context: Any) -> None:
        super().model_post_init(__context)

        # Call __post_init__ if defined in subclass (provides dataclass-like API)
        if hasattr(self, '__post_init__') and callable(getattr(self, '__post_init__')):
            self.__post_init__()

    ############################################################################
    # Core Methods
    ############################################################################

    def _raw_fields(self) -> Dict[str, Any]:
        """Every model field's raw value, unprocessed: ``{name: value}``.

        No rendering, no per-field summarising, no filtering — the most
        primitive view of the context. This is the dict the framework hands
        to :meth:`summary`.
        """
        return {name: getattr(self, name) for name in type(self).model_fields}

    def summary(self, fields: Optional[Dict[str, Any]] = None) -> Any:
        """Assemble this context for the prompt (the **overridable** method).

        An overridden ``summary`` is auto-wrapped (see :meth:`__init_subclass__`)
        so ``fields`` is always the raw per-field dict (:meth:`_raw_fields`) — the
        override just uses it (``fields.get(...)``) and composes whatever it wants
        (typically a ``str``), with zero manual fetch. The default (no override)
        returns the raw dict unchanged.

        Parameters
        ----------
        fields : Optional[Dict[str, Any]]
            The raw per-field dict, auto-injected into an overridden ``summary``.

        Returns
        -------
        Any
            The raw dict by default, or whatever an override composes.
        """
        return fields if fields is not None else self._raw_fields()

    def __iter__(self) -> Iterator[Tuple[str, Any]]:
        """Yield ``(field_name, field_value)`` for every model field on this context."""
        for field_name in type(self).model_fields:
            yield field_name, getattr(self, field_name)

    def __str__(self) -> str:
        """Return a formatted, human-readable view of every field."""
        lines = [f"{'=' * 50}", f"  {self.__class__.__name__}", f"{'=' * 50}"]
        for field_name in self.__class__.model_fields:
            value = getattr(self, field_name)
            if value is not None:
                lines.append(f"\n[{field_name}]")
                lines.append(f"  {value}")
        lines.append(f"\n{'=' * 50}")
        return "\n".join(lines)

    def __repr__(self) -> str:
        """Return a concise representation of the context."""
        parts = []
        for field_name in self.__class__.model_fields:
            value = getattr(self, field_name)
            if value is not None:
                parts.append(f"{field_name}={value!r}")
        return f"{self.__class__.__name__}({', '.join(parts)})"

summary

summary(fields: Optional[Dict[str, Any]] = None) -> Any

Assemble this context for the prompt (the overridable method).

An overridden summary is auto-wrapped (see :meth:__init_subclass__) so fields is always the raw per-field dict (:meth:_raw_fields) — the override just uses it (fields.get(...)) and composes whatever it wants (typically a str), with zero manual fetch. The default (no override) returns the raw dict unchanged.

Parameters:

Name Type Description Default
fields Optional[Dict[str, Any]]

The raw per-field dict, auto-injected into an overridden summary.

None

Returns:

Type Description
Any

The raw dict by default, or whatever an override composes.

Source code in bridgic/amphibious/_context.py
def summary(self, fields: Optional[Dict[str, Any]] = None) -> Any:
    """Assemble this context for the prompt (the **overridable** method).

    An overridden ``summary`` is auto-wrapped (see :meth:`__init_subclass__`)
    so ``fields`` is always the raw per-field dict (:meth:`_raw_fields`) — the
    override just uses it (``fields.get(...)``) and composes whatever it wants
    (typically a ``str``), with zero manual fetch. The default (no override)
    returns the raw dict unchanged.

    Parameters
    ----------
    fields : Optional[Dict[str, Any]]
        The raw per-field dict, auto-injected into an overridden ``summary``.

    Returns
    -------
    Any
        The raw dict by default, or whatever an override composes.
    """
    return fields if fields is not None else self._raw_fields()

OTAContext

Bases: Context

Small-loop working context: one run's input + its OTA round trace + tools.

The framework-owned half of the two-loop model. During a run the automa drives it directly through the per-round result accessors (ota_ctx.obs_result = ... / .think_result / .action_result), :meth:open_record, and :meth:add_tool. Each round is one :class:OTARecord (observe/think/action results, extra="allow" so a before_action / after_action hook can fold custom per-round fields like a permission_result via :meth:_current_record).

Its tools are declared on the class via :meth:tool — the registry lives here, not on the base :class:Context, because tools are an OTA-loop concern. The framework no longer merges any tools in; whatever the context declares is what the small loop carries.

Attributes:

Name Type Description
user_input Any

This run's question / objective. Any payload — a plain str, or a structured input the agent's own hooks (e.g. observation) parse. Framework built-ins only str() it for default rendering / tracing.

ota_record List[OTARecord]

The observe-think-act round trace (one :class:OTARecord per round).

Examples:

1
2
3
4
5
>>> ota = OTAContext(user_input="Find the bug")
>>> ota.open_record()                  # framework brackets each OTA cycle
>>> ota.obs_result = "saw a stack trace"
>>> ota.think_result = decision
>>> ota.action_result = tool_output
Source code in bridgic/amphibious/_context.py
class OTAContext(Context):
    """Small-loop working context: one run's input + its OTA round trace + tools.

    The **framework-owned** half of the two-loop model. During a run the
    automa drives it directly through the per-round result accessors
    (``ota_ctx.obs_result = ...`` / ``.think_result`` / ``.action_result``),
    :meth:`open_record`, and :meth:`add_tool`. Each round is one
    :class:`OTARecord` (observe/think/action results, ``extra="allow"`` so a
    ``before_action`` / ``after_action`` hook can fold custom per-round fields
    like a ``permission_result`` via :meth:`_current_record`).

    Its ``tools`` are **declared on the class** via :meth:`tool` — the registry
    lives here, not on the base :class:`Context`, because tools are an OTA-loop
    concern. The framework no longer merges any tools in; whatever the context
    declares is what the small loop carries.

    Attributes
    ----------
    user_input : Any
        This run's question / objective. Any payload — a plain ``str``, or a
        structured input the agent's own hooks (e.g. ``observation``) parse.
        Framework built-ins only ``str()`` it for default rendering / tracing.
    ota_record : List[OTARecord]
        The observe-think-act round trace (one :class:`OTARecord` per round).

    Examples
    --------
    >>> ota = OTAContext(user_input="Find the bug")
    >>> ota.open_record()                  # framework brackets each OTA cycle
    >>> ota.obs_result = "saw a stack trace"
    >>> ota.think_result = decision
    >>> ota.action_result = tool_output
    """
    _declared_tools: ClassVar[List[ToolSpec]] = []  # Tools declared on this class via ``tool`` (per-subclass, inherits bases).

    user_input: Any = Field(
        default="",
        description=(
            "This run's question / objective. Any payload — the agent's hooks "
            "interpret it; framework built-ins only ``str()`` it (default render)."
        ),
    )
    ota_record: List[OTARecord] = Field(
        default_factory=list,
        description="Observe-think-act round trace (one OTARecord per round)",
    )
    tools: List[ToolSpec] = Field(
        default_factory=list,
        description="Action-phase tool affordances carried by this OTA run",
    )

    ############################################################################
    # Tool registry (action-phase affordances the OTA loop carries)
    ############################################################################
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        # A subclass inherits its bases' declared tools and can add more via its own ``tool`` calls.
        seeded: List[ToolSpec] = []
        seen: set = set()
        for base in cls.__bases__:
            for spec in getattr(base, "_declared_tools", []):
                if spec.tool_name in seen:
                    continue
                seen.add(spec.tool_name)
                seeded.append(spec)
        cls._declared_tools = seeded

    @classmethod
    def tool(cls, obj):
        """Declare a tool on this OTA context — usable as a decorator **and** a call.

        Every context now declares the tools it carries; nothing is
        auto-injected by the framework. ``obj`` is normalized by
        :func:`_to_tool_spec` and appended to this class's
        :attr:`_declared_tools`. The original ``obj`` is returned so this works
        transparently as a decorator.

        * ``@MyOTACtx.tool`` on a standalone ``def f(...)`` — registers ``f``,
          returns ``f``.
        * ``MyOTACtx.tool(bash_tool)`` — registers an existing :class:`ToolSpec`.
        * ``MyOTACtx.tool(obj.method)`` — registers a bound method, keeping
          ``obj`` as its ``self`` (see :func:`_to_tool_spec`).

        Parameters
        ----------
        obj : Callable | ToolSpec
            A plain callable, a bound method, or an existing tool spec.

        Returns
        -------
        Callable | ToolSpec
            ``obj`` unchanged, so this may be used as a decorator.
        """
        cls._declared_tools.append(_to_tool_spec(obj))
        return obj

    def add_tool(self, tool: ToolSpec) -> None:
        """Register a tool into this run's action-phase toolset."""
        self.tools.append(tool)

    def model_post_init(self, __context: Any) -> None:
        # Seed this run's toolset from the class's declared tools before the
        # base hook fires, so a subclass ``__post_init__`` can rely on it. An
        # explicit ``tools=`` (e.g. a narrowed delegation set) is preserved.
        if not self.tools:
            self.tools = list(type(self)._declared_tools)
        super().model_post_init(__context)

    ############################################################################
    # Round lifecycle + per-round result accessors
    ############################################################################
    def _current_record(self) -> OTARecord:
        """The in-flight (latest) round; opens one lazily if none exists yet.

        This is the record the result accessors write to, and the fold-point
        hooks attach custom fields onto (e.g.
        ``ota_ctx._current_record().permission_result = verdict``).
        """
        if not self.ota_record:
            self.open_record()
        return self.ota_record[-1]

    def open_record(self) -> None:
        """Explicitly open a new round (append a new record to the trace)."""
        self.ota_record.append(OTARecord())

    @property
    def obs_result(self) -> Any:
        return self.ota_record[-1].observation_result if self.ota_record else None

    @obs_result.setter
    def obs_result(self, value: Any) -> None:
        self._current_record().observation_result = value

    @property
    def think_result(self) -> Any:
        return self.ota_record[-1].think_result if self.ota_record else None

    @think_result.setter
    def think_result(self, value: Any) -> None:
        self._current_record().think_result = value

    @property
    def action_result(self) -> Any:
        return self.ota_record[-1].action_result if self.ota_record else None

    @action_result.setter
    def action_result(self, value: Any) -> None:
        self._current_record().action_result = value

    ############################################################################
    # Prompt rendering (overridable)
    ############################################################################
    def summary(self, fields: Optional[Dict[str, Any]] = None) -> str:
        """Render this run's small-loop state for the prompt.

        Default: the user input + the OTA round trace. ``fields`` is the
        auto-injected raw dict (available to an override that prefers it);
        subclass and override to customise how the run is summarised.

        Returns
        -------
        str
            A prompt-facing rendering of the input + round trace.
        """
        parts: List[str] = [f"User input: {self.user_input}"]
        for i, record in enumerate(self.ota_record):
            parts.append(f"[Round {i}]")
            if record.observation_result is not None:
                parts.append(f"  Observation: {record.observation_result}")
            if record.think_result is not None:
                parts.append(f"  Think: {record.think_result}")
            if record.action_result is not None:
                parts.append(f"  Action: {record.action_result}")
            for key, value in (getattr(record, "model_extra", None) or {}).items():
                parts.append(f"  {key}: {value}")
        return "\n".join(parts)

tool

classmethod
tool(obj)

Declare a tool on this OTA context — usable as a decorator and a call.

Every context now declares the tools it carries; nothing is auto-injected by the framework. obj is normalized by :func:_to_tool_spec and appended to this class's :attr:_declared_tools. The original obj is returned so this works transparently as a decorator.

  • @MyOTACtx.tool on a standalone def f(...) — registers f, returns f.
  • MyOTACtx.tool(bash_tool) — registers an existing :class:ToolSpec.
  • MyOTACtx.tool(obj.method) — registers a bound method, keeping obj as its self (see :func:_to_tool_spec).

Parameters:

Name Type Description Default
obj Callable | ToolSpec

A plain callable, a bound method, or an existing tool spec.

required

Returns:

Type Description
Callable | ToolSpec

obj unchanged, so this may be used as a decorator.

Source code in bridgic/amphibious/_context.py
@classmethod
def tool(cls, obj):
    """Declare a tool on this OTA context — usable as a decorator **and** a call.

    Every context now declares the tools it carries; nothing is
    auto-injected by the framework. ``obj`` is normalized by
    :func:`_to_tool_spec` and appended to this class's
    :attr:`_declared_tools`. The original ``obj`` is returned so this works
    transparently as a decorator.

    * ``@MyOTACtx.tool`` on a standalone ``def f(...)`` — registers ``f``,
      returns ``f``.
    * ``MyOTACtx.tool(bash_tool)`` — registers an existing :class:`ToolSpec`.
    * ``MyOTACtx.tool(obj.method)`` — registers a bound method, keeping
      ``obj`` as its ``self`` (see :func:`_to_tool_spec`).

    Parameters
    ----------
    obj : Callable | ToolSpec
        A plain callable, a bound method, or an existing tool spec.

    Returns
    -------
    Callable | ToolSpec
        ``obj`` unchanged, so this may be used as a decorator.
    """
    cls._declared_tools.append(_to_tool_spec(obj))
    return obj

add_tool

add_tool(tool: ToolSpec) -> None

Register a tool into this run's action-phase toolset.

Source code in bridgic/amphibious/_context.py
def add_tool(self, tool: ToolSpec) -> None:
    """Register a tool into this run's action-phase toolset."""
    self.tools.append(tool)

open_record

open_record() -> None

Explicitly open a new round (append a new record to the trace).

Source code in bridgic/amphibious/_context.py
def open_record(self) -> None:
    """Explicitly open a new round (append a new record to the trace)."""
    self.ota_record.append(OTARecord())

summary

summary(fields: Optional[Dict[str, Any]] = None) -> str

Render this run's small-loop state for the prompt.

Default: the user input + the OTA round trace. fields is the auto-injected raw dict (available to an override that prefers it); subclass and override to customise how the run is summarised.

Returns:

Type Description
str

A prompt-facing rendering of the input + round trace.

Source code in bridgic/amphibious/_context.py
def summary(self, fields: Optional[Dict[str, Any]] = None) -> str:
    """Render this run's small-loop state for the prompt.

    Default: the user input + the OTA round trace. ``fields`` is the
    auto-injected raw dict (available to an override that prefers it);
    subclass and override to customise how the run is summarised.

    Returns
    -------
    str
        A prompt-facing rendering of the input + round trace.
    """
    parts: List[str] = [f"User input: {self.user_input}"]
    for i, record in enumerate(self.ota_record):
        parts.append(f"[Round {i}]")
        if record.observation_result is not None:
            parts.append(f"  Observation: {record.observation_result}")
        if record.think_result is not None:
            parts.append(f"  Think: {record.think_result}")
        if record.action_result is not None:
            parts.append(f"  Action: {record.action_result}")
        for key, value in (getattr(record, "model_extra", None) or {}).items():
            parts.append(f"  {key}: {value}")
    return "\n".join(parts)

CognitiveWorker

Bases: GraphAutoma

Cognitive worker — one observe-think-act cycle.

Observation and action execution are handled by AmphibiousAutoma as shared infrastructure. The worker owns one thing: the thinking step.

:meth:thinking is abstract — subclass and implement it to assemble the prompt from the two contexts and call self._llm (chat / tool-select / structured output); whatever you return, :meth:_assemble_decision adapts into the framework's decision. Optional hooks observation / before_action / after_action refine the cycle further.

class MyThink(CognitiveWorker): ... async def thinking(self, ota_context, context=None): ... return await self._llm.aselect_tool( ... messages=build_messages(ota_context), ... tools=[t.to_tool() for t in ota_context.tools], ... )

Source code in bridgic/amphibious/_cognitive_worker.py
class CognitiveWorker(GraphAutoma):
    """Cognitive worker — one observe-think-act cycle.

    Observation and action execution are handled by ``AmphibiousAutoma`` as
    shared infrastructure. The worker owns one thing: the **thinking** step.

    :meth:`thinking` is abstract — subclass and implement it to assemble the
    prompt from the two contexts and call ``self._llm`` (chat / tool-select /
    structured output); whatever you return, :meth:`_assemble_decision`
    adapts into the framework's decision. Optional hooks ``observation`` /
    ``before_action`` / ``after_action`` refine the cycle further.

    >>> class MyThink(CognitiveWorker):
    ...     async def thinking(self, ota_context, context=None):
    ...         return await self._llm.aselect_tool(
    ...             messages=build_messages(ota_context),
    ...             tools=[t.to_tool() for t in ota_context.tools],
    ...         )
    """

    def __init__(
        self,
        llm: Optional[BaseLlm] = None,
        verbose: Optional[bool] = None,
    ):
        super().__init__()

        # LLM
        self._llm = llm

        # Log
        self._verbose = verbose

        # Usage stats
        self.spent_tokens = 0
        self.spent_time = 0

    ############################################################################
    # Core methods
    ############################################################################

    @worker(is_start=True, is_output=True)
    async def _thinking(self, ota_context: Optional[OTAContext] = None, context: Optional[Context] = None) -> Any:
        """Framework entry for the thinking phase — orchestrates :meth:`thinking`.

        Both contexts are injected by the dispatcher
        (``arun(ota_context=…, context=…)``): ``ota_context`` is the
        small-loop OTA state, ``context`` the free-form knowledge (``None``
        for a pure-reasoning run). Validates the LLM, calls the overridable
        :meth:`thinking` method to interact with the LLM, then *adapts* its
        result — ``(tool_calls, content)``, a structured ``BaseModel``, or
        text — into the framework's decision shape (see
        :meth:`_assemble_decision`). That decision becomes the ``arun()``
        return value — the driver captures it and runs the act phase.

        The seam: ``thinking`` owns *talking to the model*, the framework
        owns *turning the reply into a decision*.
        """
        if self._llm is None:
            raise RuntimeError(
                "CognitiveWorker has no LLM set — pass llm= when constructing "
                "the worker."
            )
        if ota_context is None:
            ota_context = OTAContext()

        result = await self.thinking(ota_context, context)
        return self._assemble_decision(result)

    def _assemble_decision(self, result: Any) -> ThinkResult:
        """Adapt whatever :meth:`thinking` returned into the act phase's decision.

        The single seam between *any* bridgic LLM protocol and
        ``AmphibiousAutoma``'s dispatch: ``thinking`` calls the model however
        it likes and hands back that call's **natural** result; this maps each
        protocol's real return shape (see ``bridgic.llms.*``) onto a decision:

        Every shape collapses to a flat ``ThinkResult`` (``step_content`` +
        ``tool_calls``); a result with NO ``tool_calls`` IS the finish:

        - ``Response``                 [``achat``]
          -> content-only (``step_content`` = the reply text).
        - ``(tool_calls, content)``    [``aselect_tool``]
          -> tool-calling (``step_content`` = content). NOTE the order —
          ``aselect_tool`` returns ``tool_calls`` first.
        - a pydantic ``BaseModel`` / ``dict``  [``astructured_output``]
          -> content-only; the structured value is serialized into
          ``step_content`` (JSON).
        - a ``str``                    [plain text / an accumulated stream]
          -> content-only.

        Tool-call items may be ``ToolCall`` objects (``.name`` / ``.arguments``)
        or ``{"name": ..., "arguments": {...}}`` dicts.
        """
        # chat — a Response (text in .message.content). Checked before
        # BaseModel because Response *is* a BaseModel.
        if isinstance(result, Response):
            return ThinkResult(step_content=result.message.content or "", tool_calls=[])

        # structured output — a pydantic model or a json-schema dict; the
        # typed value is serialized into ``step_content`` (which is text).
        if isinstance(result, BaseModel):
            return ThinkResult(step_content=result.model_dump_json(), tool_calls=[])
        if isinstance(result, dict):
            return ThinkResult(
                step_content=json.dumps(result, ensure_ascii=False, default=str),
                tool_calls=[],
            )

        # plain text / an accumulated stream.
        if isinstance(result, str):
            return ThinkResult(step_content=result, tool_calls=[])

        # tool-select — (tool_calls, content), aselect_tool's native order.
        if not isinstance(result, (tuple, list)):
            raise TypeError(
                f"thinking() returned an unsupported type {type(result).__name__}; "
                "return a Response, (tool_calls, content), a pydantic BaseModel, "
                "a dict, or str."
            )
        tool_calls, content = result
        tool_calls = tool_calls or []
        tool_calls = [
            StepToolCall(
                call_id=self._tool_call_id(call),
                tool=self._tool_call_name(call),
                tool_arguments=[
                    ToolArgument(name=str(name), value=value)
                    for name, value in self._tool_call_args(call).items()
                ],
            )
            for call in tool_calls
        ]
        return ThinkResult(step_content=content or "", tool_calls=tool_calls)

    ############################################################################
    # Internal helpers
    ############################################################################

    @staticmethod
    def _tool_call_id(call: Any) -> Optional[str]:
        """Read a tool call id from common provider/adapter shapes."""
        if isinstance(call, dict):
            for key in ("id", "call_id", "tool_call_id"):
                value = call.get(key)
                if value:
                    return str(value)
            return None

        for attr in ("id", "call_id", "tool_call_id"):
            value = getattr(call, attr, None)
            if value:
                return str(value)
        return None

    @staticmethod
    def _tool_call_name(call: Any) -> str:
        """Read a tool call's name — accepts an object (``.name``) or a dict."""
        return call["name"] if isinstance(call, dict) else call.name

    @staticmethod
    def _tool_call_args(call: Any) -> Dict[str, Any]:
        """Read a tool call's arguments — accepts an object (``.arguments``) or a dict."""
        args = call.get("arguments") if isinstance(call, dict) else call.arguments
        return args or {}

    def _clone(self) -> "CognitiveWorker":
        """Return a fresh worker with the same configuration.

        The ``BaseLlm`` is *shared* across clones — it is stateless per
        call — so the clone is built with ``llm=None`` and the agent sets
        the LLM at runtime. Only config (verbose) is carried over; runtime
        state (tokens, time, GraphAutoma execution state) starts clean.
        Subclasses with extra ``__init__`` params should override.

        Used by ``ThinkUnitDescriptor._clone_worker`` for state isolation
        at every ``yield ThinkUnit(...)``.
        """
        return type(self)(
            llm=None,
            verbose=self._verbose,
        )

    ############################################################################
    # Template Methods
    ############################################################################

    async def observation(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
        """Worker-level observation hook. Override to customize.

        Both forms accepted: coroutine (``return _DELEGATE`` /
        ``return value``) or async-generator (yield side-effect calls,
        then ``yield RETURN(value)``).

        Returning ``_DELEGATE`` (or ``None``) hands off to
        ``AmphibiousAutoma.observation()``. Other values become the
        observation directly.

        >>> async def observation(self, ota_context):
        ...     return f"Current state: {ota_context.user_input}"
        """
        return _DELEGATE

    async def thinking(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
        """Assemble context, call the model, return its result. **Override this.**

        The worker's one job and override point: turn the two contexts into a
        prompt and call ``self._llm`` however the model needs, then return that
        call's **natural** result — :meth:`_assemble_decision` adapts it. Just
        return what the bridgic protocol hands you:

        - ``achat`` -> a ``Response`` (content-only, finished).
        - ``aselect_tool`` -> ``(tool_calls, content)``.
        - ``astructured_output`` -> a pydantic ``BaseModel`` or a ``dict``.
        - ``astream`` -> consume the ``MessageChunk`` deltas yourself (forward
          them to a live callback if you want), then return the accumulated
          ``str`` (or a ``Response``).

        Two-loop inputs: ``ota_context`` is the small-loop OTA context (its
        ``user_input`` + ``ota_record`` round trace form the task, its
        ``tools`` list the action affordances); ``context`` is the free-form
        knowledge context (``None`` for a pure-reasoning run).

        >>> async def thinking(self, ota_context, context=None):
        ...     msgs = my_messages(ota_context, context)
        ...     return await self._llm.aselect_tool(messages=msgs, tools=...)
        """
        raise NotImplementedError(
            "CognitiveWorker.thinking must be overridden: assemble the prompt "
            "from the two contexts, call self._llm, and return "
            "(tool_calls, content), a pydantic BaseModel, or text."
        )

    async def before_action(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
        """Worker-level before_action hook. Override to intercept the decision.

        No decision argument — the pending decision is already on the current
        OTA round: read it from ``ota_context.think_result``. Return
        ``_DELEGATE`` / ``None`` to chain to the agent-level hook; return any
        other value (or ``yield RETURN(...)``) to override the decision before
        the act phase runs.
        """
        return _DELEGATE

    async def after_action(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
        """Worker-level after_action hook. Override for side-effects.

        No result argument — the action result is already on the current OTA
        round: read it from ``ota_context.action_result``. The return value is
        a control signal: ``_DELEGATE`` / ``None`` chains to the agent-level
        hook; any other value suppresses it. Folding extra fields onto
        ``ota_context`` is the framework's one sanctioned in-place seam (the
        round trace is mutated by design); do not rely on mutating
        user-supplied data elsewhere.
        """
        return _DELEGATE

    ############################################################################
    # Entry point
    ############################################################################

    async def arun(
        self,
        *args: Any,
        feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
        **kwargs: Any,
    ) -> Any:
        """Execute the thinking phase. The automa runs the observe step first; this round's observation is on the latest ``OTARecord`` (read via ``.obs_result``)."""
        start_time = time.monotonic()
        result = await super().arun(*args, feedback_data=feedback_data, **kwargs)
        self.spent_time += time.monotonic() - start_time
        return result

observation

async
observation(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level observation hook. Override to customize.

Both forms accepted: coroutine (return _DELEGATE / return value) or async-generator (yield side-effect calls, then yield RETURN(value)).

Returning _DELEGATE (or None) hands off to AmphibiousAutoma.observation(). Other values become the observation directly.

async def observation(self, ota_context): ... return f"Current state: {ota_context.user_input}"

Source code in bridgic/amphibious/_cognitive_worker.py
async def observation(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
    """Worker-level observation hook. Override to customize.

    Both forms accepted: coroutine (``return _DELEGATE`` /
    ``return value``) or async-generator (yield side-effect calls,
    then ``yield RETURN(value)``).

    Returning ``_DELEGATE`` (or ``None``) hands off to
    ``AmphibiousAutoma.observation()``. Other values become the
    observation directly.

    >>> async def observation(self, ota_context):
    ...     return f"Current state: {ota_context.user_input}"
    """
    return _DELEGATE

thinking

async
thinking(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Assemble context, call the model, return its result. Override this.

The worker's one job and override point: turn the two contexts into a prompt and call self._llm however the model needs, then return that call's natural result — :meth:_assemble_decision adapts it. Just return what the bridgic protocol hands you:

  • achat -> a Response (content-only, finished).
  • aselect_tool -> (tool_calls, content).
  • astructured_output -> a pydantic BaseModel or a dict.
  • astream -> consume the MessageChunk deltas yourself (forward them to a live callback if you want), then return the accumulated str (or a Response).

Two-loop inputs: ota_context is the small-loop OTA context (its user_input + ota_record round trace form the task, its tools list the action affordances); context is the free-form knowledge context (None for a pure-reasoning run).

async def thinking(self, ota_context, context=None): ... msgs = my_messages(ota_context, context) ... return await self._llm.aselect_tool(messages=msgs, tools=...)

Source code in bridgic/amphibious/_cognitive_worker.py
async def thinking(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
    """Assemble context, call the model, return its result. **Override this.**

    The worker's one job and override point: turn the two contexts into a
    prompt and call ``self._llm`` however the model needs, then return that
    call's **natural** result — :meth:`_assemble_decision` adapts it. Just
    return what the bridgic protocol hands you:

    - ``achat`` -> a ``Response`` (content-only, finished).
    - ``aselect_tool`` -> ``(tool_calls, content)``.
    - ``astructured_output`` -> a pydantic ``BaseModel`` or a ``dict``.
    - ``astream`` -> consume the ``MessageChunk`` deltas yourself (forward
      them to a live callback if you want), then return the accumulated
      ``str`` (or a ``Response``).

    Two-loop inputs: ``ota_context`` is the small-loop OTA context (its
    ``user_input`` + ``ota_record`` round trace form the task, its
    ``tools`` list the action affordances); ``context`` is the free-form
    knowledge context (``None`` for a pure-reasoning run).

    >>> async def thinking(self, ota_context, context=None):
    ...     msgs = my_messages(ota_context, context)
    ...     return await self._llm.aselect_tool(messages=msgs, tools=...)
    """
    raise NotImplementedError(
        "CognitiveWorker.thinking must be overridden: assemble the prompt "
        "from the two contexts, call self._llm, and return "
        "(tool_calls, content), a pydantic BaseModel, or text."
    )

before_action

async
before_action(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level before_action hook. Override to intercept the decision.

No decision argument — the pending decision is already on the current OTA round: read it from ota_context.think_result. Return _DELEGATE / None to chain to the agent-level hook; return any other value (or yield RETURN(...)) to override the decision before the act phase runs.

Source code in bridgic/amphibious/_cognitive_worker.py
async def before_action(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
    """Worker-level before_action hook. Override to intercept the decision.

    No decision argument — the pending decision is already on the current
    OTA round: read it from ``ota_context.think_result``. Return
    ``_DELEGATE`` / ``None`` to chain to the agent-level hook; return any
    other value (or ``yield RETURN(...)``) to override the decision before
    the act phase runs.
    """
    return _DELEGATE

after_action

async
after_action(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level after_action hook. Override for side-effects.

No result argument — the action result is already on the current OTA round: read it from ota_context.action_result. The return value is a control signal: _DELEGATE / None chains to the agent-level hook; any other value suppresses it. Folding extra fields onto ota_context is the framework's one sanctioned in-place seam (the round trace is mutated by design); do not rely on mutating user-supplied data elsewhere.

Source code in bridgic/amphibious/_cognitive_worker.py
async def after_action(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
    """Worker-level after_action hook. Override for side-effects.

    No result argument — the action result is already on the current OTA
    round: read it from ``ota_context.action_result``. The return value is
    a control signal: ``_DELEGATE`` / ``None`` chains to the agent-level
    hook; any other value suppresses it. Folding extra fields onto
    ``ota_context`` is the framework's one sanctioned in-place seam (the
    round trace is mutated by design); do not rely on mutating
    user-supplied data elsewhere.
    """
    return _DELEGATE

arun

async
arun(
    *args: Any,
    feedback_data: Optional[
        Union[
            InteractionFeedback, List[InteractionFeedback]
        ]
    ] = None,
    **kwargs: Any
) -> Any

Execute the thinking phase. The automa runs the observe step first; this round's observation is on the latest OTARecord (read via .obs_result).

Source code in bridgic/amphibious/_cognitive_worker.py
async def arun(
    self,
    *args: Any,
    feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
    **kwargs: Any,
) -> Any:
    """Execute the thinking phase. The automa runs the observe step first; this round's observation is on the latest ``OTARecord`` (read via ``.obs_result``)."""
    start_time = time.monotonic()
    result = await super().arun(*args, feedback_data=feedback_data, **kwargs)
    self.spent_time += time.monotonic() - start_time
    return result

AgentWorker

Bases: GraphAutoma

External-agent worker — one delegated cycle.

Concrete class, peer of CognitiveWorker. Anchored on a BaseAgent (its BASE, exactly as CognitiveWorker is anchored on a BaseLlm): the worker only ever calls self._agent.run(); the BaseAgent owns how the CLI is actually driven.

Constructor

agent : BaseAgent The external coding-agent driver (ClaudeCodeAgent, …). verbose : Optional[bool] Logging override (None = inherit from AmphibiousAutoma). verbose_prompt : Optional[bool] When truthy, log the assembled message before each delegation.

No goal / tools / skills / history knobs — those are all carried by the contexts the framework passes in, and read straight from them (thinking() reads ota_context.user_input etc.).

Customize by subclassing and overriding the template methods — thinking (assemble the message), observation, before_action, after_action. The default thinking already produces a sensible message, so AgentWorker(agent) works out of the box with no subclass.

reviewer = think_agent(AgentWorker( ... ClaudeCodeAgent(allowed_builtin_tools=["Read", "Grep"]), ... ))

class StrictReviewer(AgentWorker): ... async def thinking(self, ota_context, context=None): ... base = await super().thinking(ota_context, context) ... return base + "\n\nBe extremely thorough."

Source code in bridgic/amphibious/_agent_worker.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class AgentWorker(GraphAutoma):
    """External-agent worker — one delegated cycle.

    Concrete class, peer of ``CognitiveWorker``. Anchored on a
    ``BaseAgent`` (its BASE, exactly as ``CognitiveWorker`` is anchored
    on a ``BaseLlm``): the worker only ever calls ``self._agent.run()``;
    the ``BaseAgent`` owns how the CLI is actually driven.

    Constructor
    -----------
    agent : BaseAgent
        The external coding-agent driver (``ClaudeCodeAgent``, …).
    verbose : Optional[bool]
        Logging override (``None`` = inherit from ``AmphibiousAutoma``).
    verbose_prompt : Optional[bool]
        When truthy, log the assembled message before each delegation.

    No ``goal`` / ``tools`` / ``skills`` / ``history`` knobs — those are
    all carried by the contexts the framework passes in, and read
    straight from them (``thinking()`` reads ``ota_context.user_input``
    etc.).

    Customize by subclassing and overriding the template methods —
    ``thinking`` (assemble the message), ``observation``,
    ``before_action``, ``after_action``. The default ``thinking``
    already produces a sensible message, so ``AgentWorker(agent)`` works
    out of the box with no subclass.

    >>> reviewer = think_agent(AgentWorker(
    ...     ClaudeCodeAgent(allowed_builtin_tools=["Read", "Grep"]),
    ... ))
    >>>
    >>> class StrictReviewer(AgentWorker):
    ...     async def thinking(self, ota_context, context=None):
    ...         base = await super().thinking(ota_context, context)
    ...         return base + "\\n\\nBe extremely thorough."
    """

    def __init__(
        self,
        agent: BaseAgent,
        *,
        verbose: Optional[bool] = None,
        verbose_prompt: Optional[bool] = None,
    ) -> None:
        super().__init__()

        if not isinstance(agent, BaseAgent):
            raise TypeError(
                f"AgentWorker(agent, ...) requires a BaseAgent instance; "
                f"got {type(agent).__name__}. Use ClaudeCodeAgent(...) or "
                "subclass BaseAgent."
            )
        # The BASE — mirrors ``CognitiveWorker._llm``.
        self._agent: BaseAgent = agent

        # Logging runtime (``None`` = inherit / off). ``verbose`` mirrors
        # ``CognitiveWorker.verbose``; ``verbose_prompt`` logs the prompt.
        self._verbose = verbose
        self._verbose_prompt = verbose_prompt

        # Framework-injected per-call wiring (set by
        # ``AmphibiousAutoma._run_think_agent`` before driving). Each
        # CLI tool call is surfaced onto this channel as a decision; the
        # framework's consumer executes it and returns the result. The
        # worker itself never touches ``_run_action_call`` — same spirit
        # as ``CognitiveWorker`` only ever holding a ``_llm``.
        self._decision_channel: Optional["asyncio.Queue"] = None

        # Wall-clock spent across this worker's delegations. (No
        # ``spent_tokens`` — an external CLI agent's token usage is not
        # visible to the framework; its stdout is not captured.)
        self.spent_time = 0.0

    ############################################################################
    # Core dispatch — NOT user-overridable
    ############################################################################

    @worker(is_start=True, is_output=True)
    async def _think(
        self,
        ota_context: OTAContext,
        context: Optional[Context] = None,
    ) -> Any:
        """Think-phase entry (mirrors ``CognitiveWorker._thinking``).

        Both contexts are injected by the dispatcher
        (``arun(ota_context=…, context=…)``): ``ota_context`` is the
        small-loop OTA state, ``context`` the free-form knowledge. Returns
        the ``AgentResult`` from the delegation — the parent dispatcher
        unwraps ``.output`` for the ``yield ThinkAgent`` asend value.
        """
        if not isinstance(ota_context, OTAContext):
            raise TypeError(
                f"Expected OTAContext, got {type(ota_context).__name__}. "
                "AgentWorker is driven with the small-loop OTA context."
            )
        return await self._run_think(ota_context, context)

    async def _run_think(
        self,
        ota_context: OTAContext,
        context: Optional[Context] = None,
    ) -> AgentResult:
        """Organize context, then delegate to ``self._agent.run(...)``.

        Phases:

        1. MCP-ify ``ctx.tools`` — derive bindings, boot the in-process
           FastMCP host (project tools + the ``agent_done`` signal).
        2. Assemble the message via the ``thinking()`` template.
        3. Pack an ``AgentRequest`` (message + cwd + mcp servers +
           allow-list + completion future).
        4. ``await self._agent.run(request)`` — the BaseAgent owns the
           CLI mechanics from here.
        5. Tear the host down; return the ``AgentResult``.

        This method is the AgentWorker's whole job: context organization
        + delegation. It is not user-overridable — override ``thinking``
        / the hooks instead.

        Returns the ``AgentResult`` straight from ``self._agent.run`` —
        no result is stashed on the worker; the outcome flows out
        through the return value, mirroring ``CognitiveWorker.arun``.
        """
        ########################
        # 1. MCP-ify ctx.tools → boot the host
        ########################
        builtin_names = {t.tool_name for t in ALL_BUILTIN_TOOLS}
        bindings = self._build_bindings_from_ctx(ota_context, builtin_names)

        loop = asyncio.get_event_loop()
        agent_done_future: asyncio.Future[str] = loop.create_future()

        async def _on_tool_call(tool_name: str, args: Dict[str, Any]) -> Any:
            return await self._emit_decision(tool_name, args)

        def _on_agent_done(result: str) -> None:
            if not agent_done_future.done():
                agent_done_future.set_result(result)

        host = MCPHost(
            server_name=self._mcp_server_name(),
            bindings=bindings,
            on_tool_call=_on_tool_call,
            on_agent_done=_on_agent_done,
        )
        await host.start()

        ########################
        # 2-5. Assemble request → delegate → teardown
        ########################
        try:
            with tempfile.TemporaryDirectory(prefix="amphi-delegate-") as tmp:
                cwd = Path(tmp)

                message = await self.thinking(ota_context, context)
                if self._verbose_prompt:
                    printer.print(
                        f"[AgentWorker] prompt → {type(self._agent).__name__}",
                        color="cyan",
                    )
                    printer.print(message, color="gray")

                exposed_tool_names = [
                    f"mcp__{host.server_name}__{b.name}" for b in bindings
                ]
                exposed_tool_names.append(f"mcp__{host.server_name}__agent_done")

                request = AgentRequest(
                    message=message,
                    cwd=cwd,
                    mcp_servers={
                        host.server_name: {"type": "http", "url": host.url},
                    },
                    allowed_tools=exposed_tool_names,
                    done_signal=agent_done_future,
                )
                result = await self._agent.run(request)
        finally:
            await host.stop()

        return result

    def _mcp_server_name(self) -> str:
        """MCP server name advertised to the external agent.

        Subclasses may override. The name prefixes every bridged tool's
        external identifier (``mcp__<server>__<tool>``).
        """
        return "amphi-bridge"

    ############################################################################
    # Internal helpers — MCP bindings / decision emit / cloning
    ############################################################################

    def _build_bindings_from_ctx(
        self, ctx: OTAContext, builtin_names: set,
    ) -> List[MCPToolBinding]:
        """Derive MCP tool bindings from ``ctx.tools``.

        Skips framework built-ins (the CLI has its own); any
        ``expose_tools`` filtering already happened upstream where the
        parent dispatcher built the sub-run's OTA context with ``ota.tools``
        narrowed to the whitelisted set before invoking us.
        """
        bindings: List[MCPToolBinding] = []
        for tool in ctx.tools:
            name = tool.tool_name
            if name in builtin_names:
                continue
            bindings.append(MCPToolBinding(
                name=name,
                description=tool.tool_description or name,
                parameters=tool.tool_parameters or {
                    "type": "object",
                    "properties": {},
                    "required": [],
                },
            ))
        return bindings

    async def _emit_decision(
        self, tool_name: str, args: Dict[str, Any],
    ) -> Any:
        """Surface a CLI tool call as a decision for the framework to execute.

        Each tool call the external agent makes over MCP is, in effect,
        a ``think_result`` — "I want to call this tool." The worker does
        NOT execute it. It builds the decision, hands it to the framework
        over ``self._decision_channel``, and relays back whatever the
        framework's consumer fills in.

        This keeps ``AgentWorker`` symmetric with ``CognitiveWorker``:
        both only *produce* decisions; ``AmphibiousAutoma`` is the one
        that *acts*. The worker never references ``_run_action_call``.

        The framework's consumer runs each decision through
        ``_run_action_call`` (worker ``before_action`` / ``after_action``
        hooks fire, the call folds onto the OTA context's current round +
        the ``AgentTrace``), then resolves the future with the resulting
        ``Step`` — which is unwrapped here into the raw tool result the
        external agent expects back.
        """
        if self._decision_channel is None:
            raise RuntimeError(
                "AgentWorker has no decision channel — it must be driven "
                "by AmphibiousAutoma._run_think_agent, which wires the "
                "channel and runs the consumer that executes each decision."
            )
        # Build the decision directly: each external-agent tool call becomes a
        # one-call ``ThinkResult`` for the framework's consumer to execute.
        # Args are carried as ``ToolArgument`` name/value pairs, so a tool
        # parameter named ``description`` / ``tool_name`` poses no collision.
        decision = ThinkResult(
            step_content=f"[think_agent] {tool_name}",
            tool_calls=[StepToolCall(
                tool=tool_name,
                tool_arguments=[
                    ToolArgument(name=k, value=str(v)) for k, v in args.items()
                ],
            )],
        )
        result_future: "asyncio.Future" = (
            asyncio.get_event_loop().create_future()
        )
        await self._decision_channel.put((decision, result_future))
        step = await result_future
        return _extract_tool_result(step)

    def _clone(self) -> "AgentWorker":
        """Return a fresh worker with the same configuration.

        The ``BaseAgent`` is *shared* across clones — it is stateless
        per call (every dynamic input arrives via ``AgentRequest``),
        exactly as a ``BaseLlm`` is shared across ``CognitiveWorker``
        clones. Subclasses with extra ``__init__`` params should
        override.

        Used by ``ThinkAgentDescriptor._clone_worker`` for state
        isolation at every ``yield ThinkAgent(...)``.
        """
        return type(self)(
            self._agent,
            verbose=self._verbose,
            verbose_prompt=self._verbose_prompt,
        )

    ############################################################################
    # Template methods (override by user to customize the behavior)
    ############################################################################

    async def observation(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
        """Worker-level observation hook. Override to customize.

        Same contract as ``CognitiveWorker.observation``: returning
        ``_DELEGATE`` (or ``None``) hands off to
        ``AmphibiousAutoma.observation()``. Other values are used as
        the observation directly.
        """
        return _DELEGATE

    async def thinking(
        self,
        ota_context: OTAContext,
        context: Optional[Context] = None,
    ) -> str:
        """Assemble the message handed to the external agent.

        The AgentWorker analog of ``CognitiveWorker.thinking()`` — it
        produces the prompt. The default layout is goal → parent context
        (small-loop task summary + big-loop knowledge + observation) →
        completion contract; override to restructure or inject domain
        instructions.

        Two-loop inputs (both injected by the dispatcher): ``ota_context``
        is the small-loop OTA context — its ``user_input`` is the resolved
        goal for this delegation; ``context`` is the free-form big-loop
        knowledge context (``None`` for a pure-reasoning run). The project
        tools are NOT enumerated here — the agent discovers them through
        the MCP server; the contract just needs to tell it they exist and
        how to finish.
        """
        goal = str(ota_context.user_input or "")
        context_info = _format_context_info(ota_context, context, ota_context.obs_result)

        parts = [
            "You are running as the external agent layer of an AmphibiousAutoma.",
            "",
            "GOAL:",
            goal or "(no goal supplied)",
        ]
        if context_info:
            parts += ["", "PARENT CONTEXT:", context_info]
        parts += [
            "",
            "PROJECT TOOLS:",
            "  Project tools are exposed to you over MCP. Calling them "
            "routes back into the parent automa's hook pipeline.",
            "",
            "COMPLETION CONTRACT:",
            "  When the goal is fully complete, call the `agent_done` "
            "tool with `result` set to the final answer / summary "
            "string, then finish. The parent automa resumes with the "
            "value you pass.",
        ]
        return "\n".join(parts)

    async def before_action(
        self,
        ota_context: OTAContext,
        context: Optional[Context] = None,
    ) -> Any:
        """Worker-level before_action hook. Override to intercept bridged tool calls.

        Same contract as ``CognitiveWorker.before_action``: ``_DELEGATE`` /
        ``None`` chains to the agent-level hook; any other value
        overrides the decision.
        """
        return _DELEGATE

    async def after_action(
        self,
        ota_context: OTAContext,
        context: Optional[Context] = None,
    ) -> Any:
        """Worker-level after_action hook. Override for side-effects.

        Same contract as ``CognitiveWorker.after_action``: ``_DELEGATE`` /
        ``None`` chains to the agent-level hook; any other value
        suppresses it.
        """
        return _DELEGATE

    ############################################################################
    # Entry point
    ############################################################################

    async def arun(
        self,
        *args: Any,
        feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
        **kwargs: Any,
    ) -> Any:
        """Execute the think phase.

        Observation must be pre-set in ``context.observation`` (handled
        by ``AmphibiousAutoma._run_think_agent``). Returns the
        ``AgentResult`` for the delegation (mirrors how
        ``CognitiveWorker.arun`` returns its decision).
        """
        start_time = time.monotonic()
        result = await super().arun(*args, feedback_data=feedback_data, **kwargs)
        self.spent_time += time.monotonic() - start_time
        return result

observation

async
observation(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level observation hook. Override to customize.

Same contract as CognitiveWorker.observation: returning _DELEGATE (or None) hands off to AmphibiousAutoma.observation(). Other values are used as the observation directly.

Source code in bridgic/amphibious/_agent_worker.py
async def observation(self, ota_context: OTAContext, context: Optional[Context] = None) -> Any:
    """Worker-level observation hook. Override to customize.

    Same contract as ``CognitiveWorker.observation``: returning
    ``_DELEGATE`` (or ``None``) hands off to
    ``AmphibiousAutoma.observation()``. Other values are used as
    the observation directly.
    """
    return _DELEGATE

thinking

async
thinking(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> str

Assemble the message handed to the external agent.

The AgentWorker analog of CognitiveWorker.thinking() — it produces the prompt. The default layout is goal → parent context (small-loop task summary + big-loop knowledge + observation) → completion contract; override to restructure or inject domain instructions.

Two-loop inputs (both injected by the dispatcher): ota_context is the small-loop OTA context — its user_input is the resolved goal for this delegation; context is the free-form big-loop knowledge context (None for a pure-reasoning run). The project tools are NOT enumerated here — the agent discovers them through the MCP server; the contract just needs to tell it they exist and how to finish.

Source code in bridgic/amphibious/_agent_worker.py
async def thinking(
    self,
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> str:
    """Assemble the message handed to the external agent.

    The AgentWorker analog of ``CognitiveWorker.thinking()`` — it
    produces the prompt. The default layout is goal → parent context
    (small-loop task summary + big-loop knowledge + observation) →
    completion contract; override to restructure or inject domain
    instructions.

    Two-loop inputs (both injected by the dispatcher): ``ota_context``
    is the small-loop OTA context — its ``user_input`` is the resolved
    goal for this delegation; ``context`` is the free-form big-loop
    knowledge context (``None`` for a pure-reasoning run). The project
    tools are NOT enumerated here — the agent discovers them through
    the MCP server; the contract just needs to tell it they exist and
    how to finish.
    """
    goal = str(ota_context.user_input or "")
    context_info = _format_context_info(ota_context, context, ota_context.obs_result)

    parts = [
        "You are running as the external agent layer of an AmphibiousAutoma.",
        "",
        "GOAL:",
        goal or "(no goal supplied)",
    ]
    if context_info:
        parts += ["", "PARENT CONTEXT:", context_info]
    parts += [
        "",
        "PROJECT TOOLS:",
        "  Project tools are exposed to you over MCP. Calling them "
        "routes back into the parent automa's hook pipeline.",
        "",
        "COMPLETION CONTRACT:",
        "  When the goal is fully complete, call the `agent_done` "
        "tool with `result` set to the final answer / summary "
        "string, then finish. The parent automa resumes with the "
        "value you pass.",
    ]
    return "\n".join(parts)

before_action

async
before_action(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level before_action hook. Override to intercept bridged tool calls.

Same contract as CognitiveWorker.before_action: _DELEGATE / None chains to the agent-level hook; any other value overrides the decision.

Source code in bridgic/amphibious/_agent_worker.py
async def before_action(
    self,
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any:
    """Worker-level before_action hook. Override to intercept bridged tool calls.

    Same contract as ``CognitiveWorker.before_action``: ``_DELEGATE`` /
    ``None`` chains to the agent-level hook; any other value
    overrides the decision.
    """
    return _DELEGATE

after_action

async
after_action(
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any

Worker-level after_action hook. Override for side-effects.

Same contract as CognitiveWorker.after_action: _DELEGATE / None chains to the agent-level hook; any other value suppresses it.

Source code in bridgic/amphibious/_agent_worker.py
async def after_action(
    self,
    ota_context: OTAContext,
    context: Optional[Context] = None,
) -> Any:
    """Worker-level after_action hook. Override for side-effects.

    Same contract as ``CognitiveWorker.after_action``: ``_DELEGATE`` /
    ``None`` chains to the agent-level hook; any other value
    suppresses it.
    """
    return _DELEGATE

arun

async
arun(
    *args: Any,
    feedback_data: Optional[
        Union[
            InteractionFeedback, List[InteractionFeedback]
        ]
    ] = None,
    **kwargs: Any
) -> Any

Execute the think phase.

Observation must be pre-set in context.observation (handled by AmphibiousAutoma._run_think_agent). Returns the AgentResult for the delegation (mirrors how CognitiveWorker.arun returns its decision).

Source code in bridgic/amphibious/_agent_worker.py
async def arun(
    self,
    *args: Any,
    feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
    **kwargs: Any,
) -> Any:
    """Execute the think phase.

    Observation must be pre-set in ``context.observation`` (handled
    by ``AmphibiousAutoma._run_think_agent``). Returns the
    ``AgentResult`` for the delegation (mirrors how
    ``CognitiveWorker.arun`` returns its decision).
    """
    start_time = time.monotonic()
    result = await super().arun(*args, feedback_data=feedback_data, **kwargs)
    self.spent_time += time.monotonic() - start_time
    return result

AmphibiousAutoma

Bases: GraphAutoma, Generic[OTAContextT, ContextT]

Base class for amphibious agents — dual-mode orchestration engine.

Subclasses define behavior by implementing on_agent() (LLM-driven, yields ThinkUnit / ThinkAgent) and/or on_workflow() (deterministic, yields ActionCall / HumanCall / LLMCall / EnterAgent). Under RunMode.AUTO (default), only-on_agent → AGENT, only-on_workflow → WORKFLOW, both → AMPHIFLOW (workflow-first with agent fallback on step failure).

Yield-type ↔ scope rules:

=========== ============ ======== ===== primitive on_workflow on_agent hooks =========== ============ ======== ===== ActionCall ✓ ✗ ✓ HumanCall ✓ ✗ ✓ LLMCall ✓ ✗ ✓ EnterAgent ✓ ✗ ✗ ThinkUnit ✗ ✓ ✗ ThinkAgent ✗ ✓ ✗ RETURN ✓ ✓ ✓ =========== ============ ======== =====

Constructor params: llm (default LLM for workers), name (instance name), verbose (log execution summary), and verbose_hook (surface dispatch logs for Calls yielded from hooks — suppressed by default since hooks are internal side-effects).

Examples:

1
2
3
4
5
6
7
8
9
>>> class MyThink(CognitiveWorker):
...     async def thinking(self, ota_context, context=None):
...         return await self._llm.aselect_tool(messages=[...], tools=[...])
>>> class MyAgent(AmphibiousAutoma[OTAContext, Context]):
...     main_think = think_unit(MyThink(), max_attempts=20)
...     async def on_agent(self, ota_context, context=None):
...         yield ThinkUnit("main_think")
...
>>> answer = await MyAgent().arun(llm=llm, user_input="Complete the task")
Source code in bridgic/amphibious/_amphibious_automa.py
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
class AmphibiousAutoma(GraphAutoma, Generic[OTAContextT, ContextT]):
    """Base class for amphibious agents — dual-mode orchestration engine.

    Subclasses define behavior by implementing ``on_agent()`` (LLM-driven,
    yields ``ThinkUnit`` / ``ThinkAgent``) and/or ``on_workflow()``
    (deterministic, yields ``ActionCall`` / ``HumanCall`` / ``LLMCall`` /
    ``EnterAgent``). Under ``RunMode.AUTO`` (default), only-on_agent →
    AGENT, only-on_workflow → WORKFLOW, both → AMPHIFLOW (workflow-first
    with agent fallback on step failure).

    Yield-type ↔ scope rules:

    ===========  ============  ========  =====
    primitive    on_workflow   on_agent  hooks
    ===========  ============  ========  =====
    ActionCall   ✓             ✗         ✓
    HumanCall    ✓             ✗         ✓
    LLMCall      ✓             ✗         ✓
    EnterAgent   ✓             ✗         ✗
    ThinkUnit    ✗             ✓         ✗
    ThinkAgent   ✗             ✓         ✗
    RETURN       ✓             ✓         ✓
    ===========  ============  ========  =====

    Constructor params: ``llm`` (default LLM for workers), ``name``
    (instance name), ``verbose`` (log execution summary), and
    ``verbose_hook`` (surface dispatch logs for Calls yielded from
    hooks — suppressed by default since hooks are internal side-effects).

    Examples
    --------
    >>> class MyThink(CognitiveWorker):
    ...     async def thinking(self, ota_context, context=None):
    ...         return await self._llm.aselect_tool(messages=[...], tools=[...])
    >>> class MyAgent(AmphibiousAutoma[OTAContext, Context]):
    ...     main_think = think_unit(MyThink(), max_attempts=20)
    ...     async def on_agent(self, ota_context, context=None):
    ...         yield ThinkUnit("main_think")
    ...
    >>> answer = await MyAgent().arun(llm=llm, user_input="Complete the task")
    """

    ############################################################################
    # Class attributes — populated by ``__init_subclass__``
    ############################################################################

    #: Small-loop context type, resolved from the first generic argument by
    #: ``_detect_context_classes``. The framework constructs a fresh instance
    #: of this per ``arun`` (seeding ``goal``), so it must be ``OTAContext``
    #: (or a subclass).
    _ota_context_class: Optional[Type[OTAContext]] = None
    #: Big-loop context type, resolved from the second generic argument. A
    #: free-form ``Context`` subclass; supplied at run time via ``arun(context=)``
    #: (optional — the framework reads its ``summary()`` and its declared
    #: ``tools``).
    _context_class: Optional[Type[Context]] = None

    #: ``@human_channel``-decorated registry, populated by
    #: ``__init_subclass__``. Maps channel-name → method-name. Empty on
    #: the base class; subclasses inherit and may add or override.
    _human_channels: ClassVar[Dict[str, str]] = {}

    def __init_subclass__(cls, **kwargs) -> None:
        """Per-subclass initialisation.

        Three responsibilities:

        1. Extract the two context types (``OTAContext`` small-loop +
           ``Context`` loop) from the ``Generic[OTAContextT, ContextT]``
           parameters so ``cls._ota_context_class`` / ``cls._context_class``
           are set.
        2. Build the ``cls._human_channels`` registry by walking the MRO
           and collecting every method tagged via ``@human_channel``.
           Subclass overrides win over parent declarations.
        3. Validate that every overridden template method is an async
           generator (the only shape the dispatch model supports).
        """
        super().__init_subclass__(**kwargs)
        cls._detect_context_classes()
        cls._build_human_channel_registry()
        cls._validate_template_forms()

    @classmethod
    def _validate_template_forms(cls) -> None:
        """Reject coroutine-form template overrides at class-creation time.

        The dispatch model is yield-driven: every framework primitive
        (``ActionCall`` / ``HumanCall`` / ``LLMCall`` / ``EnterAgent`` /
        ``ThinkUnit`` / ``ThinkAgent`` / ``RETURN``) reaches the framework
        via ``yield``. A coroutine-form override (``async def`` without
        any ``yield``) cannot use any of these primitives, so the
        framework no longer accepts that shape. The base class defaults
        are themselves stub async generators (``if False: yield``), so
        not overriding is also fine.
        """
        template_names = (
            "on_agent", "on_workflow",
            "observation", "before_action", "after_action",
        )
        for name in template_names:
            impl = getattr(cls, name, None)
            base_impl = getattr(AmphibiousAutoma, name, None)
            # Not overridden — base default is already a proper async-gen.
            if impl is base_impl:
                continue
            if not inspect.isasyncgenfunction(impl):
                raise TypeError(
                    f"{cls.__name__}.{name} must be an ``async def`` "
                    f"function with at least one ``yield`` statement in "
                    f"its body. The framework's dispatch model is "
                    f"yield-driven — every primitive (ActionCall / "
                    f"HumanCall / LLMCall / EnterAgent / ThinkUnit / "
                    f"ThinkAgent / RETURN) reaches the framework via "
                    f"``yield``, so a coroutine-form template override "
                    f"(no ``yield``) cannot use the framework. If the "
                    f"body has no real yields, add ``if False: yield`` "
                    f"as an unreachable stub to keep the async-generator "
                    f"shape."
                )

    @classmethod
    def _detect_context_classes(cls) -> None:
        """Resolve the two context types from ``Generic[OTAContextT, ContextT]``.

        Parses ``__orig_bases__`` for a parametrization carrying exactly two
        arguments and validates each against its bound: the first must be an
        :class:`OTAContext` (framework-owned small loop), the second a
        :class:`Context` (free-form loop). Both are required — there is no
        single-argument form.

        A subclass of an already-parametrized agent (whose own
        ``__orig_bases__`` no longer name the generic) inherits both classes
        from its base. The error path fires only when neither parametrization
        nor inheritance yields a valid pair.
        """
        for base in getattr(cls, "__orig_bases__", []):
            if get_origin(base) is None:
                continue
            args = get_args(base)
            if len(args) != 2:
                continue
            ota_type, loop_type = args
            # Skip bare-TypeVar / unresolved parametrizations; inheritance
            # (below) covers concrete-parametrized intermediate subclasses.
            if not (isinstance(ota_type, type) and isinstance(loop_type, type)):
                continue
            if not issubclass(ota_type, OTAContext):
                raise TypeError(
                    f"{cls.__name__}: the first generic argument {ota_type.__name__!r} "
                    f"is not an OTAContext. AmphibiousAutoma[OTAContextT, ContextT] "
                    f"requires the small-loop context (arg 1) to subclass OTAContext, "
                    f"e.g. class {cls.__name__}(AmphibiousAutoma[OTAContext, Context])."
                )
            if not issubclass(loop_type, Context):
                raise TypeError(
                    f"{cls.__name__}: the second generic argument {loop_type.__name__!r} "
                    f"is not a Context. AmphibiousAutoma[OTAContextT, ContextT] requires "
                    f"the loop context (arg 2) to subclass Context, "
                    f"e.g. class {cls.__name__}(AmphibiousAutoma[OTAContext, Context])."
                )
            cls._ota_context_class = ota_type
            cls._context_class = loop_type
            return

        # Inheritance: a subclass of an already-parametrized agent.
        for base in cls.__bases__:
            ota_inherited = getattr(base, "_ota_context_class", None)
            loop_inherited = getattr(base, "_context_class", None)
            if ota_inherited is not None and loop_inherited is not None:
                cls._ota_context_class = ota_inherited
                cls._context_class = loop_inherited
                break

        if cls._ota_context_class is None or cls._context_class is None:
            raise TypeError(
                f"{cls.__name__} must specify both context types via the generic "
                f"parameters, e.g. "
                f"class {cls.__name__}(AmphibiousAutoma[OTAContext, Context]). "
                f"Arg 1 (small loop) must subclass OTAContext; arg 2 (loop) must "
                f"subclass Context."
            )

    @classmethod
    def _build_human_channel_registry(cls) -> None:
        """Walk MRO bottom-up so subclass overrides win, populate registry."""
        registry: Dict[str, str] = {}
        for klass in reversed(cls.__mro__):
            for attr_name, attr in vars(klass).items():
                channel_name = getattr(attr, _HUMAN_CHANNEL_MARKER, None)
                if channel_name is not None:
                    registry[channel_name] = attr_name
        cls._human_channels = registry

    ############################################################################
    # Instance attributes — set up in ``__init__``
    ############################################################################

    def __init__(
        self,
        name: Optional[str] = None,
        thread_pool: Optional[ThreadPoolExecutor] = None,
        running_options: Optional[RunningOptions] = None,
        verbose: bool = False,
        verbose_hook: bool = False,
    ):
        super().__init__(name=name, thread_pool=thread_pool, running_options=running_options)

        # User-facing state. Two context slots for the two loops, each read
        # through a property accessor (``self.ota_ctx`` / ``self.ctx``) so
        # internal methods reach the active context off ``self`` rather than
        # threading it as a parameter:
        #   * ``_current_ota_context`` — the small-loop OTA context, freshly
        #     constructed per ``arun`` and swapped to a nested sub-context for
        #     the duration of a delegation (via ``_ota_scope``). Read: ``ota_ctx``.
        #   * ``_current_context`` — the loop knowledge context, supplied by
        #     the caller and read-only to the run. Read: ``ctx``.
        self._llm = None
        self._current_ota_context: Optional[OTAContextT] = None
        self._current_context: Optional[ContextT] = None
        self._run_mode: Optional[RunMode] = None

        # Log configuration
        self._verbose = verbose
        self._verbose_hook = verbose_hook
        self._log_depth: int = 0
        self._log_hook_name: Optional[str] = None

        # Trace capture
        self._agent_trace: Optional[AgentTrace] = None
        self._read_tracker: Dict[str, float] = {}
        self._current_run_dir: Optional[Path] = None

        # Running results
        self._final_answer: Optional[str] = None
        self.spent_tokens: int = 0
        self.spent_time: float = 0.0

        # AMPHIFLOW FSM state — set by ``_amphiflow`` for the duration of one AMPHIFLOW run
        self._amphi: Optional[_AmphiState] = None

    @property
    def llm(self) -> Optional[Any]:
        """LLM of the active or most recent ``arun`` (``None`` before
        the first run and after ``arun`` clears it in ``finally``)."""
        return self._llm

    @property
    def ota_ctx(self) -> Optional[OTAContextT]:
        """The active small-loop (OTA) context.

        Freshly constructed per ``arun`` and swapped to a nested sub-context
        for the span of a delegation (``EnterAgent`` / ``ThinkAgent`` /
        step-level fallback) by ``_ota_scope``. Internal methods read the
        active context through this accessor instead of threading it as a
        parameter; the underlying slot (``_current_ota_context``) is written
        only by ``arun`` and ``_ota_scope``.
        """
        return self._current_ota_context

    @property
    def ctx(self) -> Optional[ContextT]:
        """The loop (knowledge) context — the free-form context passed to
        ``arun(context=)`` (or a fresh default when none was supplied).

        Shared read-only across the parent run and any nested delegation;
        only the small loop (``ota_ctx``) is isolated per sub-run.
        """
        return self._current_context

    @property
    def final_answer(self) -> Optional[str]:
        """The final answer produced by the last ``arun()`` call.

        Automatically captured from the ``step_content`` of the finishing
        step (agent mode) or the last executed step (workflow mode).
        Top-level template-method generators may override the auto-captured
        value by yielding ``RETURN(value)``.
        """
        return self._final_answer

    ############################################################################
    # Template methods — overridable hooks. AmphibiousAutoma overrides must be
    # async generators (yielding framework primitives), as enforced by
    # ``_validate_template_forms``. Scope rules are documented on the class
    # docstring above.
    ############################################################################
    async def observation(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
        """Agent-level default observation, shared across all workers.

        Called before each thinking phase; workers' own ``observation()``
        delegates here when it returns ``_DELEGATE`` / ``None``.

        Yield ``RETURN(text)`` to set ``ota_context.obs_result`` for this
        cycle. Exhausting without ``RETURN`` (or yielding ``RETURN(None)``)
        **preserves** the previous ``ota_context.obs_result`` — so
        ``after_action``-driven refresh patterns work without a dedicated
        passthrough override.

        >>> async def observation(self, ota_context, context=None):
        ...     snapshot = yield ActionCall("bash", command="bridgic-browser snapshot")
        ...     yield RETURN(snapshot[0].result)
        """
        if False:  # pragma: no cover — async generator stub
            yield

    async def on_agent(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
        """Agent mode: LLM-driven cognitive flow.

        Override to declare the agent's strategy. on_agent body is
        reserved for orchestrating cognitive steps — only ``ThinkUnit``
        / ``ThinkAgent`` / ``RETURN`` are allowed (deterministic tool /
        HITL / direct-LLM operations belong in on_workflow or a hook).
        Without ``RETURN``, the framework auto-captures the final answer
        from the last think step's ``step_content``.

        >>> async def on_agent(self, ota_context, context=None):
        ...     yield ThinkUnit("main_think", max_attempts=20)
        ...     yield ThinkUnit("exec_think", until=lambda c: c.done)
        ...     yield RETURN(ota_context.ota_record[-1].think_result.step_content)
        """
        if False:  # pragma: no cover — async generator stub
            yield

    async def on_workflow(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Union[ActionCall, HumanCall, EnterAgent, LLMCall], None]:
        """Workflow mode: deterministic flow as an async generator.

        Override to declare a deterministic workflow. Yield ``ActionCall``
        / ``HumanCall`` / ``LLMCall`` for atomic steps, ``EnterAgent`` to
        enter an autonomous sub-flow, ``RETURN(value)`` to terminate
        early. Use ``result = yield ActionCall(...)`` to receive results
        via ``asend()``.

        >>> async def on_workflow(self, ota_context, context=None):
        ...     yield ActionCall("navigate_to", url="http://example.com")
        ...     result = yield ActionCall("click_element_by_ref", ref="42")
        ...     summary = yield LLMCall.chat("Summarize the page in one line.")
        ...     yield EnterAgent(goal="Handle complex case")
        """
        if False:  # pragma: no cover — makes this a proper async generator stub
            yield

    async def before_action(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
        """Agent-level before_action hook, shared across all workers.

        Called when a worker's ``before_action()`` returns ``_DELEGATE``
        / ``None``. Payload-free — read the pending decision from
        ``ota_context.think_result``. Yield ``RETURN(modified_decision)``
        to override the decision; exhausting without RETURN (or returning
        ``None`` from a coroutine override) is passthrough — the folded
        decision stands.

        >>> async def before_action(self, ota_context, context=None):
        ...     adjusted = sanitize(ota_context.think_result)
        ...     yield RETURN(adjusted)
        """
        if False:  # pragma: no cover — async generator stub
            yield

    async def action_tool_call(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> ActionResult:
        """Execute the current decision's tool calls concurrently, collect results.

        The calls are read off the decision on ``ota_context.think_result``
        (a ``before_action`` hook may have already filtered or replaced it)
        and matched against ``ota_context.tools``. Override to customize
        execution (sequential, rate-limited, sandboxed); both contexts are
        passed for parity with the other template methods.
        """
        matched = _decision_to_matched_calls(
            ota_context.think_result, ota_context.tools
        )

        async def _run_one(tool_call: ToolCall, tool_spec: ToolSpec) -> ActionStepResult:
            tool_worker = tool_spec.create_worker()
            sandbox = ConcurrentAutoma()
            worker_key = f"tool_{tool_call.name}_{tool_call.id}"
            sandbox.add_worker(
                key=worker_key,
                worker=tool_worker,
                args_mapping_rule=ArgsMappingRule.UNPACK,
            )
            try:
                results = await sandbox.arun(InOrder([tool_call.arguments]))
                result = results[0] if results else None
                return ActionStepResult(
                    tool_id=tool_call.id,
                    tool_name=tool_call.name,
                    tool_arguments=tool_call.arguments,
                    tool_result=result,
                    success=True,
                )
            except Exception as e:
                return ActionStepResult(
                    tool_id=tool_call.id,
                    tool_name=tool_call.name,
                    tool_arguments=tool_call.arguments,
                    tool_result=None,
                    success=False,
                    error=str(e),
                )

        step_results = await asyncio.gather(
            *(_run_one(tc, ts) for tc, ts in matched)
        )
        return ActionResult(results=list(step_results))

    async def after_action(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
        """Agent-level after_action hook.

        Called after action execution. Payload-free — read the action
        result from ``ota_context.action_result``. Override to update
        custom context fields or trigger follow-up primitives based on
        it. ``RETURN`` is unused here — the hook's return value is
        ignored.

        >>> async def after_action(self, ota_context, context=None):
        ...     summary = yield LLMCall.chat(f"Summarize: {ota_context.action_result}")
        ...     ota_context.action_result  # action payload on the current round
        """
        if False:  # pragma: no cover — async generator stub
            yield

    ############################################################################
    # Core methods
    #
    # Two engines: ``_invoke_template`` / ``_amphiflow`` drive generators,
    # ``_dispatch_step`` routes each yield to a ``_run_<primitive>`` /
    # ``_enter_agent`` handler. ``RETURN`` is the only yield NOT routed
    # through dispatch — the two drivers intercept it directly as a loop
    # control signal. ``_ota_scope`` provides the fresh-instance delegation
    # mechanism EnterAgent, ThinkAgent, and step-level fallback rely on
    # (each runs a nested OTA episode with its own ``OTAContext``).
    ############################################################################

    async def _invoke_template(
        self,
        gen_or_coro: Any,
        *,
        scope: str = "hook",
    ) -> Any:
        """Generic template-method driver. No fallback policy.

        Supports two template shapes:

        * **Async-generator** — driven with ``__anext__`` / ``asend``,
          dispatching each yielded item through ``_dispatch_step``,
          capturing ``RETURN(value)`` as the return.
        * **Coroutine** — ``await`` and return the awaited value. Used
          by ``CognitiveWorker`` hooks (``observation`` /
          ``before_action`` / ``after_action``) whose natural shape is
          ``return _DELEGATE`` / ``return value``.

        ``scope`` is one of ``"workflow"`` / ``"agent"`` / ``"hook"``
        and gates which primitives ``_dispatch_step`` accepts. Errors
        propagate; body-level fallback lives in ``_amphiflow``.
        """
        if not inspect.isasyncgen(gen_or_coro):
            return await gen_or_coro

        send_value: Any = None
        return_value: Any = None
        try:
            while True:
                try:
                    if send_value is None:
                        item = await gen_or_coro.__anext__()
                    else:
                        item = await gen_or_coro.asend(send_value)
                    send_value = None
                except StopAsyncIteration:
                    break
                else:
                    if isinstance(item, RETURN):
                        return_value = item.value
                        break
                    send_value = await self._dispatch_step(item, scope=scope)
        finally:
            # Cleanup
            try:
                await gen_or_coro.aclose()
            except Exception:
                pass

        return return_value

    async def _dispatch_step(
        self,
        item: Any,
        *,
        scope: str = "hook",
    ) -> Any:
        """Per-yield handler — the single place that knows framework primitives.

        Routes each operation primitive to its ``_run_<primitive>`` /
        ``_enter_agent`` and returns the raw result for the caller to
        forward via ``.asend()`` (inline) or write to
        ``fsm.{agent,workflow}_send`` (AMPHIFLOW). ``RETURN`` is
        intercepted by the callers themselves (``_invoke_template`` /
        ``_amphiflow``) — it is a control-flow signal, not an operation.

        Scope rules:

        * ``ActionCall`` / ``HumanCall`` / ``LLMCall`` — ``workflow`` or
          ``hook``, never ``agent``.
        * ``EnterAgent`` — ``workflow`` only.
        * ``ThinkUnit`` / ``ThinkAgent`` — ``agent`` only.

        ActionCall in ``scope="hook"`` skips before/after_action hooks
        (``_run_action_call(..., with_hooks=False)``): hooks are not OTC
        participants — re-entering the hook chain would recurse into
        the generator that yielded the call.
        """
        if isinstance(item, EnterAgent):
            # Scope validation
            if scope != "workflow":
                raise RuntimeError(
                    f"EnterAgent(goal={item.goal!r}) is only valid inside "
                    f"on_workflow (scope='workflow'); got scope={scope!r}. "
                    "EnterAgent is the deterministic→autonomous mode "
                    "switch; once you are inside on_agent, keep "
                    "thinking via ThinkUnit instead."
                )
            if not self._has_agent():
                raise RuntimeError(
                    f"EnterAgent(goal={item.goal!r}) requires an on_agent() "
                    "override on the agent class."
                )

            # Mode switch
            return await self._enter_agent(item=item)

        if isinstance(item, HumanCall):
            # Scope validation
            if scope == "agent":
                raise RuntimeError(
                    f"HumanCall(prompt={item.prompt!r}) is not allowed inside "
                    "on_agent — the agent should request human input via the "
                    "explicitly declared ``request_human`` tool (called by the "
                    "LLM during a ThinkUnit), not by yielding HumanCall directly. "
                    "If you need a deterministic human step, put it in "
                    "on_workflow."
                )

            # Human call
            return await self._run_human_call(item)

        if isinstance(item, LLMCall):
            # Scope validation: LLMCall is an atomic step and must be handled
            if scope == "agent":
                raise RuntimeError(
                    f"LLMCall(protocol={item.protocol!r}) is not allowed inside "
                    "on_agent — on_agent body is reserved for orchestrating "
                    "cognitive steps via ThinkUnit. Direct LLM calls belong "
                    "in on_workflow, in a hook, or inside a CognitiveWorker's "
                    "thinking() method."
                )

            # LLM call
            return await self._run_llm_call(item)

        if isinstance(item, ThinkUnit):
            # Scope validation: ThinkUnit is a cognitive step and must be handled by on_agent.
            if scope != "agent":
                raise RuntimeError(
                    f"ThinkUnit(name={item.name!r}) is only valid inside "
                    f"on_agent (scope='agent'); got scope={scope!r}. "
                    "ThinkUnit references a class-level think_unit and "
                    "represents a step in the agent's cognitive strategy; "
                    "use LLMCall for a direct LLM invocation outside the "
                    "cognitive loop, or EnterAgent to enter an on_agent flow."
                )
            # Run ThinkUnit
            return await self._run_think_unit(item)

        if isinstance(item, ThinkAgent):
            # Scope validation: ThinkAgent is a cognitive step that delegates to an external agent runtime.
            if scope != "agent":
                raise RuntimeError(
                    f"ThinkAgent(name={item.name!r}) is only valid inside "
                    f"on_agent (scope='agent'); got scope={scope!r}. "
                    "ThinkAgent hands the sub-goal off to an external agent "
                    "runtime and is part of the cognitive-composition layer; "
                    "use EnterAgent from on_workflow if you need to enter the "
                    "agent flow, then yield ThinkAgent from there."
                )

            # ThinkAgent
            return await self._run_think_agent(item)

        if isinstance(item, ActionCall):
            # Scope validation: ActionCall is an atomic step and must be handled by on_workflow or a hook, never on_agent.
            if scope == "agent":
                raise RuntimeError(
                    f"ActionCall(tool_name={item.tool_name!r}) is not allowed "
                    "inside on_agent — let the LLM decide tool calls inside a "
                    "ThinkUnit. If you need a deterministic tool call, put it "
                    "in on_workflow or in a worker hook (observation / "
                    "before_action / after_action)."
                )

            # ActionCall — wrap the single tool call into a ThinkResult decision.
            decision = ThinkResult(
                step_content=item.description,
                tool_calls=[StepToolCall(
                    tool=item.tool_name,
                    tool_arguments=[
                        ToolArgument(name=k, value=str(v)) for k, v in item.tool_args.items()
                    ],
                )],
            )
            if scope == "hook":
                action_result = await self._run_action_call(decision, with_hooks=False, top_level=False)
            else:
                action_result = await self._run_action_call(decision, _worker=None)

            inner = getattr(action_result, "result", None)
            if isinstance(inner, ActionResult):
                failed = [r for r in inner.results if not r.success]
                if failed:
                    errors = "; ".join(f"{r.tool_name}: {r.error}" for r in failed)
                    raise RuntimeError(
                        f"Tool execution failed for: "
                        f"{decision.step_content}{errors}"
                    )

            return self._build_tool_results(action_result)

        raise TypeError(
            f"Unknown yield type: {type(item).__name__}. Expected one of "
            "ActionCall / HumanCall / LLMCall / EnterAgent / ThinkUnit / ThinkAgent. "
            "(RETURN is a control-flow signal handled upstream in "
            "``_invoke_template`` / ``_amphiflow`` before dispatch.)"
        )

    async def _enter_agent(
        self,
        *,
        item: Optional[EnterAgent] = None,
    ) -> Any:
        """Run a fresh nested OTA episode of the agent's ``on_agent`` strategy.

        Delegation = a fresh sub-run (isolation by construction), not a
        snapshot of the parent context. A fresh :class:`OTAContext` is
        built (own ``user_input`` / ``ota_record``, carrying the OTA context
        class's declared tools) and installed as
        ``self._current_ota_context`` for the sub-flow; the parent's OTA
        context is restored when the sub-flow ends. The loop knowledge
        context is **shared** (read via the ``current_agent`` ContextVar) —
        only the small loop is isolated.

        Two entry shapes:

        * ``item`` (a yielded ``EnterAgent``) — sub-goal is ``item.goal``.
          Emits the ``[EnterAgent]`` header + ``-> final:`` closer.
        * no ``item`` (AMPHIFLOW full fallback) — the sub-run inherits the
          parent's goal. No envelope.

        (Step-level fallback no longer routes through here — it runs a
        bounded inline recovery via ``_run_fallback_agent``.)

        The sub-run's tools always come from the OTA context class
        declaration (``OTAContext.tool``); nothing is filtered or passed in.
        The inherited goal is read off ``self.ota_ctx`` (still the parent —
        the scope swap happens afterwards, step 3 / 4).
        """
        # 1. Resolve the fresh sub-run's goal from the entry shape (its tools
        #    come from the OTA context class declaration, so there is nothing
        #    to pass or filter). ``self.ota_ctx`` is still the parent here.
        if item is not None:
            sub_goal: str = item.goal
        else:
            sub_goal = self.ota_ctx.user_input

        # 2. Build the fresh small-loop OTA context (isolation by construction;
        #    it auto-carries the OTA context class's declared tools).
        sub_ctx = self._ota_context_class(user_input=sub_goal)

        envelope = item is not None
        if envelope:
            self._log(
                "EnterAgent",
                f"goal={_brief(item.goal)}",
                color="yellow",
            )
            self._log_depth += 1
        try:
            # 3. AMPHIFLOW path: install the sub-context on an
            #    ``AsyncExitStack`` (restored when the agent generator
            #    exhausts, via ``fsm.agent_mode_stack``), then hand the
            #    fresh ``on_agent`` generator to the state machine.
            #    Mirrors the legacy snapshot hand-off — only the scoped
            #    object changed (a fresh OTA context, not field overrides).
            if self._run_mode is RunMode.AMPHIFLOW:
                fsm = self._amphi
                assert fsm is not None, (
                    "AMPHIFLOW run_mode but ``self._amphi`` is None — "
                    "``_enter_agent`` was called outside ``_amphiflow``'s "
                    "state machine. Check the run-mode / FSM lifecycle."
                )
                stack = AsyncExitStack()
                agent_obj = None
                try:
                    await stack.__aenter__()
                    await stack.enter_async_context(self._ota_scope(sub_ctx))
                    # Build the generator AFTER the swap so its ``ctx``
                    # parameter is the fresh sub-context.
                    agent_obj = self.on_agent(sub_ctx, self.ctx)
                except BaseException:
                    if agent_obj is not None:
                        try:
                            await agent_obj.aclose()
                        except Exception:
                            pass
                    try:
                        await stack.__aexit__(None, None, None)
                    except Exception:
                        pass
                    raise
                fsm.agent_mode_stack = stack
                fsm.agent_gen = agent_obj
                fsm.scope = "agent"
                result = None
            else:
                # 4. Inline path: drive the fresh sub-run to completion
                #    against the fresh sub-context, then restore the parent.
                async with self._ota_scope(sub_ctx):
                    result = await self._invoke_template(
                        self.on_agent(sub_ctx, self.ctx), scope="agent",
                    )

            if envelope:
                self._record_enter_agent(item, result)
            return result
        finally:
            if envelope:
                self._log_depth -= 1

    async def _run_fallback_agent(self, goal: str) -> Any:
        """Run a bounded recovery sub-run inline and return its conclusion.

        Step-level fallback — unlike full fallback, which hands ``on_agent``
        to the state machine for the rest of the run — is a *bounded*
        recovery: a fresh OTA episode runs to completion against ``goal``,
        and its conclusion is what the caller shapes into the failed step's
        return type and asends to the resuming workflow.

        The conclusion is read off the **isolated sub-context** — the
        sub-run's ``RETURN`` value, else its last think step's
        ``step_content``. It deliberately never touches
        ``self._final_answer``: that slot is owned by the run drivers
        (``_agent`` / ``_workflow`` / ``_amphiflow``) for the run's *own*
        final answer (``return self._final_answer or summary()``), so a
        helper must not reset it. The recovery agent's think step still
        updates ``self._final_answer`` naturally (as any agent run does) —
        last meaningful answer wins, overwritten if the resuming workflow
        yields its own ``RETURN``.

        Nothing is injected and no toolset is mutated — the sub-run carries
        the OTA context class's declared tools, same as any other sub-run.
        """
        sub_ctx = self._ota_context_class(user_input=goal)
        async with self._ota_scope(sub_ctx):
            result = await self._invoke_template(
                self.on_agent(sub_ctx, self.ctx), scope="agent",
            )
        if result is not None:
            return result
        # No RETURN — fall back to the recovery run's last think conclusion,
        # read off the isolated sub-context (never ``self._final_answer``).
        last_decision = sub_ctx.think_result
        return getattr(last_decision, "step_content", None) or None

    async def _run_human_call(self, item: "HumanCall") -> str:
        """Run one HumanCall and emit ``[Human Interaction]`` header +
        ``-> result:`` arrow. ``_record_human_call`` is invoked here so
        the trace + log live in this method (not the dispatcher).
        """
        async def _stdin_human_fallback(prompt: str) -> str:
            """Default human-input source when no ``@human_channel`` is registered.

            Reads a single line from stdin in a thread executor so the
            event loop is not blocked. Tests stub by monkey-patching
            ``builtins.input``.
            """
            loop = asyncio.get_event_loop()
            return await loop.run_in_executor(
                None, input, f"\n[HumanInput] {prompt}\n> "
            )

        prompt = item.prompt
        channel = item.channel

        channel_str = channel or "default"
        self._log(
            "Human Interaction",
            f"{channel_str}: {_brief(prompt or '')}",
            color="purple",
        )
        self._log_depth += 1
        try:
            registry = type(self)._human_channels
            if not registry:
                response = await _stdin_human_fallback(prompt)
            else:
                ch = channel
                if ch is None:
                    if len(registry) != 1:
                        raise RuntimeError(
                            "HumanCall(channel=None) is ambiguous: "
                            f"{len(registry)} channels registered "
                            f"({sorted(registry.keys())}). Specify channel='name' "
                            "explicitly."
                        )
                    ch = next(iter(registry))
                method_name = registry.get(ch)
                if method_name is None:
                    raise RuntimeError(
                        f"Unknown human channel: {ch!r}. "
                        f"Registered: {sorted(registry.keys())}"
                    )
                response = await getattr(self, method_name)(prompt)
            self._record_human_call(item, response)
            return response
        finally:
            self._log_depth -= 1

    async def _run_llm_call(self, item: LLMCall) -> Any:
        """Run one LLMCall and emit ``[LLM Query]`` header +
        ``-> result:`` arrow. ``_record_llm_call`` is invoked here so
        the trace + log live in this method (not the dispatcher).
        """
        self._log("LLM Query", item.protocol, color="white")
        self._log_depth += 1
        try:
            if self._llm is None:
                raise RuntimeError(
                    f"LLMCall(protocol={item.protocol!r}) requires self._llm, "
                    "but no LLM was passed to arun(llm=...)."
                )

            messages: List[Message] = []
            if item.history:
                messages.extend(item.history)
            messages.append(Message.from_text(item.prompt, role=Role.USER))

            if item.protocol == "chat":
                response = await self._llm.achat(messages)
                text = ""
                msg = getattr(response, "message", None)
                if msg is not None:
                    text = msg.content or ""
                if not text:
                    text = str(response)
                result = text
            elif item.protocol == "structure_output":
                if not isinstance(self._llm, StructuredOutput):
                    raise TypeError(
                        f"LLM {type(self._llm).__name__} does not implement the "
                        "StructuredOutput protocol; cannot satisfy "
                        "LLMCall(protocol='structure_output')."
                    )
                result = await self._llm.astructured_output(messages, item.constraint)
            elif item.protocol == "tool_selector":
                if not isinstance(self._llm, ToolSelection):
                    raise TypeError(
                        f"LLM {type(self._llm).__name__} does not implement the "
                        "ToolSelection protocol; cannot satisfy "
                        "LLMCall(protocol='tool_selector')."
                    )
                result = await self._llm.aselect_tool(messages, item.tools)
            else:
                raise ValueError(
                    f"Unknown LLMCall protocol: {item.protocol!r}. "
                    "Expected 'chat', 'structure_output', or 'tool_selector'."
                )

            self._record_llm_call(item, result)
            return result
        finally:
            self._log_depth -= 1

    async def _run_think_unit(
        self,
        item: ThinkUnit,
    ) -> Any:
        """Drive one ``ThinkUnit`` yield through its observe-think-act cycle.

        Returns the think unit's result — the finishing think's
        ``step_content`` — which becomes the ``yield ThinkUnit(...)`` value.

        Resolves the descriptor from ``item.name``, clones the
        ``CognitiveWorker`` template (state isolation), resolves
        per-yield overlays against descriptor defaults, sets up the
        runtime env (LLM injection, verbose), and runs the OTC loop.

        Emits the ``[Think] <name>`` header + bumps ``_log_depth`` so
        per-cycle arrows nest underneath. Mirrors ``_run_think_agent``
        in shape.
        """
        ########################
        # Resolve descriptor + overlays
        ########################
        descriptor = getattr(type(self), item.name, None)
        if not isinstance(descriptor, ThinkUnitDescriptor):
            raise AttributeError(
                f"ThinkUnit(name={item.name!r}) does not match any "
                f"think_unit declaration on {type(self).__name__}."
            )

        until = item.until if item.until is not None else descriptor._until
        max_attempts: int = (
            item.max_attempts if item.max_attempts is not None
            else descriptor._max_attempts
        )
        # on_error / max_retries are descriptor-only (no per-yield overlay).
        on_error: ErrorStrategy = descriptor._on_error
        max_retries: int = descriptor._max_retries

        ########################
        # Clone worker (state isolation)
        ########################
        worker = ThinkUnitDescriptor._clone_worker(descriptor._worker_template)
        worker_label = worker.__class__.__name__

        ########################
        # [Think] header + depth bump
        ########################
        self._log("Think", item.name, color="cyan")
        self._log_depth += 1
        try:
            result = await self._run_think_unit_body(
                worker, worker_label,
                until=until,
                max_attempts=max_attempts,
                on_error=on_error,
                max_retries=max_retries,
            )
        finally:
            self._log_depth -= 1

        return result

    async def _run_think_unit_body(
        self,
        worker: CognitiveWorker,
        worker_label: str,
        *,
        until: Optional[Union[Callable[..., bool], Callable[..., Awaitable[bool]]]] = None,
        max_attempts: int = 1,
        on_error: ErrorStrategy = ErrorStrategy.RAISE,
        max_retries: int = 0,
    ) -> None:
        """OTC body — the actual ``CognitiveWorker`` observe-think-act loop.

        Split out from ``_run_think_unit`` so the verbose-injection /
        token-tracking ``try / finally`` keeps its shape; the outer method
        wraps it with descriptor resolution + ``[Think]`` header.

        The toolset the LLM sees is whatever the worker's ``thinking()``
        assembles from ``ota_context.tools`` (the OTA loop owns the tool
        registry) — the think unit no longer narrows it. Its only
        knobs are loop control (``max_attempts`` / ``until``) and the
        per-cycle error policy (``on_error`` / ``max_retries``).
        """
        ########################
        # Setup runtime env.
        ########################
        # The active small-loop OTA context the worker operates on (stable for
        # the whole OTC loop — a ThinkUnit never swaps the delegation scope).
        ota_ctx = self.ota_ctx
        if ota_ctx is None:
            raise RuntimeError(
                "Cannot call _run_think_unit(): no active context. "
                "_run_think_unit() must be called within an on_agent() method."
            )

        # LLM (final CognitiveWorker has no set_llm — LLM is set directly)
        if worker._llm is None and self._llm is not None:
            worker._llm = self._llm
        if worker._llm is None:
            raise RuntimeError(
                f"ThinkUnit's CognitiveWorker ({worker_label}) has no LLM. "
                "Either pass llm=... to arun(), or set llm on the "
                "CognitiveWorker template itself."
            )

        # verbose
        injected_verbose = False
        if worker._verbose is None:
            worker._verbose = self._verbose
            injected_verbose = True

        # spent-tokens delta tracker
        tokens_before = worker.spent_tokens

        ########################
        # OTC cycle closure
        ########################
        async def _run_observe_think_act(cycle: int) -> bool:
            # 0. Open a fresh OTA round at cycle start
            ota_ctx.open_record()

            # 1. Observe (worker → agent fallback) → ``ota.obs_result``.
            obs = await self._invoke_template(worker.observation(ota_ctx))
            if obs is _DELEGATE or obs is None:
                obs = await self._invoke_template(self.observation(ota_ctx, self.ctx))
            if obs is not None:
                ota_ctx.obs_result = obs

            # 2. Think (worker reads the small-loop OTA ``ota_ctx``
            decision = await worker.arun(ota_context=ota_ctx, context=self.ctx)
            self._record_think_unit(worker, obs, decision, cycle=cycle)
            # Fold the full decision onto the round (the act path re-folds the
            # same via _run_action_call; the finish path below relies on it too).
            self.ota_ctx.think_result = decision
            if decision.tool_calls == []:
                # No tool calls → this IS the finish; the think text is both
                # the run's final answer and the ``yield ThinkUnit`` result.
                self.ota_ctx.action_result = None
                self._final_answer = decision.step_content
                return True, decision.step_content

            # 3. Act — execute the tool calls. On a non-finishing cycle the
            # ``yield ThinkUnit`` result is still the latest think text.
            await self._run_action_call(decision, _worker=worker, top_level=False)
            return False, decision.step_content

        # Run loop with on_error handling, then restore environment.
        result: Any = None
        try:
            for cycle_idx in range(max_attempts):
                cycle_num = cycle_idx + 1
                try:
                    finished, result = await _run_observe_think_act(cycle_num)
                except Exception as e:
                    if on_error == ErrorStrategy.RAISE:
                        raise RuntimeError(
                            f"Worker '{worker_label}' failed during "
                            f"observe-think-act cycle: {e}"
                        ) from e
                    elif on_error == ErrorStrategy.IGNORE:
                        # ``result`` keeps the last successful cycle's
                        # ``step_content`` (None if none has succeeded) —
                        # an ignored cycle contributes no value.
                        finished = False
                    elif on_error == ErrorStrategy.RETRY:
                        finished = False
                        for attempt in range(max_retries + 1):
                            try:
                                finished, result = await _run_observe_think_act(cycle_num)
                                break
                            except Exception as retry_e:
                                if attempt == max_retries:
                                    raise RuntimeError(
                                        f"Worker '{worker_label}' failed after "
                                        f"{max_retries + 1} retries: {retry_e}"
                                    ) from retry_e
                else:
                    if finished:
                        break
                    if until is not None:
                        cond_result = until(ota_ctx)
                        if inspect.iscoroutine(cond_result):
                            cond_result = await cond_result
                        if cond_result:
                            break
        finally:
            self.spent_tokens += worker.spent_tokens - tokens_before
            if injected_verbose:
                worker._verbose = None

        return result

    async def _run_think_agent(self, item: ThinkAgent) -> Any:
        """Drive one ``ThinkAgent`` yield through one delegated cycle.

        Resolves the descriptor from ``item.name``, clones the
        ``AgentWorker`` template (state isolation), runs the delegation
        against a **fresh nested OTA context** (its ``goal`` is the
        per-yield ``goal`` overlaid on the parent's; its ``tools`` are the
        ``expose_tools``-filtered parent toolset), runs the observation
        phase (worker → agent fallback), then drives the worker. The
        parent OTA context is restored when the delegation ends — it is
        never mutated (isolation by construction, replacing the removed
        snapshot mechanism).

        **Decision channel.** The worker does NOT execute the external
        agent's tool calls — it only *produces* decisions, exactly like
        ``CognitiveWorker``. Each MCP tool call the external agent makes
        is surfaced onto a per-delegation ``asyncio.Queue`` as a
        ``(decision, future)`` pair; a consumer task — owned here, alive
        only for this one delegation — pulls each, runs it through
        ``_run_action_call`` against the fresh sub-context (so
        ``before_action`` / ``after_action`` hooks fire and the call lands
        in the sub-run's rounds + the trace), and resolves the future.
        ``AmphibiousAutoma`` is the only place that *acts*.

        Per-yield knobs flow through the fresh sub-context exactly the way
        ``CognitiveWorker`` reads its inputs — no worker-side slots, no
        second protocol. ``AgentWorker.thinking()`` reads ``context.goal``
        directly (the fresh sub-context's).

        Mirrors ``_run_think_unit`` in shape — the two cognitive-
        composition drivers share the same skeleton.
        """
        ########################
        # Resolve descriptor + per-yield overlays
        ########################
        descriptor = getattr(type(self), item.name, None)
        if not isinstance(descriptor, ThinkAgentDescriptor):
            raise AttributeError(
                f"ThinkAgent(name={item.name!r}) does not match any "
                f"think_agent declaration on {type(self).__name__}."
            )

        expose_tools_filter: Optional[List[str]] = (
            item.expose_tools if item.expose_tools is not None
            else descriptor._expose_tools
        )

        ########################
        # Build the fresh nested OTA context for this delegation
        ########################
        # ``yield ThinkAgent(goal=...)`` becomes the sub-context's goal
        # (else inherit the parent's); ``expose_tools`` narrows the parent's
        # ``ota.tools`` to the whitelisted set — the external agent only ever
        # sees / calls these (it MCP-ifies ``ota.tools``), so the filter is a
        # real construction-time narrowing here, not just a render-time one.
        # ``self.ota_ctx`` is still the parent here — the scope swap to
        # ``sub_ctx`` happens below via ``_ota_scope``.
        parent_ota = self.ota_ctx
        sub_goal: Any = item.goal if item.goal is not None else parent_ota.user_input
        sub_tools = self._filter_tools(parent_ota.tools, expose_tools_filter)
        sub_ctx = self._ota_context_class(user_input=sub_goal, tools=sub_tools)

        ########################
        # Clone worker (state isolation) + wire the decision channel
        ########################
        worker = ThinkAgentDescriptor._clone_worker(descriptor._worker_template)
        decision_channel: asyncio.Queue = asyncio.Queue()
        worker._decision_channel = decision_channel

        async def _execute_decisions() -> None:
            """Per-delegation consumer: pull the decisions the worker
            surfaces from the external agent's MCP tool calls, run each
            through ``_run_action_call`` (folding onto the fresh
            sub-context), resolve the result future.

            Lives only for this one delegation — it ends as soon as the
            ``_DELEGATION_DONE`` sentinel arrives (put in the ``finally``
            below, after the worker has finished and the channel is
            drained).
            """
            while True:
                msg = await decision_channel.get()
                if msg is _DELEGATION_DONE:
                    return
                decision, result_future = msg
                try:
                    step = await self._run_action_call(decision, _worker=worker, top_level=False)
                    result_future.set_result(step)
                except Exception as exc:  # surface to the worker's await
                    result_future.set_exception(exc)

        ########################
        # [ThinkAgent] header + depth bump
        ########################
        self._log(
            "ThinkAgent",
            f"{item.name}  goal={_brief(item.goal or '')}",
            color="yellow",
        )
        self._log_depth += 1
        try:
            ########################
            # Drive within the fresh sub-context, alongside the consumer
            ########################
            consumer = asyncio.create_task(_execute_decisions())
            try:
                async with self._ota_scope(sub_ctx):
                    result = await self._run_think_agent_body(worker)
            finally:
                # Worker is done → no more decisions can arrive (the
                # external agent blocks on each call's result, so the
                # channel is already drained). Signal the consumer to
                # stop and join it.
                await decision_channel.put(_DELEGATION_DONE)
                await consumer

            # ``result`` is an ``AgentResult`` — captured from
            # ``worker.arun``'s return value, mirroring how
            # ``CognitiveWorker.arun`` hands its decision back. The
            # worker keeps no result slot of its own.
            self._record_think_agent(item, result, worker)
            return result.output
        finally:
            self._log_depth -= 1

    async def _run_think_agent_body(
        self,
        worker: AgentWorker,
    ) -> Any:
        """Delegate body — observation + ``AgentWorker.arun``.

        Split out from ``_run_think_agent`` so the verbose-injection +
        token-tracking ``try / finally`` keeps its shape; the outer
        method handles descriptor resolution, installing the fresh
        sub-context (``_ota_scope``), header / depth orchestration, and
        the ``_record_think_agent`` envelope.

        Tests that want to bypass the actual MCP host + subprocess can
        patch this method — by the time it runs, ``self.ota_ctx`` is the
        fresh sub-context (its ``user_input`` / ``tools`` reflect the
        per-yield overlay) so introspection works.

        Returns the ``AgentResult`` from ``worker.arun`` — the parent
        unwraps ``.output`` for the ``yield ThinkAgent`` asend value and
        folds the whole result into the trace envelope.
        """
        ota_ctx = self.ota_ctx
        if ota_ctx is None:
            raise RuntimeError(
                "Cannot call _run_think_agent(): no active context. "
                "_run_think_agent() must be called within an on_agent() method."
            )

        # verbose
        injected_verbose = False
        if worker._verbose is None:
            worker._verbose = self._verbose
            injected_verbose = True

        try:
            ########################
            # Observe (worker → agent fallback)
            ########################
            obs = await self._invoke_template(worker.observation(ota_ctx))
            if obs is _DELEGATE or obs is None:
                obs = await self._invoke_template(self.observation(ota_ctx, self.ctx))
            if obs is not None:
                ota_ctx.obs_result = obs

            ########################
            # Drive the worker — return value is the AgentResult
            ########################
            return await worker.arun(ota_context=ota_ctx, context=self.ctx)
        finally:
            if injected_verbose:
                worker._verbose = None

    async def _run_action_call(
        self,
        decision: Any,
        *,
        _worker: Optional[CognitiveWorker] = None,
        with_hooks: bool = True,
        top_level: bool = True,
    ) -> Step:
        """Execute a thinking decision — the single canonical action executor.

        Executes the decision's ``tool_calls`` via ``action_tool_call()``
        (a decision with none is the finish — no action runs), optionally
        wrapped by ``before_action`` / ``after_action`` hooks. When
        ``_worker`` is given AND ``with_hooks`` is True, the worker-level
        hooks run first and delegate to the agent level via ``_DELEGATE``.

        ``with_hooks=False`` skips ALL before/after_action — reserved for
        the hook-scope ActionCall path, where re-entering the hook chain
        would recurse into the generator that yielded the call.

        ``top_level=True`` (default) emits the ``[Action Execution]``
        header + ``-> observation:`` arrow and bumps ``_log_depth``.
        Callers that wrap this in their own scope (worker OTC inside
        ThinkUnit, the dispatcher's hook-scope branch, MCP bridge in
        ThinkAgent) pass ``top_level=False`` to suppress the header.
        """
        # The active small-loop OTA context
        ota_ctx = self.ota_ctx

        # A nested hook-scope ActionCall (``with_hooks=False``) runs INSIDE the
        # outer round, which already folded the outer decision onto
        # ``think_result``. Since the act phase re-reads ``think_result``, this
        # nested call must not leave its own decision there — save the outer's
        # and restore it on exit. Top-level / OTC calls persist think_result:
        # it is the round's real think.
        _restore_think = not with_hooks
        _outer_think = ota_ctx.think_result if _restore_think else None

        # Top-level: Log
        if top_level:
            desc = getattr(decision, "step_content", "") or ""
            if not desc:
                calls = getattr(decision, "tool_calls", None) or []
                names = [getattr(c, "tool", None) for c in calls]
                names = [t for t in names if t]
                desc = ", ".join(names) if names else "<action>"
            self._log("Action Execution", _brief(desc), color="green")
            self._log_depth += 1

        try:
            # Top-level observation gathering (agent-level only).
            if top_level:
                obs = await self._invoke_template(self.observation(ota_ctx, self.ctx))
                if obs is not None:
                    ota_ctx.obs_result = obs
                    self._log("Observation", _brief(obs), color="green")

            # Fold the decision onto the current round BEFORE before_action so
            # the payload-free hook reads it via ``ota_context.think_result``.
            ota_ctx.think_result = decision

            # Before_action hooks
            if with_hooks:
                with self._hook_log_scope("before_action"):
                    if _worker is not None:
                        worker_ret = await self._invoke_template(
                            _worker.before_action(ota_ctx, self.ctx),
                        )
                        if worker_ret is _DELEGATE or worker_ret is None:
                            agent_ret = await self._invoke_template(
                                self.before_action(ota_ctx, self.ctx),
                            )
                            if agent_ret is not None:
                                ota_ctx.think_result = agent_ret
                        else:
                            ota_ctx.think_result = worker_ret
                    else:
                        agent_ret = await self._invoke_template(
                            self.before_action(ota_ctx, self.ctx),
                        )
                        if agent_ret is not None:
                            ota_ctx.think_result = agent_ret

            # Execute the (possibly hook-modified) decision off
            # ``ota_context.think_result``: run its ``tool_calls`` via
            # ``action_tool_call``, or — when there are none — finish (the
            # content-only think has no action payload).
            final_decision = ota_ctx.think_result
            if getattr(final_decision, "tool_calls", None):
                action_result = await self.action_tool_call(ota_ctx, self.ctx)
                result = Step(result=action_result)
            else:
                # No tool calls — a content-only finish; no action payload.
                result = Step(result=None)

            # Fold the action payload onto the current round BEFORE after_action
            # so the payload-free hook reads it via ``ota_context.action_result``.
            ota_ctx.action_result = result.result

            # Record (trace + ``-> result:`` arrow). Sits between hooks
            # so the arrow lands chronologically between ``-> before_action:``
            # and ``-> after_action:`` arrows.
            self._record_action_call(
                _worker, obs=ota_ctx.obs_result, decision=final_decision,
                action_result=result,
            )

            # After_action hooks — skipped entirely when with_hooks=False.
            if with_hooks:
                with self._hook_log_scope("after_action"):
                    if _worker is not None:
                        delegate = await self._invoke_template(
                            _worker.after_action(ota_ctx, self.ctx),
                        )
                        if delegate is _DELEGATE or delegate is None:
                            await self._invoke_template(self.after_action(ota_ctx, self.ctx))
                    else:
                        await self._invoke_template(self.after_action(ota_ctx, self.ctx))

            return result
        finally:
            if top_level:
                self._log_depth -= 1
            if _restore_think:
                ota_ctx.think_result = _outer_think

    @asynccontextmanager
    async def _ota_scope(self, sub_ctx: OTAContextT):
        """Install ``sub_ctx`` as the active small-loop context for a block.

        Delegation isolation by construction (replaces the removed
        ``snapshot`` / ``_AgentSnapshot`` field-override machinery): a
        fresh :class:`OTAContext` becomes ``self._current_ota_context`` for
        the duration of the block, and the parent OTA context is restored
        on exit (including on exception). The parent context is **never
        mutated** — the sub-run's ``rounds`` accumulate on its own object.

        Parameters
        ----------
        sub_ctx : OTAContextT
            The fresh small-loop context to make active.
        """
        parent_ctx = self._current_ota_context
        self._current_ota_context = sub_ctx
        try:
            yield sub_ctx
        finally:
            self._current_ota_context = parent_ctx

    @staticmethod
    def _filter_tools(
        tools: List[ToolSpec],
        allowed_names: Optional[List[str]],
    ) -> List[ToolSpec]:
        """Return a fresh ``list`` of ``tools`` narrowed to a whitelist.

        When ``allowed_names`` is ``None`` the result is a verbatim copy
        (no narrowing). Always returns a NEW list — the input is never
        mutated, so a sub-run's filtered toolset never aliases the parent's.
        """
        if allowed_names is None:
            return AmphibiousAutoma._clone_tools(tools)
        allowed = set(allowed_names)
        return [tool for tool in tools if tool.tool_name in allowed]

    @staticmethod
    def _clone_tools(tools: List[ToolSpec]) -> List[ToolSpec]:
        """Return a fresh ``list`` carrying the same specs.

        A shallow copy of the list (the ``ToolSpec`` instances are
        shared — they are stateless), so a sub-run's ``ota.tools`` is an
        independent list from the parent's.
        """
        return list(tools)

    ############################################################################
    # Internal helpers — logging, trace recording, override detection.
    ############################################################################

    @contextlib.contextmanager
    def _hook_log_scope(self, hook_name: str):
        """Mark log entries inside the block as belonging to a hook.

        While active, ``_log`` lazily emits a ``[<hook_name>]`` header on
        first call, indents subsequent lines +1, and overrides color to
        gray. Gated by ``self._verbose_hook`` (independent of
        main-flow ``self._verbose``).
        """
        prev = self._log_hook_name
        self._log_hook_name = hook_name
        try:
            yield
        finally:
            self._log_hook_name = prev

    def _log(self, label: str, content: str = "", *, color: str = "white") -> None:
        """Render one log line.

        Two display forms, chosen automatically:

        * **Header** (``depth == 0``, not in hook scope) —
          ``[HH:MM:SS.mmm] [<label>] <content>``. Used for top-level
          Calls (``ActionCall`` / ``LLMCall`` / ``HumanCall`` /
          ``ThinkUnit`` / ``ThinkAgent`` / ``EnterAgent``) and the
          one-shot ``Router`` event.
        * **Arrow** (``depth > 0`` or in hook scope) —
          ``[HH:MM:SS.mmm]   -> <phase>: <content>``. Used for
          sub-phases of a Call: ``observation`` / ``before_action`` /
          ``result`` / ``after_action`` / ``think`` etc. When inside
          ``_hook_log_scope(<name>)`` the phase tag is overridden to
          ``<name>`` (the original ``label`` is discarded) and color
          is forced to gray.

        Long content wraps so continuation lines align with the start
        of the first line's body (after the ``[<label>] `` or
        ``-> <phase>: `` prefix), keeping the column layout intact.

        Gating: main-scope lines need ``self._verbose``; hook-scope
        lines need ``self._verbose_hook`` (independent flags).
        """
        in_hook = self._log_hook_name is not None
        # Gating
        if in_hook:
            if not self._verbose_hook:
                return
        else:
            if not self._verbose:
                return

        # Compose prefix + body. Only header lines (depth 0, not in
        # hook scope) get the timestamp marker — arrow sub-phase lines
        # stay quiet AND lead with a timestamp-width spacer so ``->``
        # aligns under the header's ``[Label]`` column.
        #
        # Indent shape:
        #   depth 0, not hook  →  ``[ts] [Label] content``
        #   depth ≥1 or hook   →  ``<ts_spacer><(depth-1)*2 spaces>-> phase: content``
        if in_hook:
            arrow_indent = " " * (
                _LOG_TS_PREFIX_WIDTH + max(0, self._log_depth - 1) * 2
            )
            prefix = f"{arrow_indent}-> {self._log_hook_name}: "
            body = str(content) if content else str(label)
            # Preserve red for failure visibility — gray would hide a
            # ``✗`` tool-call failure inside a hook. All other colors
            # collapse to gray (hooks are visually subordinate).
            final_color = "red" if color == "red" else "gray"
        elif self._log_depth == 0:
            ts = datetime.now().strftime("[%H:%M:%S.%f]")[:-4] + "]"
            prefix = f"{ts} [{label}] "
            body = str(content)
            final_color = color
        else:
            arrow_indent = " " * (
                _LOG_TS_PREFIX_WIDTH + max(0, self._log_depth - 1) * 2
            )
            prefix = f"{arrow_indent}-> {label}: "
            body = str(content)
            final_color = color

        # Wrap so continuation lines align with body start, at the
        # fixed ``_LOG_TERMINAL_WIDTH``.
        plain = prefix + body
        if len(plain) <= _LOG_TERMINAL_WIDTH or not body:
            printer.print(plain, color=final_color)
            return
        body_width = max(_LOG_TERMINAL_WIDTH - len(prefix), 20)
        wrapped = textwrap.wrap(
            body,
            width=body_width,
            initial_indent="",
            subsequent_indent="",
            break_long_words=True,
            break_on_hyphens=False,
        )
        cont_indent = " " * len(prefix)
        printer.print(prefix + (wrapped[0] if wrapped else ""), color=final_color)
        for line in wrapped[1:]:
            printer.print(cont_indent + line, color=final_color)

    def _record_action_call(
        self,
        worker: Optional[CognitiveWorker],
        obs: Any,
        decision: Any,
        action_result: Step,
    ) -> None:
        """Record + log an act-phase step.

        Called both from worker OTC (per cycle, ``worker`` supplied) and
        from the dispatcher (per ``yield ActionCall``, ``worker=None``).
        The act result is either an ``ActionResult`` (tool calls →
        ``TOOL_CALLS``) or ``None`` (a content-only finish → ``CONTENT_ONLY``).
        """
        tool_calls = []
        output_type = StepOutputType.CONTENT_ONLY
        result_obj = None

        if action_result is not None and isinstance(action_result, Step):
            result_obj = action_result.result
            if isinstance(result_obj, ActionResult):
                output_type = StepOutputType.TOOL_CALLS
                for r in result_obj.results:
                    tool_calls.append({
                        "tool_id": r.tool_id,
                        "tool_name": r.tool_name,
                        "tool_arguments": r.tool_arguments,
                        "tool_result": r.tool_result,
                        "success": r.success,
                        "error": r.error,
                    })

        # Trace storage
        if self._agent_trace is not None:
            self._agent_trace.record_step({
                "name": worker.__class__.__name__ if worker is not None else "workflow",
                "step_content": getattr(decision, "step_content", ""),
                "tool_calls": tool_calls,
                "observation": str(obs) if obs is not None else None,
                "observation_hash": observation_fingerprint(obs),
                "output_type": output_type.value,
            })

        # Log arrow(s). One ``-> result: ...`` line per tool call (so
        # success/failure each get visibility); structured / content-only
        # fall back to a single summary line. Under a ``_hook_log_scope``
        # the "result" label is overridden to the hook name by ``_log``.
        if output_type == StepOutputType.TOOL_CALLS:
            for tc in tool_calls:
                mark = "✓" if tc["success"] else "✗"
                line_color = "green" if tc["success"] else "red"
                content = (
                    f"{tc['tool_name']}({_brief(tc['tool_arguments'])}) "
                    f"{mark} {_brief(tc['tool_result'])}"
                )
                if not tc["success"] and tc["error"]:
                    content += f" — {_brief(tc['error'], n=200)}"
                self._log("result", content, color=line_color)
        else:  # CONTENT_ONLY
            step_content = getattr(decision, "step_content", "")
            if step_content:
                self._log("result", _brief(step_content), color="green")

    def _record_think_unit(
        self,
        worker: CognitiveWorker,
        obs: Any,
        decision: Any,
        cycle: int = 0,
    ) -> None:
        """Log one ``ThinkUnit`` OTC cycle's observation + think phases.

        Called from worker OTC inside ``_run_think_unit`` before
        ``_run_action_call`` fires. The cycle's act phase is logged
        separately by ``_record_action_call`` (invoked inside
        ``_run_action_call`` between the worker hooks). No trace
        storage — the cycle's outcome is captured by the per-cycle
        ``_record_action_call`` trace step.

        ``cycle`` (1-based) — when ``>= 2`` an ``-- cycle N --`` gray
        divider line is emitted before the phase arrows so multi-cycle
        OTC runs are visually delimited. Cycle 1 is the natural opener
        right after the ``[Think]`` header, so no divider for it.
        """
        # Cycle divider (cycle 1+). Gated by ``_verbose`` since this
        # is main-flow output, not hook-scope. Same spacer width as
        # arrow lines so the divider aligns with the surrounding ``->``
        # column.
        if cycle >= 1 and self._verbose:
            divider_indent = " " * (
                _LOG_TS_PREFIX_WIDTH + max(0, self._log_depth - 1) * 2
            )
            printer.print(f"{divider_indent}-- cycle {cycle} --", color="gray")

        if obs is not None:
            self._log("observation", _brief(obs), color="green")
        if decision is not None:
            worker_label = worker.__class__.__name__
            step_content = getattr(decision, "step_content", "") or ""
            content = (
                f"{worker_label}: {_brief(step_content)}" if step_content
                else worker_label
            )
            self._log("think", content, color="cyan")

    def _record_human_call(self, item: "HumanCall", response: str) -> None:
        """Record + log a ``HUMAN_CALL`` step.

        The prompt sits in the ``observation`` slot (closest analog);
        the response and channel land in ``structured_output``.
        """
        response_text = "" if response is None else str(response)

        if self._agent_trace is not None:
            self._agent_trace.record_step({
                "name": "human_call",
                "step_content": f"HumanCall(channel={item.channel or 'default'})",
                "tool_calls": [],
                "observation": item.prompt or None,
                "observation_hash": observation_fingerprint(item.prompt),
                "output_type": StepOutputType.HUMAN_CALL.value,
                "structured_output": {
                    "channel": item.channel,
                    "response": _brief(response_text),
                },
                "structured_output_class": None,
            })

        self._log("result", _brief(response_text), color="purple")

    def _record_llm_call(self, item: LLMCall, result: Any) -> None:
        """Record + log an ``LLM_CALL`` step.

        The prompt sits in the ``observation`` slot; the result is
        serialised into ``structured_output``. ``llm_call_protocol`` on
        the top-level step records which LLM contract was invoked.
        """
        try:
            if isinstance(result, BaseModel):
                serialized = result.model_dump()
                cls_name = (
                    f"{result.__class__.__module__}.{result.__class__.__qualname__}"
                )
            else:
                serialized = {"__value__": result}
                cls_name = type(result).__qualname__
        except Exception:
            serialized = {"__value__": str(result)}
            cls_name = type(result).__qualname__

        if self._agent_trace is not None:
            self._agent_trace.record_step({
                "name": "llm_call",
                "step_content": f"LLMCall({item.protocol})",
                "tool_calls": [],
                "observation": item.prompt or None,
                "observation_hash": observation_fingerprint(item.prompt),
                "output_type": StepOutputType.LLM_CALL.value,
                "structured_output": serialized,
                "structured_output_class": cls_name,
                "llm_call_protocol": item.protocol,
            })

        self._log("result", _brief(result), color="white")

    def _record_think_agent(
        self,
        item: "ThinkAgent",
        result: Any,
        worker: AgentWorker,
    ) -> None:
        """Record a ``THINK_AGENT`` trace step.

        The MCP-bridged tool calls fired *inside* the external agent
        each generate their own ``_record_action_call`` entries via the
        decision-channel path (``AgentWorker._emit_decision`` →
        ``_run_think_agent``'s consumer → ``_run_action_call``). This
        record is the outer envelope marking the yield itself.

        ``result`` is the ``AgentResult`` returned by ``worker.arun`` —
        its ``output`` / ``exit_code`` / ``completion`` plus the worker
        / agent class identities are folded into ``structured_output``
        so the unified ``AgentTrace`` is the single source of truth for
        delegate runs. (The worker keeps no result slot — the outcome
        flows through the return value, mirroring ``CognitiveWorker``.)
        """
        output = getattr(result, "output", None)
        result_preview = _brief(output) if output is not None else ""

        # Record the yield-supplied goal verbatim. The "resolved goal"
        # — whatever the delegation's sub-context ``user_input`` was —
        # is already captured by ``AgentTrace``'s top-level ``goal``
        # field (the original arun input) plus any ``EnterAgent`` step
        # in scope. No need to duplicate here.
        goal = item.goal
        step_content = f"ThinkAgent({item.name!r})"
        if goal:
            step_content += f": {_brief(goal, n=200)}"

        structured: Dict[str, Any] = {
            "goal": goal,
            "result": result_preview or None,
            "exit_code": getattr(result, "exit_code", None),
            "completion_signal": getattr(result, "completion", None),
            "worker_class": (
                f"{type(worker).__module__}.{type(worker).__qualname__}"
            ),
        }
        base_agent = getattr(worker, "_agent", None)
        if base_agent is not None:
            structured["agent_class"] = (
                f"{type(base_agent).__module__}.{type(base_agent).__qualname__}"
            )

        if self._agent_trace is not None:
            self._agent_trace.record_step({
                "name": "think_agent",
                "step_content": step_content,
                "tool_calls": [],
                "observation": None,
                "observation_hash": None,
                "output_type": StepOutputType.THINK_AGENT.value,
                "structured_output": structured,
                "structured_output_class": None,
                "think_agent_name": item.name,
            })

        self._log("final", result_preview or "(no return value)", color="yellow")

    def _record_enter_agent(self, item: "EnterAgent", result: Any) -> None:
        """Record + log an ``ENTER_AGENT`` scope-switch closer.

        Minimal marker — the actual steps that ran inside the agent
        scope each produced their own records (ThinkUnit cycles,
        ThinkAgent yields, etc.). This step exists so the trace
        timeline reflects "we entered agent mode here with this goal
        and exited with this final answer".
        """
        result_text = _brief(result) if result is not None else ""

        if self._agent_trace is not None:
            self._agent_trace.record_step({
                "name": "enter_agent",
                "step_content": f"EnterAgent(goal={item.goal!r})",
                "tool_calls": [],
                "observation": None,
                "observation_hash": None,
                "output_type": StepOutputType.ENTER_AGENT.value,
                "structured_output": {
                    "goal": item.goal,
                    "result": result_text or None,
                },
                "structured_output_class": None,
            })

        self._log("final", result_text or "(no return value)", color="yellow")

    def _has_workflow(self) -> bool:
        """Check whether the subclass has overridden on_workflow().

        ``_validate_template_forms`` at class creation guarantees that an
        overridden ``on_workflow`` is always an async generator function,
        so a plain identity check against the base method is sufficient.
        """
        return type(self).on_workflow is not AmphibiousAutoma.on_workflow

    def _has_agent(self) -> bool:
        """Check whether the subclass has overridden on_agent()."""
        return type(self).on_agent is not AmphibiousAutoma.on_agent

    @staticmethod
    def _build_tool_results(action_result: Optional[Step]) -> List[ToolResult]:
        """Convert an action Step into a List[ToolResult] for asend() back to the generator."""
        if action_result is None:
            return []
        inner = getattr(action_result, "result", None)
        if inner is not None and isinstance(inner, ActionResult):
            return [
                ToolResult(
                    tool_name=r.tool_name,
                    tool_arguments=r.tool_arguments,
                    result=r.tool_result,
                    success=r.success,
                    error=r.error,
                )
                for r in inner.results
            ]
        return []

    ############################################################################
    # Entry point — ``arun`` + mode resolution + GraphAutoma router plumbing.
    # ``router`` ferries to ``_agent`` / ``_workflow`` / ``_amphiflow``
    # based on the resolved mode.
    ############################################################################

    def _resolve_mode(self, mode: RunMode) -> RunMode:
        """Resolve and validate the run mode against overridden template methods.

        Resolution (when ``mode is RunMode.AUTO``):

        - both ``on_agent`` and ``on_workflow`` overridden → ``RunMode.AMPHIFLOW``
        - only ``on_workflow`` overridden → ``RunMode.WORKFLOW``
        - only ``on_agent`` overridden → ``RunMode.AGENT``
        - neither overridden → ``RuntimeError``

        Validation (when an explicit mode is supplied):

        - ``RunMode.AGENT`` requires ``on_agent`` overridden
        - ``RunMode.WORKFLOW`` requires ``on_workflow`` overridden
        - ``RunMode.AMPHIFLOW`` requires both ``on_agent`` and ``on_workflow``
          overridden

        Establishing this invariant at the routing boundary lets the
        downstream drivers (``_agent`` / ``_workflow`` / ``_amphiflow``)
        rely on the presence of the templates they need without
        repeatedly re-checking. In particular, ``_amphiflow`` can assume
        ``on_agent`` is always available for step-level and full
        fallback, eliminating defensive ``_has_agent()`` branches.
        """
        has_agent = self._has_agent()
        has_workflow = self._has_workflow()

        if mode is RunMode.AUTO:
            if has_agent and has_workflow:
                return RunMode.AMPHIFLOW
            if has_workflow:
                return RunMode.WORKFLOW
            if has_agent:
                return RunMode.AGENT
            raise RuntimeError(
                f"{type(self).__name__} must override on_agent() or on_workflow()."
            )

        if mode is RunMode.AGENT and not has_agent:
            raise RuntimeError(
                f"{type(self).__name__} requested mode=RunMode.AGENT but "
                f"does not override on_agent()."
            )
        if mode is RunMode.WORKFLOW and not has_workflow:
            raise RuntimeError(
                f"{type(self).__name__} requested mode=RunMode.WORKFLOW but "
                f"does not override on_workflow()."
            )
        if mode is RunMode.AMPHIFLOW and not (has_agent and has_workflow):
            missing = []
            if not has_agent:
                missing.append("on_agent()")
            if not has_workflow:
                missing.append("on_workflow()")
            raise RuntimeError(
                f"{type(self).__name__} requested mode=RunMode.AMPHIFLOW but "
                f"does not override {' and '.join(missing)}."
            )
        return mode

    @worker(is_start=True)
    async def router(self, mode: RunMode, max_consecutive_fallbacks: int) -> str:
        """
        Router worker: dispatches to the correct execution mode.

        ``RunMode.AUTO`` is resolved upstream in ``arun()``, so this worker
        always receives a concrete mode.
        """
        if mode is RunMode.AGENT:
            self._log("Router", "Ferrying to AGENT mode")
            self.ferry_to("_agent")
        elif mode is RunMode.WORKFLOW:
            self._log("Router", "Ferrying to WORKFLOW mode")
            self.ferry_to("_workflow")
        elif mode is RunMode.AMPHIFLOW:
            self._log("Router", f"Ferrying to AMPHIFLOW mode, max_consecutive_fallbacks={max_consecutive_fallbacks}")
            self.ferry_to("_amphiflow", max_consecutive_fallbacks=max_consecutive_fallbacks)
        else:
            raise RuntimeError(f"Unsupported run mode: {mode!r}")

    @worker(is_output=True)
    async def _agent(self) -> str:
        """AGENT mode entry point.

        Drives ``on_agent`` through ``_invoke_template`` with
        ``scope='agent'``. No state machine, no fallback (agent IS
        already the autonomous tier).

        Returns
        -------
        str
            ``self._final_answer`` (if set by a ``RETURN(value)`` yield
            or by a worker finishing via empty ``tool_calls``) or the
            OTA context's ``summary()``.
        """
        return_value = await self._invoke_template(
            self.on_agent(self.ota_ctx, self.ctx), scope="agent",
        )
        if return_value is not None:
            self._final_answer = str(return_value)
        return self._final_answer or self.ota_ctx.summary()

    @worker(is_output=True)
    async def _workflow(self) -> str:
        """WORKFLOW mode entry point.

        Drives ``on_workflow`` through ``_invoke_template`` with
        ``scope='workflow'``. No fallback — failures propagate.
        ``EnterAgent`` yielded from on_workflow is dispatched through
        ``_dispatch_step``'s recursive ``_invoke_template`` path (works
        without a state machine because there is no fallback to track).

        Returns
        -------
        str
            ``self._final_answer`` (if set by a ``RETURN(value)`` yield)
            or the OTA context's ``summary()``.
        """
        return_value = await self._invoke_template(
            self.on_workflow(self.ota_ctx, self.ctx), scope="workflow",
        )
        if return_value is not None:
            self._final_answer = str(return_value)
        return self._final_answer or self.ota_ctx.summary()

    @worker(is_output=True)
    async def _amphiflow(self, max_consecutive_fallbacks: int) -> str:
        """AMPHIFLOW mode entry point + peer state machine.

        Drives interleaved ``on_workflow`` and ``on_agent`` generators
        with step-level fallback for atomic-Call failures. The loop
        intercepts ``RETURN`` (terminate), and defers other primitives
        to ``_dispatch_step``.

        Step-level fallback is the only thing this driver owns above
        plain dispatch: when ``_dispatch_step`` raises and the failed
        primitive was an atomic Call in workflow scope, it counts the
        failure, runs a bounded inline recovery sub-run
        (``_run_fallback_agent``), shapes that sub-run's final answer
        into the failed step's return type, and asends it to the
        resuming workflow. On threshold breach or a workflow
        generator-internal exception, the workflow generator is closed
        and ``on_agent`` runs linearly via ``_invoke_template`` (full
        fallback — workflow does not resume).
        """
        def _is_atomic_step(item: Any) -> bool:
            """
            Whether ``item`` is a recognized framework atomic primitive.
            """
            return isinstance(item, (
                ActionCall, HumanCall, LLMCall,
                EnterAgent, ThinkUnit, ThinkAgent,
            ))

        def _describe_atomic_step(item: Any) -> str:
            """
            One-line description of an atomic step for logs / fallback goals.
            """
            if isinstance(item, ActionCall):
                return f"ActionCall(tool_name={item.tool_name!r})"
            if isinstance(item, HumanCall):
                channel = item.channel or "<default>"
                return f"HumanCall(channel={channel!r})"
            if isinstance(item, LLMCall):
                return f"LLMCall(protocol={item.protocol!r})"
            return type(item).__name__

        def _shape_fallback_value(item: Any, answer: Any) -> Any:
            """Shape the recovery agent's final answer into the failed step's
            expected return type, so the suspended workflow resumes as if the
            step had produced it. ``answer is None`` (the agent produced
            nothing) degrades to a benign default — chosen so a "void" atomic
            Call (one whose return value the workflow does not use) resumes
            without blowing up downstream code:

            ============================  ====================================
            Failed Call                   Shaped value (``answer`` = agent's)
            ============================  ====================================
            ActionCall                    one ToolResult(result=answer)
            HumanCall                     answer or ""
            LLMCall(protocol="chat")      answer or ""
            LLMCall("structure_output")   answer (best-effort passthrough)
            LLMCall("tool_selector")      ([], answer)
            ============================  ====================================
            """
            if isinstance(item, ActionCall):
                return [
                    ToolResult(
                        tool_name=item.tool_name,
                        tool_arguments=dict(item.tool_args),
                        result=answer,
                        success=True,
                    )
                ]
            if isinstance(item, HumanCall):
                return answer or ""
            if isinstance(item, LLMCall):
                if item.protocol == "chat":
                    return answer or ""
                if item.protocol == "tool_selector":
                    return ([], answer)
                return answer
            return answer

        def _build_fallback_goal(
            item: Any,
            item_label: str,
            error: BaseException,
            fsm: "_AmphiState",
        ) -> str:
            """Goal text fed to on_agent on step-level fallback.

            Tells the agent (a) what failed and why, and (b) that its final
            answer becomes the value the failed step should have returned —
            the workflow resumes with it. There is no tool to call and no
            toolset is touched: the recovery sub-run's conclusion IS the
            resolution.
            """
            if isinstance(item, ActionCall):
                intent = item.description or item.tool_name
            else:
                intent = item_label
            return (
                f"[Workflow fallback] Step {fsm.step_index} failed.\n"
                f"Step intent: {intent}\n"
                f"Failed call: {item_label}\n"
                f"Error: {error}\n\n"
                f"Recover however you see fit. Your final answer becomes the "
                f"value the failed step should have returned — the workflow "
                f"resumes with it as if the step had succeeded. If the failed "
                f"call's return value is not used downstream, a brief "
                f"acknowledgement is fine."
            )

        # Initialize the state machine with the workflow generator before `while` loop
        # With workflow as the main focus
        workflow_gen = self.on_workflow(self.ota_ctx, self.ctx)
        self._amphi = _AmphiState(
            workflow_gen=workflow_gen,
            max_consecutive_fallbacks=max_consecutive_fallbacks,
        )
        fsm = self._amphi

        ########################
        # State machine main loop
        ########################
        try:
            while not fsm.should_break:
                # Pick the active generator slot based on scope.
                if fsm.scope == "agent":
                    gen, send = fsm.agent_gen, fsm.agent_send
                    fsm.agent_send = None
                else:
                    gen, send = fsm.workflow_gen, fsm.workflow_send
                    fsm.workflow_send = None

                # Advance the chosen generator.
                try:
                    if send is None:
                        item = await gen.__anext__()
                    else:
                        item = await gen.asend(send)
                except StopAsyncIteration:
                    # If it is Agent Mode stop.
                    if fsm.scope == "agent":
                        # TODO: introduce a symmetric agent → workflow switch primitive.
                        #
                        # Today the handoff is asymmetric: workflow → agent is explicit (the user yields ``EnterAgent``, and
                        # ``_enter_agent`` performs the switch), but agent → workflow is implicit — an on_agent run
                        # is bounded by a snapshot scope (a "sub-task"), and "returning to workflow" is signalled by the
                        # generator naturally exhausting. There is no agent-side primitive that mirrors ``EnterAgent``;
                        # exhaustion under a bounded scope is the only way the state machine learns the agent is done.
                        #
                        # Symmetric design: add an agent-side primitive (e.g. ``enter_workflow(value)``) that the agent tool call
                        # to deliberately hand control back. ``_dispatch_step`` would handle that yield the way this branch
                        # currently handles ``StopAsyncIteration`` — tear down the agent slot, forward ``value`` via
                        # ``workflow_send``, restore ``scope = "workflow"``. Exhaustion would degrade
                        # to a default empty-return fallback (or be a strict-mode error).
                        #
                        # Until that primitive exists, this branch is the single point where the implicit "agent done →
                        # resume workflow / terminate run" decision lives.

                        # Agent generator exhausted.
                        if fsm.agent_mode_stack is not None:
                            await fsm.agent_mode_stack.__aexit__(None, None, None)
                            fsm.agent_mode_stack = None
                        fsm.agent_gen = None

                        # Full-fallback exhaustion: the workflow is dead, the
                        # run is over.
                        if fsm.workflow_gen is None:
                            fsm.should_break = True
                        # User-yielded EnterAgent exhausted: resume the workflow
                        # at the instruction after the EnterAgent yield. (Step-
                        # level fallback never reaches here — it runs inline.)
                        else:
                            fsm.scope = "workflow"
                        continue

                    # If it is Workflow Mode stop. 
                    else:
                        fsm.should_break = True
                        continue 
                except Exception as e:
                    # If agent body raised
                    if fsm.scope == "agent":
                        if fsm.agent_mode_stack is not None:
                            await fsm.agent_mode_stack.__aexit__(type(e), e, e.__traceback__)
                            fsm.agent_mode_stack = None
                        fsm.agent_gen = None
                        raise

                    # If Workflow generator-internal error → full fallback.
                    fsm.workflow_gen = None
                    await self._enter_agent()
                    continue

                # RETURN is a control-flow signal — terminate the FSM
                # loop with the carried value. All other primitives
                # (including EnterAgent) go through the dispatcher.
                if isinstance(item, RETURN):
                    fsm.return_value = item.value
                    fsm.should_break = True
                    continue

                try:
                    outcome = await self._dispatch_step(item, scope=fsm.scope)
                except Exception as e:
                    # Agent-scope error / unknown yield type: no fallback, just propagate the exception.
                    if fsm.scope == "agent" or not _is_atomic_step(item):
                        raise

                    # Set up for fallback info
                    fsm.consecutive_failures += 1
                    fsm.step_index += 1
                    item_label = _describe_atomic_step(item)
                    fsm.failed_steps.append(f"Step {fsm.step_index}: {item_label}{e}")

                    # Full fallback.
                    if fsm.consecutive_failures >= fsm.max_consecutive_fallbacks:
                        try:
                            await fsm.workflow_gen.aclose()
                        except Exception:
                            pass
                        fsm.workflow_gen = None
                        await self._enter_agent()
                        continue

                    # Step-level fallback. Run a bounded recovery sub-run
                    # inline; its final answer, shaped into the failed step's
                    # return type, is asend-ed to the resuming workflow. No
                    # tool is injected and no toolset is mutated — the recovery
                    # sub-run's conclusion IS the resolution.
                    #
                    # TODO(amphiflow step-level fallback): this recovery
                    # semantics is still awkward and needs a rethink. Mapping
                    # the recovery agent's free-form conclusion (a str) onto the
                    # failed step's *typed* return via ``_shape_fallback_value``
                    # is a loose fit (esp. ActionCall -> List[ToolResult] and
                    # structure_output), and clearing ``_final_answer`` below is
                    # a patch over the recovery sub-run's think-step writing the
                    # shared run state. Revisit: a dedicated recovery-value
                    # channel, or reconsider whether a recovered value should
                    # feed back into the workflow at all. Left as-is for now.
                    else:
                        fallback_goal = _build_fallback_goal(item, item_label, e, fsm)
                        recovered = await self._run_fallback_agent(fallback_goal)
                        fsm.workflow_send = _shape_fallback_value(item, recovered)
                        # The recovered value flows to the workflow via
                        # ``workflow_send`` — it is an internal step value, not
                        # the run's answer. Clear the ``_final_answer`` that the
                        # recovery sub-run's think step set on the shared run
                        # state, so the run's final answer comes from the
                        # resuming workflow (or ``summary()``), never the
                        # internal recovery.
                        self._final_answer = None
                        continue
                else:
                    if fsm.scope == "agent":
                        fsm.agent_send = outcome
                    else:
                        fsm.workflow_send = outcome
                        fsm.consecutive_failures = 0
                        fsm.step_index += 1
        finally:
            # Cleanup order: agent_gen (may be mid-yield) → agent_mode_stack (snapshot) → workflow_gen. 
            if fsm.agent_gen is not None:
                try:
                    await fsm.agent_gen.aclose()
                except Exception:
                    pass
            if fsm.agent_mode_stack is not None:
                try:
                    await fsm.agent_mode_stack.__aexit__(None, None, None)
                except Exception:
                    pass
            if fsm.workflow_gen is not None:
                try:
                    await fsm.workflow_gen.aclose()
                except Exception:
                    pass
            return_value = fsm.return_value
            self._amphi = None

        if return_value is not None:
            self._final_answer = str(return_value)
        return self._final_answer or self.ota_ctx.summary()

    async def arun(
        self,
        *,
        user_input: Any = "",
        llm: Optional[BaseLlm] = None,
        context: Optional[ContextT] = None,
        ota_context: Optional[OTAContextT] = None,
        mode: Optional[RunMode] = RunMode.AUTO,
        max_consecutive_fallbacks: int = 1,
        trace: bool = False,
        workdir: Optional[Union[Path, str]] = None,
    ) -> str:
        """Run the agent. Returns a summary of the final context.

        Two contexts, two loops. ``context=`` is the **loop** knowledge
        context (free-form, optional — defaults to an empty ``_context_class``);
        the framework constructs a fresh **small-loop** ``OTAContext`` per run
        from ``_ota_context_class``, seeded with ``user_input`` — unless the
        caller passes a pre-built ``ota_context=``, which is then used verbatim
        (its own ``user_input`` stands). That lets the caller seed per-run
        small-loop state — e.g. inject a per-turn resource the workers/hooks
        read back off ``ota_context``. Pure dispatch:
        the automa only schedules and no longer assembles any toolset — each
        OTA context declares the tools it carries on its class via
        ``OTAContext.tool`` (framework builtins it wants + its own), so whatever
        a context declared is exactly what its ``tools`` field holds.

        ``mode=RunMode.AUTO`` (default) picks AMPHIFLOW / WORKFLOW / AGENT
        from which template methods the subclass overrides.

        ``trace`` and ``workdir`` are orthogonal:

        * ``trace=True`` activates an in-memory ``AgentTrace`` (survives
          on ``self._agent_trace`` after the run for inspection).
        * ``workdir=path`` materialises ``<workdir>/runs/<run_id>/`` —
          the run directory — independent of whether the trace is active.
        * Both set ⇒ ``AgentTrace`` incrementally persists the single
          ``<run>/trace.json`` (goal + metadata + history) — the run
          directory's only artifact.
        * ``trace=False, workdir=path`` ⇒ the run dir is created but
          empty (nothing writes ``trace.json``).

        ``max_consecutive_fallbacks`` (AMPHIFLOW only) is the workflow
        step-failure threshold before switching to full agent mode.
        """
        async def _run_and_report(context: ContextT) -> str:
            """Run the agent, measure time, and log summary."""
            start_time = time.time()
            result = await GraphAutoma.arun(
                self, self._run_mode,
                max_consecutive_fallbacks=max_consecutive_fallbacks,
            )
            self.spent_time = time.time() - start_time

            if self._verbose:
                agent_name = self.name or self.__class__.__name__
                separator = "=" * 50
                printer.print(separator, color="cyan")
                printer.print(
                    f"  {agent_name} | Completed\n"
                    f"Tokens: {self.spent_tokens} | "
                    f"Time: {self.spent_time:.2f}s",
                    color="cyan"
                )
                printer.print(separator, color="cyan")

            return result

        ########################
        # Pre-initialize status
        ########################
        # Config
        self._llm = llm
        self._run_mode = self._resolve_mode(mode if mode is not None else RunMode.AUTO)

        # Trace
        self._read_tracker = {}
        self._current_run_dir = None
        self._agent_trace = None

        # State
        self._final_answer = None
        self.spent_tokens = 0
        self.spent_time = 0.0
        self._log_depth = 0
        self._log_hook_name = None

        ########################
        # Run-dir + trace activation — orthogonal axes.
        #   trace=True  → AgentTrace is created (in-memory recorder).
        #   workdir set → <workdir>/runs/<run_id>/ is materialised.
        #   Both set    → AgentTrace also persists trace.json there.
        ########################
        run_id: Optional[str] = None
        if workdir is not None:
            run_id = make_run_id()
            self._current_run_dir = ensure_run_dir(Path(workdir).expanduser().resolve(), run_id)

        if trace:
            self._agent_trace = AgentTrace(workdir=self._current_run_dir)

        ########################
        # Initialize the two contexts (pure dispatch — no toolset assembly).
        #   * Loop — caller-supplied free-form knowledge context, or a fresh
        #            default ``_context_class`` when none was passed.
        #   * OTA  — a caller-supplied pre-built small-loop context, or a fresh
        #            one constructed per run seeded with ``user_input``.
        # Each context already carries its own declared ``tools`` (populated
        # from its class's ``OTAContext.tool`` registrations); the framework
        # does not inject or merge any tools here.
        ########################
        if context is not None and not isinstance(context, self._context_class):
            raise ValueError(
                f"context= must be an instance of {self._context_class.__name__} "
                f"(the loop context), got {type(context).__name__}."
            )
        if ota_context is not None and not isinstance(ota_context, self._ota_context_class):
            raise ValueError(
                f"ota_context= must be an instance of {self._ota_context_class.__name__} "
                f"(the small-loop context), got {type(ota_context).__name__}."
            )

        loop_ctx = context if context is not None else self._context_class()
        ota_ctx = ota_context if ota_context is not None else self._ota_context_class(user_input=user_input)
        self._current_ota_context = ota_ctx
        self._current_context = loop_ctx

        ########################
        # Run the amphibious automa
        ########################
        token = current_agent.set(self)
        try:
            # Trace lifecycle — begin.
            if self._agent_trace is not None:
                self._agent_trace.begin_run(
                    goal=str(ota_ctx.user_input or ""),
                    agent_class=f"{type(self).__module__}.{type(self).__qualname__}",
                    agent_name=self.name,
                    context_class=(
                        f"{self._context_class.__module__}.{self._context_class.__qualname__}"
                        if self._context_class else None
                    ),
                    mode=self._run_mode.value,
                    run_id=run_id,
                    max_consecutive_fallbacks=max_consecutive_fallbacks,
                    start_time=time.time(),
                )
            return await _run_and_report(context=loop_ctx)
        finally:
            # Trace lifecycle — end.
            if self._agent_trace is not None:
                try:
                    self._agent_trace.end_run(
                        end_time=time.time(),
                        spent_tokens=self.spent_tokens,
                        spent_time=self.spent_time,
                    )
                except Exception:
                    pass
            self._current_run_dir = None
            self._run_mode = None
            self._llm = None
            current_agent.reset(token)

llm property

llm: Optional[Any]

LLM of the active or most recent arun (None before the first run and after arun clears it in finally).

ota_ctx property

ota_ctx: Optional[OTAContextT]

The active small-loop (OTA) context.

Freshly constructed per arun and swapped to a nested sub-context for the span of a delegation (EnterAgent / ThinkAgent / step-level fallback) by _ota_scope. Internal methods read the active context through this accessor instead of threading it as a parameter; the underlying slot (_current_ota_context) is written only by arun and _ota_scope.

ctx property

ctx: Optional[ContextT]

The loop (knowledge) context — the free-form context passed to arun(context=) (or a fresh default when none was supplied).

Shared read-only across the parent run and any nested delegation; only the small loop (ota_ctx) is isolated per sub-run.

final_answer property

final_answer: Optional[str]

The final answer produced by the last arun() call.

Automatically captured from the step_content of the finishing step (agent mode) or the last executed step (workflow mode). Top-level template-method generators may override the auto-captured value by yielding RETURN(value).

observation

async
observation(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> AsyncGenerator[Any, Any]

Agent-level default observation, shared across all workers.

Called before each thinking phase; workers' own observation() delegates here when it returns _DELEGATE / None.

Yield RETURN(text) to set ota_context.obs_result for this cycle. Exhausting without RETURN (or yielding RETURN(None)) preserves the previous ota_context.obs_result — so after_action-driven refresh patterns work without a dedicated passthrough override.

async def observation(self, ota_context, context=None): ... snapshot = yield ActionCall("bash", command="bridgic-browser snapshot") ... yield RETURN(snapshot[0].result)

Source code in bridgic/amphibious/_amphibious_automa.py
async def observation(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
    """Agent-level default observation, shared across all workers.

    Called before each thinking phase; workers' own ``observation()``
    delegates here when it returns ``_DELEGATE`` / ``None``.

    Yield ``RETURN(text)`` to set ``ota_context.obs_result`` for this
    cycle. Exhausting without ``RETURN`` (or yielding ``RETURN(None)``)
    **preserves** the previous ``ota_context.obs_result`` — so
    ``after_action``-driven refresh patterns work without a dedicated
    passthrough override.

    >>> async def observation(self, ota_context, context=None):
    ...     snapshot = yield ActionCall("bash", command="bridgic-browser snapshot")
    ...     yield RETURN(snapshot[0].result)
    """
    if False:  # pragma: no cover — async generator stub
        yield

on_agent

async
on_agent(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> AsyncGenerator[Any, Any]

Agent mode: LLM-driven cognitive flow.

Override to declare the agent's strategy. on_agent body is reserved for orchestrating cognitive steps — only ThinkUnit / ThinkAgent / RETURN are allowed (deterministic tool / HITL / direct-LLM operations belong in on_workflow or a hook). Without RETURN, the framework auto-captures the final answer from the last think step's step_content.

async def on_agent(self, ota_context, context=None): ... yield ThinkUnit("main_think", max_attempts=20) ... yield ThinkUnit("exec_think", until=lambda c: c.done) ... yield RETURN(ota_context.ota_record[-1].think_result.step_content)

Source code in bridgic/amphibious/_amphibious_automa.py
async def on_agent(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
    """Agent mode: LLM-driven cognitive flow.

    Override to declare the agent's strategy. on_agent body is
    reserved for orchestrating cognitive steps — only ``ThinkUnit``
    / ``ThinkAgent`` / ``RETURN`` are allowed (deterministic tool /
    HITL / direct-LLM operations belong in on_workflow or a hook).
    Without ``RETURN``, the framework auto-captures the final answer
    from the last think step's ``step_content``.

    >>> async def on_agent(self, ota_context, context=None):
    ...     yield ThinkUnit("main_think", max_attempts=20)
    ...     yield ThinkUnit("exec_think", until=lambda c: c.done)
    ...     yield RETURN(ota_context.ota_record[-1].think_result.step_content)
    """
    if False:  # pragma: no cover — async generator stub
        yield

on_workflow

async
on_workflow(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> AsyncGenerator[
    Union[ActionCall, HumanCall, EnterAgent, LLMCall], None
]

Workflow mode: deterministic flow as an async generator.

Override to declare a deterministic workflow. Yield ActionCall / HumanCall / LLMCall for atomic steps, EnterAgent to enter an autonomous sub-flow, RETURN(value) to terminate early. Use result = yield ActionCall(...) to receive results via asend().

async def on_workflow(self, ota_context, context=None): ... yield ActionCall("navigate_to", url="http://example.com") ... result = yield ActionCall("click_element_by_ref", ref="42") ... summary = yield LLMCall.chat("Summarize the page in one line.") ... yield EnterAgent(goal="Handle complex case")

Source code in bridgic/amphibious/_amphibious_automa.py
async def on_workflow(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Union[ActionCall, HumanCall, EnterAgent, LLMCall], None]:
    """Workflow mode: deterministic flow as an async generator.

    Override to declare a deterministic workflow. Yield ``ActionCall``
    / ``HumanCall`` / ``LLMCall`` for atomic steps, ``EnterAgent`` to
    enter an autonomous sub-flow, ``RETURN(value)`` to terminate
    early. Use ``result = yield ActionCall(...)`` to receive results
    via ``asend()``.

    >>> async def on_workflow(self, ota_context, context=None):
    ...     yield ActionCall("navigate_to", url="http://example.com")
    ...     result = yield ActionCall("click_element_by_ref", ref="42")
    ...     summary = yield LLMCall.chat("Summarize the page in one line.")
    ...     yield EnterAgent(goal="Handle complex case")
    """
    if False:  # pragma: no cover — makes this a proper async generator stub
        yield

before_action

async
before_action(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> AsyncGenerator[Any, Any]

Agent-level before_action hook, shared across all workers.

Called when a worker's before_action() returns _DELEGATE / None. Payload-free — read the pending decision from ota_context.think_result. Yield RETURN(modified_decision) to override the decision; exhausting without RETURN (or returning None from a coroutine override) is passthrough — the folded decision stands.

async def before_action(self, ota_context, context=None): ... adjusted = sanitize(ota_context.think_result) ... yield RETURN(adjusted)

Source code in bridgic/amphibious/_amphibious_automa.py
async def before_action(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
    """Agent-level before_action hook, shared across all workers.

    Called when a worker's ``before_action()`` returns ``_DELEGATE``
    / ``None``. Payload-free — read the pending decision from
    ``ota_context.think_result``. Yield ``RETURN(modified_decision)``
    to override the decision; exhausting without RETURN (or returning
    ``None`` from a coroutine override) is passthrough — the folded
    decision stands.

    >>> async def before_action(self, ota_context, context=None):
    ...     adjusted = sanitize(ota_context.think_result)
    ...     yield RETURN(adjusted)
    """
    if False:  # pragma: no cover — async generator stub
        yield

action_tool_call

async
action_tool_call(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> ActionResult

Execute the current decision's tool calls concurrently, collect results.

The calls are read off the decision on ota_context.think_result (a before_action hook may have already filtered or replaced it) and matched against ota_context.tools. Override to customize execution (sequential, rate-limited, sandboxed); both contexts are passed for parity with the other template methods.

Source code in bridgic/amphibious/_amphibious_automa.py
async def action_tool_call(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> ActionResult:
    """Execute the current decision's tool calls concurrently, collect results.

    The calls are read off the decision on ``ota_context.think_result``
    (a ``before_action`` hook may have already filtered or replaced it)
    and matched against ``ota_context.tools``. Override to customize
    execution (sequential, rate-limited, sandboxed); both contexts are
    passed for parity with the other template methods.
    """
    matched = _decision_to_matched_calls(
        ota_context.think_result, ota_context.tools
    )

    async def _run_one(tool_call: ToolCall, tool_spec: ToolSpec) -> ActionStepResult:
        tool_worker = tool_spec.create_worker()
        sandbox = ConcurrentAutoma()
        worker_key = f"tool_{tool_call.name}_{tool_call.id}"
        sandbox.add_worker(
            key=worker_key,
            worker=tool_worker,
            args_mapping_rule=ArgsMappingRule.UNPACK,
        )
        try:
            results = await sandbox.arun(InOrder([tool_call.arguments]))
            result = results[0] if results else None
            return ActionStepResult(
                tool_id=tool_call.id,
                tool_name=tool_call.name,
                tool_arguments=tool_call.arguments,
                tool_result=result,
                success=True,
            )
        except Exception as e:
            return ActionStepResult(
                tool_id=tool_call.id,
                tool_name=tool_call.name,
                tool_arguments=tool_call.arguments,
                tool_result=None,
                success=False,
                error=str(e),
            )

    step_results = await asyncio.gather(
        *(_run_one(tc, ts) for tc, ts in matched)
    )
    return ActionResult(results=list(step_results))

after_action

async
after_action(
    ota_context: OTAContextT,
    context: Optional[ContextT] = None,
) -> AsyncGenerator[Any, Any]

Agent-level after_action hook.

Called after action execution. Payload-free — read the action result from ota_context.action_result. Override to update custom context fields or trigger follow-up primitives based on it. RETURN is unused here — the hook's return value is ignored.

async def after_action(self, ota_context, context=None): ... summary = yield LLMCall.chat(f"Summarize: {ota_context.action_result}") ... ota_context.action_result # action payload on the current round

Source code in bridgic/amphibious/_amphibious_automa.py
async def after_action(self, ota_context: OTAContextT, context: Optional[ContextT] = None) -> AsyncGenerator[Any, Any]:
    """Agent-level after_action hook.

    Called after action execution. Payload-free — read the action
    result from ``ota_context.action_result``. Override to update
    custom context fields or trigger follow-up primitives based on
    it. ``RETURN`` is unused here — the hook's return value is
    ignored.

    >>> async def after_action(self, ota_context, context=None):
    ...     summary = yield LLMCall.chat(f"Summarize: {ota_context.action_result}")
    ...     ota_context.action_result  # action payload on the current round
    """
    if False:  # pragma: no cover — async generator stub
        yield

router

async
router(
    mode: RunMode, max_consecutive_fallbacks: int
) -> str

Router worker: dispatches to the correct execution mode.

RunMode.AUTO is resolved upstream in arun(), so this worker always receives a concrete mode.

Source code in bridgic/amphibious/_amphibious_automa.py
@worker(is_start=True)
async def router(self, mode: RunMode, max_consecutive_fallbacks: int) -> str:
    """
    Router worker: dispatches to the correct execution mode.

    ``RunMode.AUTO`` is resolved upstream in ``arun()``, so this worker
    always receives a concrete mode.
    """
    if mode is RunMode.AGENT:
        self._log("Router", "Ferrying to AGENT mode")
        self.ferry_to("_agent")
    elif mode is RunMode.WORKFLOW:
        self._log("Router", "Ferrying to WORKFLOW mode")
        self.ferry_to("_workflow")
    elif mode is RunMode.AMPHIFLOW:
        self._log("Router", f"Ferrying to AMPHIFLOW mode, max_consecutive_fallbacks={max_consecutive_fallbacks}")
        self.ferry_to("_amphiflow", max_consecutive_fallbacks=max_consecutive_fallbacks)
    else:
        raise RuntimeError(f"Unsupported run mode: {mode!r}")

arun

async
arun(
    *,
    user_input: Any = "",
    llm: Optional[BaseLlm] = None,
    context: Optional[ContextT] = None,
    ota_context: Optional[OTAContextT] = None,
    mode: Optional[RunMode] = AUTO,
    max_consecutive_fallbacks: int = 1,
    trace: bool = False,
    workdir: Optional[Union[Path, str]] = None
) -> str

Run the agent. Returns a summary of the final context.

Two contexts, two loops. context= is the loop knowledge context (free-form, optional — defaults to an empty _context_class); the framework constructs a fresh small-loop OTAContext per run from _ota_context_class, seeded with user_input — unless the caller passes a pre-built ota_context=, which is then used verbatim (its own user_input stands). That lets the caller seed per-run small-loop state — e.g. inject a per-turn resource the workers/hooks read back off ota_context. Pure dispatch: the automa only schedules and no longer assembles any toolset — each OTA context declares the tools it carries on its class via OTAContext.tool (framework builtins it wants + its own), so whatever a context declared is exactly what its tools field holds.

mode=RunMode.AUTO (default) picks AMPHIFLOW / WORKFLOW / AGENT from which template methods the subclass overrides.

trace and workdir are orthogonal:

  • trace=True activates an in-memory AgentTrace (survives on self._agent_trace after the run for inspection).
  • workdir=path materialises <workdir>/runs/<run_id>/ — the run directory — independent of whether the trace is active.
  • Both set ⇒ AgentTrace incrementally persists the single <run>/trace.json (goal + metadata + history) — the run directory's only artifact.
  • trace=False, workdir=path ⇒ the run dir is created but empty (nothing writes trace.json).

max_consecutive_fallbacks (AMPHIFLOW only) is the workflow step-failure threshold before switching to full agent mode.

Source code in bridgic/amphibious/_amphibious_automa.py
async def arun(
    self,
    *,
    user_input: Any = "",
    llm: Optional[BaseLlm] = None,
    context: Optional[ContextT] = None,
    ota_context: Optional[OTAContextT] = None,
    mode: Optional[RunMode] = RunMode.AUTO,
    max_consecutive_fallbacks: int = 1,
    trace: bool = False,
    workdir: Optional[Union[Path, str]] = None,
) -> str:
    """Run the agent. Returns a summary of the final context.

    Two contexts, two loops. ``context=`` is the **loop** knowledge
    context (free-form, optional — defaults to an empty ``_context_class``);
    the framework constructs a fresh **small-loop** ``OTAContext`` per run
    from ``_ota_context_class``, seeded with ``user_input`` — unless the
    caller passes a pre-built ``ota_context=``, which is then used verbatim
    (its own ``user_input`` stands). That lets the caller seed per-run
    small-loop state — e.g. inject a per-turn resource the workers/hooks
    read back off ``ota_context``. Pure dispatch:
    the automa only schedules and no longer assembles any toolset — each
    OTA context declares the tools it carries on its class via
    ``OTAContext.tool`` (framework builtins it wants + its own), so whatever
    a context declared is exactly what its ``tools`` field holds.

    ``mode=RunMode.AUTO`` (default) picks AMPHIFLOW / WORKFLOW / AGENT
    from which template methods the subclass overrides.

    ``trace`` and ``workdir`` are orthogonal:

    * ``trace=True`` activates an in-memory ``AgentTrace`` (survives
      on ``self._agent_trace`` after the run for inspection).
    * ``workdir=path`` materialises ``<workdir>/runs/<run_id>/`` —
      the run directory — independent of whether the trace is active.
    * Both set ⇒ ``AgentTrace`` incrementally persists the single
      ``<run>/trace.json`` (goal + metadata + history) — the run
      directory's only artifact.
    * ``trace=False, workdir=path`` ⇒ the run dir is created but
      empty (nothing writes ``trace.json``).

    ``max_consecutive_fallbacks`` (AMPHIFLOW only) is the workflow
    step-failure threshold before switching to full agent mode.
    """
    async def _run_and_report(context: ContextT) -> str:
        """Run the agent, measure time, and log summary."""
        start_time = time.time()
        result = await GraphAutoma.arun(
            self, self._run_mode,
            max_consecutive_fallbacks=max_consecutive_fallbacks,
        )
        self.spent_time = time.time() - start_time

        if self._verbose:
            agent_name = self.name or self.__class__.__name__
            separator = "=" * 50
            printer.print(separator, color="cyan")
            printer.print(
                f"  {agent_name} | Completed\n"
                f"Tokens: {self.spent_tokens} | "
                f"Time: {self.spent_time:.2f}s",
                color="cyan"
            )
            printer.print(separator, color="cyan")

        return result

    ########################
    # Pre-initialize status
    ########################
    # Config
    self._llm = llm
    self._run_mode = self._resolve_mode(mode if mode is not None else RunMode.AUTO)

    # Trace
    self._read_tracker = {}
    self._current_run_dir = None
    self._agent_trace = None

    # State
    self._final_answer = None
    self.spent_tokens = 0
    self.spent_time = 0.0
    self._log_depth = 0
    self._log_hook_name = None

    ########################
    # Run-dir + trace activation — orthogonal axes.
    #   trace=True  → AgentTrace is created (in-memory recorder).
    #   workdir set → <workdir>/runs/<run_id>/ is materialised.
    #   Both set    → AgentTrace also persists trace.json there.
    ########################
    run_id: Optional[str] = None
    if workdir is not None:
        run_id = make_run_id()
        self._current_run_dir = ensure_run_dir(Path(workdir).expanduser().resolve(), run_id)

    if trace:
        self._agent_trace = AgentTrace(workdir=self._current_run_dir)

    ########################
    # Initialize the two contexts (pure dispatch — no toolset assembly).
    #   * Loop — caller-supplied free-form knowledge context, or a fresh
    #            default ``_context_class`` when none was passed.
    #   * OTA  — a caller-supplied pre-built small-loop context, or a fresh
    #            one constructed per run seeded with ``user_input``.
    # Each context already carries its own declared ``tools`` (populated
    # from its class's ``OTAContext.tool`` registrations); the framework
    # does not inject or merge any tools here.
    ########################
    if context is not None and not isinstance(context, self._context_class):
        raise ValueError(
            f"context= must be an instance of {self._context_class.__name__} "
            f"(the loop context), got {type(context).__name__}."
        )
    if ota_context is not None and not isinstance(ota_context, self._ota_context_class):
        raise ValueError(
            f"ota_context= must be an instance of {self._ota_context_class.__name__} "
            f"(the small-loop context), got {type(ota_context).__name__}."
        )

    loop_ctx = context if context is not None else self._context_class()
    ota_ctx = ota_context if ota_context is not None else self._ota_context_class(user_input=user_input)
    self._current_ota_context = ota_ctx
    self._current_context = loop_ctx

    ########################
    # Run the amphibious automa
    ########################
    token = current_agent.set(self)
    try:
        # Trace lifecycle — begin.
        if self._agent_trace is not None:
            self._agent_trace.begin_run(
                goal=str(ota_ctx.user_input or ""),
                agent_class=f"{type(self).__module__}.{type(self).__qualname__}",
                agent_name=self.name,
                context_class=(
                    f"{self._context_class.__module__}.{self._context_class.__qualname__}"
                    if self._context_class else None
                ),
                mode=self._run_mode.value,
                run_id=run_id,
                max_consecutive_fallbacks=max_consecutive_fallbacks,
                start_time=time.time(),
            )
        return await _run_and_report(context=loop_ctx)
    finally:
        # Trace lifecycle — end.
        if self._agent_trace is not None:
            try:
                self._agent_trace.end_run(
                    end_time=time.time(),
                    spent_tokens=self.spent_tokens,
                    spent_time=self.spent_time,
                )
            except Exception:
                pass
        self._current_run_dir = None
        self._run_mode = None
        self._llm = None
        current_agent.reset(token)

AgentTrace

Unified trace recorder for one arun invocation.

Owns ALL workdir persistence: when constructed with a non-None workdir, every lifecycle event and step record triggers an incremental write of <workdir>/trace.json. That one file is the single artifact for a run — it replaced an earlier multi-file layout (separate meta.json + ctx_initial.json + ctx_final.json + a steps file).

Trace data layout (build() and the on-disk JSON share it)::

1
2
3
4
5
6
7
{
    "goal":     "<the original arun goal>",
    "metadata": {agent_class, agent_name, context_class, mode,
                 run_id, start_time, end_time, spent_tokens,
                 spent_time, cost_time, ...},
    "history":  [TraceStep, ...],  # one entry per yield primitive
}

Semantic split from OTAContext.ota_record: the small-loop round trace is summarised for the agent's own consumption (prompts), while this trace history is the detailed audit log of every step's outcome.

Source code in bridgic/amphibious/_amphibious_automa.py
class AgentTrace:
    """Unified trace recorder for one ``arun`` invocation.

    Owns ALL workdir persistence: when constructed with a non-``None``
    ``workdir``, every lifecycle event and step record triggers an
    incremental write of ``<workdir>/trace.json``. That one file is the
    single artifact for a run — it replaced an earlier multi-file layout
    (separate ``meta.json`` + ``ctx_initial.json`` + ``ctx_final.json``
    + a steps file).

    Trace data layout (``build()`` and the on-disk JSON share it)::

        {
            "goal":     "<the original arun goal>",
            "metadata": {agent_class, agent_name, context_class, mode,
                         run_id, start_time, end_time, spent_tokens,
                         spent_time, cost_time, ...},
            "history":  [TraceStep, ...],  # one entry per yield primitive
        }

    Semantic split from ``OTAContext.ota_record``: the small-loop round trace
    is summarised for the agent's own consumption (prompts), while this
    trace history is the detailed audit log of every step's outcome.
    """

    def __init__(self, workdir: Optional[Path] = None):
        self._workdir = workdir
        self._goal: Optional[str] = None
        self._metadata: Dict[str, Any] = {}
        self._steps: List[dict] = []

    ############################################################################
    # Lifecycle — called by ``AmphibiousAutoma.arun``
    ############################################################################

    def begin_run(
        self,
        *,
        goal: str,
        agent_class: str,
        agent_name: Optional[str],
        context_class: Optional[str],
        mode: str,
        run_id: Optional[str],
        max_consecutive_fallbacks: int,
        start_time: float,
    ) -> None:
        """Record run start; persist."""
        self._goal = goal
        self._metadata.update({
            "agent_class": agent_class,
            "agent_name": agent_name,
            "context_class": context_class,
            "mode": mode,
            "run_id": run_id,
            "max_consecutive_fallbacks": max_consecutive_fallbacks,
            "start_time": start_time,
            "start_time_iso": time.strftime(
                "%Y-%m-%dT%H:%M:%S", time.localtime(start_time)
            ),
        })
        self._persist()

    def end_run(
        self,
        *,
        end_time: float,
        spent_tokens: int,
        spent_time: float,
    ) -> None:
        """Record run end; persist."""
        self._metadata.update({
            "end_time": end_time,
            "end_time_iso": time.strftime(
                "%Y-%m-%dT%H:%M:%S", time.localtime(end_time)
            ),
            "spent_tokens": spent_tokens,
            "spent_time": spent_time,
            "cost_time": round(spent_time, 3),
        })
        self._persist()

    ############################################################################
    # Step recording — called by ``_record_*_trace`` in the dispatcher
    ############################################################################

    def record_step(self, step_data: dict) -> None:
        """Append a step record; persist incrementally."""
        self._steps.append(step_data)
        self._persist()

    ############################################################################
    # Snapshot / serialization
    ############################################################################

    def build(self) -> Dict[str, Any]:
        """Return the unified trace dict; pure (no IO)."""
        steps = [
            TraceStep(
                name=s["name"],
                step_content=s.get("step_content", ""),
                tool_calls=[
                    RecordedToolCall(**tc) for tc in s.get("tool_calls", [])
                ],
                observation=s.get("observation"),
                observation_hash=s.get("observation_hash"),
                output_type=StepOutputType(s.get("output_type", StepOutputType.TOOL_CALLS)),
                structured_output=s.get("structured_output"),
                structured_output_class=s.get("structured_output_class"),
                llm_call_protocol=s.get("llm_call_protocol"),
                think_agent_name=s.get("think_agent_name"),
            )
            for s in self._steps
        ]
        return {
            "goal": self._goal,
            "metadata": dict(self._metadata),
            "history": steps,
        }

    def save(self, path: str) -> None:
        """Explicit one-shot write to ``path``.

        Equivalent to what ``_persist()`` writes to ``workdir/trace.json``,
        but writable anywhere; useful for tests and ad-hoc snapshotting.
        """
        data = self._to_serializable(self.build())
        with open(path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False, default=str)

    @staticmethod
    def load(path: str) -> Dict[str, Any]:
        """Deserialize a trace from a JSON file."""
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)

    ############################################################################
    # Internals
    ############################################################################

    def _persist(self) -> None:
        """Best-effort write to ``<workdir>/trace.json``.

        No-op when ``workdir`` is ``None`` (in-memory only). Wrapped in a
        try/except so an artifact-write failure can never mask the run's
        primary control flow.
        """
        if self._workdir is None:
            return
        try:
            data = self._to_serializable(self.build())
            (self._workdir / "trace.json").write_text(
                json.dumps(data, indent=2, ensure_ascii=False, default=str),
                encoding="utf-8",
            )
        except Exception:
            pass

    def _to_serializable(self, data: Any) -> Any:
        """Recursively convert Pydantic models and enums to plain dicts/values."""
        from enum import Enum
        if isinstance(data, BaseModel):
            return self._to_serializable(data.model_dump())
        if isinstance(data, dict):
            return {k: self._to_serializable(v) for k, v in data.items()}
        if isinstance(data, list):
            return [self._to_serializable(item) for item in data]
        if isinstance(data, Enum):
            return data.value
        return data

begin_run

begin_run(
    *,
    goal: str,
    agent_class: str,
    agent_name: Optional[str],
    context_class: Optional[str],
    mode: str,
    run_id: Optional[str],
    max_consecutive_fallbacks: int,
    start_time: float
) -> None

Record run start; persist.

Source code in bridgic/amphibious/_amphibious_automa.py
def begin_run(
    self,
    *,
    goal: str,
    agent_class: str,
    agent_name: Optional[str],
    context_class: Optional[str],
    mode: str,
    run_id: Optional[str],
    max_consecutive_fallbacks: int,
    start_time: float,
) -> None:
    """Record run start; persist."""
    self._goal = goal
    self._metadata.update({
        "agent_class": agent_class,
        "agent_name": agent_name,
        "context_class": context_class,
        "mode": mode,
        "run_id": run_id,
        "max_consecutive_fallbacks": max_consecutive_fallbacks,
        "start_time": start_time,
        "start_time_iso": time.strftime(
            "%Y-%m-%dT%H:%M:%S", time.localtime(start_time)
        ),
    })
    self._persist()

end_run

end_run(
    *, end_time: float, spent_tokens: int, spent_time: float
) -> None

Record run end; persist.

Source code in bridgic/amphibious/_amphibious_automa.py
def end_run(
    self,
    *,
    end_time: float,
    spent_tokens: int,
    spent_time: float,
) -> None:
    """Record run end; persist."""
    self._metadata.update({
        "end_time": end_time,
        "end_time_iso": time.strftime(
            "%Y-%m-%dT%H:%M:%S", time.localtime(end_time)
        ),
        "spent_tokens": spent_tokens,
        "spent_time": spent_time,
        "cost_time": round(spent_time, 3),
    })
    self._persist()

record_step

record_step(step_data: dict) -> None

Append a step record; persist incrementally.

Source code in bridgic/amphibious/_amphibious_automa.py
def record_step(self, step_data: dict) -> None:
    """Append a step record; persist incrementally."""
    self._steps.append(step_data)
    self._persist()

build

build() -> Dict[str, Any]

Return the unified trace dict; pure (no IO).

Source code in bridgic/amphibious/_amphibious_automa.py
def build(self) -> Dict[str, Any]:
    """Return the unified trace dict; pure (no IO)."""
    steps = [
        TraceStep(
            name=s["name"],
            step_content=s.get("step_content", ""),
            tool_calls=[
                RecordedToolCall(**tc) for tc in s.get("tool_calls", [])
            ],
            observation=s.get("observation"),
            observation_hash=s.get("observation_hash"),
            output_type=StepOutputType(s.get("output_type", StepOutputType.TOOL_CALLS)),
            structured_output=s.get("structured_output"),
            structured_output_class=s.get("structured_output_class"),
            llm_call_protocol=s.get("llm_call_protocol"),
            think_agent_name=s.get("think_agent_name"),
        )
        for s in self._steps
    ]
    return {
        "goal": self._goal,
        "metadata": dict(self._metadata),
        "history": steps,
    }

save

save(path: str) -> None

Explicit one-shot write to path.

Equivalent to what _persist() writes to workdir/trace.json, but writable anywhere; useful for tests and ad-hoc snapshotting.

Source code in bridgic/amphibious/_amphibious_automa.py
def save(self, path: str) -> None:
    """Explicit one-shot write to ``path``.

    Equivalent to what ``_persist()`` writes to ``workdir/trace.json``,
    but writable anywhere; useful for tests and ad-hoc snapshotting.
    """
    data = self._to_serializable(self.build())
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False, default=str)

load

staticmethod
load(path: str) -> Dict[str, Any]

Deserialize a trace from a JSON file.

Source code in bridgic/amphibious/_amphibious_automa.py
@staticmethod
def load(path: str) -> Dict[str, Any]:
    """Deserialize a trace from a JSON file."""
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)

ThinkUnitDescriptor

Class-level marker for a declared think_unit.

Invocation goes through yield ThinkUnit("name", ...) inside on_agent; the dispatcher resolves the name, picks up the descriptor, clones its CognitiveWorker template (state isolation), and hands the clone to AmphibiousAutoma._run_think_unit.

Mirrors ThinkAgentDescriptor in shape — the two cognitive- composition descriptors share the same dispatch contract.

Source code in bridgic/amphibious/_think_unit.py
class ThinkUnitDescriptor:
    """Class-level marker for a declared ``think_unit``.

    Invocation goes through ``yield ThinkUnit("name", ...)`` inside
    ``on_agent``; the dispatcher resolves the name, picks up the
    descriptor, clones its ``CognitiveWorker`` template (state
    isolation), and hands the clone to
    ``AmphibiousAutoma._run_think_unit``.

    Mirrors ``ThinkAgentDescriptor`` in shape — the two cognitive-
    composition descriptors share the same dispatch contract.
    """

    def __init__(
        self,
        worker: CognitiveWorker,
        *,
        until: Optional[Union[Callable[..., bool], Callable[..., Awaitable[bool]]]] = None,
        max_attempts: int = 1,
        on_error: ErrorStrategy = ErrorStrategy.RAISE,
        max_retries: int = 0,
    ) -> None:
        if not isinstance(worker, CognitiveWorker):
            raise TypeError(
                f"think_unit(worker, ...) requires a CognitiveWorker "
                f"instance; got {type(worker).__name__}. Subclass "
                "CognitiveWorker and implement thinking()."
            )
        self._worker_template: CognitiveWorker = worker
        self._until = until
        self._max_attempts = max_attempts
        self._on_error = on_error
        self._max_retries = max_retries

    def __get__(self, obj: Any, objtype: Optional[type] = None) -> "ThinkUnitDescriptor":
        # Both class- and instance-level access return the descriptor
        # itself. Invocation goes through ``yield ThinkUnit("name")``.
        return self

    @staticmethod
    def _clone_worker(template: CognitiveWorker) -> CognitiveWorker:
        """Clone a worker from its template for state isolation.

        Delegates to ``template._clone()`` — each CognitiveWorker subclass
        owns the contract of preserving its own config (since constructor
        params vary per subclass, the framework can't copy them
        generically). The default clone carries verbose and leaves the LLM
        as None — the agent sets it at runtime.

        Mirrors ``ThinkAgentDescriptor._clone_worker``.
        """
        return template._clone()

    # TODO: Refactor this case about standalone runner in future.
    async def arun(
        self,
        *,
        llm: Optional[Any] = None,
        user_input: Any = "",
        ota_context: Optional[OTAContext] = None,
        context: Optional[Context] = None,
        tools: Optional[List[ToolSpec]] = None,
        until: Optional[Union[Callable[..., bool], Callable[..., Awaitable[bool]]]] = None,
        max_attempts: Optional[int] = None,
    ) -> Any:
        """Run this think unit directly outside an ``AmphibiousAutoma``.

        This standalone runner mirrors only the ``CognitiveWorker`` OTA path:
        observe, think, worker ``before_action``, tool action, worker
        ``after_action``. It deliberately does not support framework yield
        primitive dispatch inside hooks.
        """
        run_until = until if until is not None else self._until
        run_max_attempts = (
            max_attempts if max_attempts is not None else self._max_attempts
        )

        worker = self._clone_worker(self._worker_template)
        if worker._llm is None:
            worker._llm = (
                llm if llm is not None
                else getattr(self._worker_template, "_llm", None)
            )
        if worker._llm is None:
            raise RuntimeError(
                "Standalone ThinkUnit requires an LLM. Pass llm=... to "
                "arun(), or set an LLM on the CognitiveWorker template."
            )

        ota_ctx = (
            ota_context if ota_context is not None
            else OTAContext(user_input=user_input)
        )
        if tools is not None:
            ota_ctx.tools = list(tools)
        loop_ctx = context if context is not None else Context()

        async def _invoke_worker_hook(gen_or_coro: Any) -> Any:
            if not inspect.isasyncgen(gen_or_coro):
                return await gen_or_coro

            return_value: Any = None
            try:
                while True:
                    try:
                        item = await gen_or_coro.__anext__()
                    except StopAsyncIteration:
                        break
                    if isinstance(item, RETURN):
                        return_value = item.value
                        break
                    raise RuntimeError(
                        "Standalone ThinkUnit hooks do not dispatch framework "
                        f"yield primitives ({type(item).__name__}). Return a "
                        "value, yield RETURN(value), or run inside "
                        "AmphibiousAutoma for full hook dispatch."
                    )
            finally:
                try:
                    await gen_or_coro.aclose()
                except Exception:
                    pass
            return return_value

        def _matched_tool_calls() -> List[Tuple[ToolCall, ToolSpec]]:
            calls = getattr(ota_ctx.think_result, "tool_calls", None) or []
            matched: List[Tuple[ToolCall, ToolSpec]] = []

            for call in calls:
                tool_spec = next(
                    (s for s in ota_ctx.tools if s.tool_name == call.tool),
                    None,
                )
                if tool_spec is None:
                    continue

                param_types: Dict[str, str] = {}
                param_names: List[str] = []
                if tool_spec.tool_parameters:
                    properties = tool_spec.tool_parameters.get("properties", {})
                    param_names = list(properties.keys())
                    for name, info in properties.items():
                        param_types[name] = info.get("type", "string")

                arguments: Dict[str, Any] = {}
                for arg in call.tool_arguments:
                    value: Any = arg.value
                    param_type = param_types.get(arg.name, "string")
                    if param_type == "integer":
                        try:
                            value = int(value)
                        except (TypeError, ValueError):
                            pass
                    elif param_type == "number":
                        try:
                            value = float(value)
                        except (TypeError, ValueError):
                            pass
                    elif param_type == "boolean":
                        value = str(value).lower() in ("true", "1", "yes")
                    arguments[arg.name] = value

                if arguments.get("__args__") is not None:
                    args = arguments["__args__"]
                    if isinstance(args, list):
                        arguments = dict(zip(param_names, args))
                    else:
                        arguments = {param_names[0]: args} if param_names else {}

                matched.append((
                    ToolCall(
                        id=getattr(call, "call_id", None) or generate_tool_call_id(),
                        name=call.tool,
                        arguments=arguments,
                    ),
                    tool_spec,
                ))

            return matched

        async def _action_tool_call() -> ActionResult:
            matched = _matched_tool_calls()

            async def _run_one(
                tool_call: ToolCall, tool_spec: ToolSpec,
            ) -> ActionStepResult:
                tool_worker = tool_spec.create_worker()
                sandbox = ConcurrentAutoma()
                worker_key = f"tool_{tool_call.name}_{tool_call.id}"
                sandbox.add_worker(
                    key=worker_key,
                    worker=tool_worker,
                    args_mapping_rule=ArgsMappingRule.UNPACK,
                )
                try:
                    results = await sandbox.arun(InOrder([tool_call.arguments]))
                    result = results[0] if results else None
                    return ActionStepResult(
                        tool_id=tool_call.id,
                        tool_name=tool_call.name,
                        tool_arguments=tool_call.arguments,
                        tool_result=result,
                        success=True,
                    )
                except Exception as e:
                    return ActionStepResult(
                        tool_id=tool_call.id,
                        tool_name=tool_call.name,
                        tool_arguments=tool_call.arguments,
                        tool_result=None,
                        success=False,
                        error=str(e),
                    )

            step_results = await asyncio.gather(
                *(_run_one(tc, ts) for tc, ts in matched)
            )
            return ActionResult(results=list(step_results))

        async def _run_observe_think_act() -> Tuple[bool, Any]:
            ota_ctx.open_record()

            obs = await _invoke_worker_hook(worker.observation(ota_ctx, loop_ctx))
            if obs is not _DELEGATE and obs is not None:
                ota_ctx.obs_result = obs

            decision = await worker.arun(ota_context=ota_ctx, context=loop_ctx)
            ota_ctx.think_result = decision
            if decision.tool_calls == []:
                ota_ctx.action_result = None
                return True, decision.step_content

            before_ret = await _invoke_worker_hook(
                worker.before_action(ota_ctx, loop_ctx)
            )
            if before_ret is not _DELEGATE and before_ret is not None:
                ota_ctx.think_result = before_ret

            action_result = await _action_tool_call()
            ota_ctx.action_result = action_result

            await _invoke_worker_hook(worker.after_action(ota_ctx, loop_ctx))
            return False, decision.step_content

        result: Any = None
        for _cycle_idx in range(run_max_attempts):
            try:
                finished, result = await _run_observe_think_act()
            except Exception as e:
                if self._on_error == ErrorStrategy.RAISE:
                    raise RuntimeError(
                        "Standalone ThinkUnit failed during "
                        f"observe-think-act cycle: {e}"
                    ) from e
                if self._on_error == ErrorStrategy.IGNORE:
                    finished = False
                elif self._on_error == ErrorStrategy.RETRY:
                    finished = False
                    for attempt in range(self._max_retries + 1):
                        try:
                            finished, result = await _run_observe_think_act()
                            break
                        except Exception as retry_e:
                            if attempt == self._max_retries:
                                raise RuntimeError(
                                    "Standalone ThinkUnit failed after "
                                    f"{self._max_retries + 1} retries: "
                                    f"{retry_e}"
                                ) from retry_e
            else:
                if finished:
                    break
                if run_until is not None:
                    cond_result = run_until(ota_ctx)
                    if inspect.iscoroutine(cond_result):
                        cond_result = await cond_result
                    if cond_result:
                        break

        return result

arun

async
arun(
    *,
    llm: Optional[Any] = None,
    user_input: Any = "",
    ota_context: Optional[OTAContext] = None,
    context: Optional[Context] = None,
    tools: Optional[List[ToolSpec]] = None,
    until: Optional[
        Union[
            Callable[..., bool],
            Callable[..., Awaitable[bool]],
        ]
    ] = None,
    max_attempts: Optional[int] = None
) -> Any

Run this think unit directly outside an AmphibiousAutoma.

This standalone runner mirrors only the CognitiveWorker OTA path: observe, think, worker before_action, tool action, worker after_action. It deliberately does not support framework yield primitive dispatch inside hooks.

Source code in bridgic/amphibious/_think_unit.py
async def arun(
    self,
    *,
    llm: Optional[Any] = None,
    user_input: Any = "",
    ota_context: Optional[OTAContext] = None,
    context: Optional[Context] = None,
    tools: Optional[List[ToolSpec]] = None,
    until: Optional[Union[Callable[..., bool], Callable[..., Awaitable[bool]]]] = None,
    max_attempts: Optional[int] = None,
) -> Any:
    """Run this think unit directly outside an ``AmphibiousAutoma``.

    This standalone runner mirrors only the ``CognitiveWorker`` OTA path:
    observe, think, worker ``before_action``, tool action, worker
    ``after_action``. It deliberately does not support framework yield
    primitive dispatch inside hooks.
    """
    run_until = until if until is not None else self._until
    run_max_attempts = (
        max_attempts if max_attempts is not None else self._max_attempts
    )

    worker = self._clone_worker(self._worker_template)
    if worker._llm is None:
        worker._llm = (
            llm if llm is not None
            else getattr(self._worker_template, "_llm", None)
        )
    if worker._llm is None:
        raise RuntimeError(
            "Standalone ThinkUnit requires an LLM. Pass llm=... to "
            "arun(), or set an LLM on the CognitiveWorker template."
        )

    ota_ctx = (
        ota_context if ota_context is not None
        else OTAContext(user_input=user_input)
    )
    if tools is not None:
        ota_ctx.tools = list(tools)
    loop_ctx = context if context is not None else Context()

    async def _invoke_worker_hook(gen_or_coro: Any) -> Any:
        if not inspect.isasyncgen(gen_or_coro):
            return await gen_or_coro

        return_value: Any = None
        try:
            while True:
                try:
                    item = await gen_or_coro.__anext__()
                except StopAsyncIteration:
                    break
                if isinstance(item, RETURN):
                    return_value = item.value
                    break
                raise RuntimeError(
                    "Standalone ThinkUnit hooks do not dispatch framework "
                    f"yield primitives ({type(item).__name__}). Return a "
                    "value, yield RETURN(value), or run inside "
                    "AmphibiousAutoma for full hook dispatch."
                )
        finally:
            try:
                await gen_or_coro.aclose()
            except Exception:
                pass
        return return_value

    def _matched_tool_calls() -> List[Tuple[ToolCall, ToolSpec]]:
        calls = getattr(ota_ctx.think_result, "tool_calls", None) or []
        matched: List[Tuple[ToolCall, ToolSpec]] = []

        for call in calls:
            tool_spec = next(
                (s for s in ota_ctx.tools if s.tool_name == call.tool),
                None,
            )
            if tool_spec is None:
                continue

            param_types: Dict[str, str] = {}
            param_names: List[str] = []
            if tool_spec.tool_parameters:
                properties = tool_spec.tool_parameters.get("properties", {})
                param_names = list(properties.keys())
                for name, info in properties.items():
                    param_types[name] = info.get("type", "string")

            arguments: Dict[str, Any] = {}
            for arg in call.tool_arguments:
                value: Any = arg.value
                param_type = param_types.get(arg.name, "string")
                if param_type == "integer":
                    try:
                        value = int(value)
                    except (TypeError, ValueError):
                        pass
                elif param_type == "number":
                    try:
                        value = float(value)
                    except (TypeError, ValueError):
                        pass
                elif param_type == "boolean":
                    value = str(value).lower() in ("true", "1", "yes")
                arguments[arg.name] = value

            if arguments.get("__args__") is not None:
                args = arguments["__args__"]
                if isinstance(args, list):
                    arguments = dict(zip(param_names, args))
                else:
                    arguments = {param_names[0]: args} if param_names else {}

            matched.append((
                ToolCall(
                    id=getattr(call, "call_id", None) or generate_tool_call_id(),
                    name=call.tool,
                    arguments=arguments,
                ),
                tool_spec,
            ))

        return matched

    async def _action_tool_call() -> ActionResult:
        matched = _matched_tool_calls()

        async def _run_one(
            tool_call: ToolCall, tool_spec: ToolSpec,
        ) -> ActionStepResult:
            tool_worker = tool_spec.create_worker()
            sandbox = ConcurrentAutoma()
            worker_key = f"tool_{tool_call.name}_{tool_call.id}"
            sandbox.add_worker(
                key=worker_key,
                worker=tool_worker,
                args_mapping_rule=ArgsMappingRule.UNPACK,
            )
            try:
                results = await sandbox.arun(InOrder([tool_call.arguments]))
                result = results[0] if results else None
                return ActionStepResult(
                    tool_id=tool_call.id,
                    tool_name=tool_call.name,
                    tool_arguments=tool_call.arguments,
                    tool_result=result,
                    success=True,
                )
            except Exception as e:
                return ActionStepResult(
                    tool_id=tool_call.id,
                    tool_name=tool_call.name,
                    tool_arguments=tool_call.arguments,
                    tool_result=None,
                    success=False,
                    error=str(e),
                )

        step_results = await asyncio.gather(
            *(_run_one(tc, ts) for tc, ts in matched)
        )
        return ActionResult(results=list(step_results))

    async def _run_observe_think_act() -> Tuple[bool, Any]:
        ota_ctx.open_record()

        obs = await _invoke_worker_hook(worker.observation(ota_ctx, loop_ctx))
        if obs is not _DELEGATE and obs is not None:
            ota_ctx.obs_result = obs

        decision = await worker.arun(ota_context=ota_ctx, context=loop_ctx)
        ota_ctx.think_result = decision
        if decision.tool_calls == []:
            ota_ctx.action_result = None
            return True, decision.step_content

        before_ret = await _invoke_worker_hook(
            worker.before_action(ota_ctx, loop_ctx)
        )
        if before_ret is not _DELEGATE and before_ret is not None:
            ota_ctx.think_result = before_ret

        action_result = await _action_tool_call()
        ota_ctx.action_result = action_result

        await _invoke_worker_hook(worker.after_action(ota_ctx, loop_ctx))
        return False, decision.step_content

    result: Any = None
    for _cycle_idx in range(run_max_attempts):
        try:
            finished, result = await _run_observe_think_act()
        except Exception as e:
            if self._on_error == ErrorStrategy.RAISE:
                raise RuntimeError(
                    "Standalone ThinkUnit failed during "
                    f"observe-think-act cycle: {e}"
                ) from e
            if self._on_error == ErrorStrategy.IGNORE:
                finished = False
            elif self._on_error == ErrorStrategy.RETRY:
                finished = False
                for attempt in range(self._max_retries + 1):
                    try:
                        finished, result = await _run_observe_think_act()
                        break
                    except Exception as retry_e:
                        if attempt == self._max_retries:
                            raise RuntimeError(
                                "Standalone ThinkUnit failed after "
                                f"{self._max_retries + 1} retries: "
                                f"{retry_e}"
                            ) from retry_e
        else:
            if finished:
                break
            if run_until is not None:
                cond_result = run_until(ota_ctx)
                if inspect.iscoroutine(cond_result):
                    cond_result = await cond_result
                if cond_result:
                    break

    return result

ThinkAgentDescriptor

Class-level marker for a declared think_agent.

Invocation goes through yield ThinkAgent("name", ...) inside on_agent; the dispatcher resolves the name, picks up the descriptor, clones its AgentWorker template (state isolation), and hands the clone to AmphibiousAutoma._run_think_agent.

Mirrors ThinkUnitDescriptor in shape — the two cognitive- composition descriptors share the same dispatch contract.

Source code in bridgic/amphibious/_think_agent.py
class ThinkAgentDescriptor:
    """Class-level marker for a declared ``think_agent``.

    Invocation goes through ``yield ThinkAgent("name", ...)`` inside
    ``on_agent``; the dispatcher resolves the name, picks up the
    descriptor, clones its ``AgentWorker`` template (state isolation),
    and hands the clone to ``AmphibiousAutoma._run_think_agent``.

    Mirrors ``ThinkUnitDescriptor`` in shape — the two cognitive-
    composition descriptors share the same dispatch contract.
    """

    def __init__(
        self,
        worker: AgentWorker,
        *,
        expose_tools: Optional[List[str]] = None,
    ) -> None:
        if not isinstance(worker, AgentWorker):
            raise TypeError(
                f"think_agent(worker, ...) requires an AgentWorker instance; "
                f"got {type(worker).__name__}. Use AgentWorker(ClaudeCodeAgent(...)) "
                "or subclass AgentWorker."
            )
        self._worker_template: AgentWorker = worker
        self._expose_tools: Optional[List[str]] = (
            list(expose_tools) if expose_tools is not None else None
        )

    def __get__(self, obj: Any, objtype: Optional[type] = None) -> "ThinkAgentDescriptor":
        # Both class- and instance-level access return the descriptor
        # itself. Invocation goes through ``yield ThinkAgent("name")``.
        return self

    @staticmethod
    def _clone_worker(template: AgentWorker) -> AgentWorker:
        """Clone an ``AgentWorker`` for state isolation.

        Delegates to ``template._clone()`` — each AgentWorker subclass
        owns the contract of preserving its own config (since
        constructor params vary per subclass, the framework can't
        copy them generically).

        Mirrors ``ThinkUnitDescriptor._clone_worker`` in role.
        """
        return template._clone()

Step

Bases: BaseModel

One act-phase result — the tool-execution outcome of a single observe-think-act cycle.

Carries only the result payload (an ActionResult for tool calls, or None for a content-only finish). The think text is NOT here — it lives on the round's think_result (ThinkResult.step_content).

Used by: _amphibious_automa.py (_run_action_call act-result envelope)

Source code in bridgic/amphibious/_type.py
class Step(BaseModel):
    """One act-phase result — the tool-execution outcome of a single
    observe-think-act cycle.

    Carries only the result payload (an ``ActionResult`` for tool calls, or
    ``None`` for a content-only finish). The think text is NOT here — it
    lives on the round's ``think_result`` (``ThinkResult.step_content``).

    Used by: _amphibious_automa.py (_run_action_call act-result envelope)
    """
    model_config = ConfigDict(extra="forbid")

    result: Optional[Any] = None

RunMode

Bases: str, Enum

The mode of the run.

Used by: _amphibious_automa.py (arun, router)

Source code in bridgic/amphibious/_type.py
class RunMode(str, Enum):
    """The mode of the run.

    Used by: _amphibious_automa.py (arun, router)
    """
    AGENT = "agent"
    WORKFLOW = "workflow"
    AMPHIFLOW = "amphiflow"
    AUTO = "auto"

ToolArgument

Bases: BaseModel

A single tool argument as name-value pair.

Used by: _cognitive_worker.py (StepToolCall), _amphibious_automa.py (action phase)

Source code in bridgic/amphibious/_type.py
class ToolArgument(BaseModel):
    """A single tool argument as name-value pair.

    Used by: _cognitive_worker.py (StepToolCall), _amphibious_automa.py (action phase)
    """
    model_config = ConfigDict(
        extra="forbid",
        json_schema_extra={
            "required": ["name", "value"],
            "additionalProperties": False,
        }
    )
    name: str = Field(description="Parameter name")
    value: str = Field(description="Parameter value as string")

    @field_validator('value', mode='before')
    @classmethod
    def coerce_to_str(cls, v: Any) -> str:
        return str(v) if not isinstance(v, str) else v

StepToolCall

Bases: BaseModel

A single tool call specification.

Used by: _cognitive_worker.py (ThinkModel output), _amphibious_automa.py (action phase)

Source code in bridgic/amphibious/_type.py
class StepToolCall(BaseModel):
    """A single tool call specification.

    Used by: _cognitive_worker.py (ThinkModel output), _amphibious_automa.py (action phase)
    """
    model_config = ConfigDict(
        extra="forbid",
        json_schema_extra={
            "required": ["tool", "tool_arguments"],
            "additionalProperties": False,
        }
    )
    call_id: str = Field(
        default_factory=generate_tool_call_id,
        description="Provider tool-call id, or a framework-generated local id.",
    )
    tool: str = Field(description="Name of the tool to call")
    tool_arguments: List[ToolArgument] = Field(
        description="Arguments as list of name-value pairs, e.g., [{name: 'city', value: 'Beijing'}]"
    )

    @field_validator("call_id", mode="before")
    @classmethod
    def ensure_call_id(cls, v: Any) -> str:
        return str(v) if v not in (None, "") else generate_tool_call_id()

OTARecord

Bases: BaseModel

One OTA (observe-think-act) round of the small loop.

INVARIANT: one round == one think-decision == one _execute == one ActionResult (the N tool calls of a single decision aggregate into ONE action_result).

model_config uses extra="allow" so that user hooks (e.g. before_action/after_action) can fold custom per-round fields onto the current round — for example a permission_result — without subclassing OTARecord.

Used by: _context.py (OTAContext.ota_record)

Source code in bridgic/amphibious/_type.py
class OTARecord(BaseModel):
    """One OTA (observe-think-act) round of the small loop.

    INVARIANT: one round == one think-decision == one ``_execute`` == one
    ``ActionResult`` (the N tool calls of a single decision aggregate into
    ONE ``action_result``).

    ``model_config`` uses ``extra="allow"`` so that user hooks (e.g.
    ``before_action``/``after_action``) can fold custom per-round fields
    onto the current round — for example a ``permission_result`` — without
    subclassing ``OTARecord``.

    Used by: _context.py (OTAContext.ota_record)
    """
    model_config = ConfigDict(extra="allow")

    observation_result: Optional[Any] = None
    think_result: Optional[Any] = None
    action_result: Optional[Any] = None

ActionCall dataclass

Yielded by on_workflow() / hooks for deterministic single-tool execution.

Each instance wraps exactly one tool call.

The **kwargs constructor is the ergonomic form for hand-written workflow code. The names tool_name and description are reserved by its signature and cannot also be used as tool arguments.

Used by: _amphibious_automa.py (state-machine driver)

Usage:: yield ActionCall("navigate_to", url="http://example.com") yield ActionCall("click_element_by_ref", description="Click submit", ref="e42") result = yield ActionCall("fill_field", name="user", value="john")

Source code in bridgic/amphibious/_type.py
@dataclass(init=False)
class ActionCall:
    """Yielded by on_workflow() / hooks for deterministic single-tool execution.

    Each instance wraps exactly one tool call.

    The ``**kwargs`` constructor is the ergonomic form for hand-written
    workflow code. The names ``tool_name`` and ``description`` are reserved
    by its signature and cannot also be used as tool arguments.

    Used by: _amphibious_automa.py (state-machine driver)

    Usage::
        yield ActionCall("navigate_to", url="http://example.com")
        yield ActionCall("click_element_by_ref", description="Click submit", ref="e42")
        result = yield ActionCall("fill_field", name="user", value="john")
    """
    tool_name: str
    description: str
    tool_args: Dict[str, Any]

    def __init__(self, tool_name: str, *, description: str = "", **tool_args: Any) -> None:
        self.tool_name = tool_name
        self.description = description
        self.tool_args = tool_args

HumanCall dataclass

Yielded to pause execution and request human input.

Execution is suspended until the registered @human_channel handler provides a response, which is returned to the generator via asend() as a plain string.

Channel resolution (at dispatch time):

  • channel=None → if exactly one @human_channel handler is registered, use it; if zero handlers are registered, the framework falls back to a built-in stdin handler; if 2+ handlers are registered, raises RuntimeError requiring explicit channel.
  • channel="name" → invoke the handler registered under that name.

Per-call timeouts are not exposed; if needed, the channel handler should enforce its own timeout.

Used by: _amphibious_automa.py (_dispatch_step)

Usage:: feedback = yield HumanCall(prompt="Please verify (yes/no):") feedback = yield HumanCall(channel="feishu", prompt="Confirm?")

Source code in bridgic/amphibious/_type.py
@dataclass
class HumanCall:
    """Yielded to pause execution and request human input.

    Execution is suspended until the registered ``@human_channel`` handler
    provides a response, which is returned to the generator via ``asend()``
    as a plain string.

    Channel resolution (at dispatch time):

    * ``channel=None`` → if exactly one ``@human_channel`` handler is
      registered, use it; if zero handlers are registered, the framework
      falls back to a built-in stdin handler; if 2+ handlers are
      registered, raises ``RuntimeError`` requiring explicit channel.
    * ``channel="name"`` → invoke the handler registered under that name.

    Per-call timeouts are not exposed; if needed, the channel handler
    should enforce its own timeout.

    Used by: _amphibious_automa.py (_dispatch_step)

    Usage::
        feedback = yield HumanCall(prompt="Please verify (yes/no):")
        feedback = yield HumanCall(channel="feishu", prompt="Confirm?")
    """
    prompt: str = ""
    channel: Optional[str] = None

LLMCall dataclass

Yielded by on_workflow to invoke self._llm via a bridgic-core protocol.

Result via asend() by protocol:

  • "chat"str (extracted from Response.message.content)
  • "structure_output" → value from StructuredOutput.astructured_output()
  • "tool_selector"Tuple[List[ToolCall], Optional[str]]

prompt becomes the final Role.USER message; history (if given) is prepended verbatim. Per-call temperature / kwargs are deliberately not exposed — those are baked at LLM construction time.

text = yield LLMCall.chat("What is 2+2?") parsed = yield LLMCall.structure_output("Extract...", constraint=PydanticModel(model=Schema)) calls, reply = yield LLMCall.tool_selector("...", tools=[...])

Source code in bridgic/amphibious/_type.py
@dataclass(frozen=True)
class LLMCall:
    """Yielded by ``on_workflow`` to invoke ``self._llm`` via a bridgic-core protocol.

    Result via ``asend()`` by protocol:

    * ``"chat"`` → ``str`` (extracted from ``Response.message.content``)
    * ``"structure_output"`` → value from ``StructuredOutput.astructured_output()``
    * ``"tool_selector"`` → ``Tuple[List[ToolCall], Optional[str]]``

    ``prompt`` becomes the final ``Role.USER`` message; ``history`` (if
    given) is prepended verbatim. Per-call temperature / kwargs are
    deliberately not exposed — those are baked at LLM construction time.

    >>> text = yield LLMCall.chat("What is 2+2?")
    >>> parsed = yield LLMCall.structure_output("Extract...", constraint=PydanticModel(model=Schema))
    >>> calls, reply = yield LLMCall.tool_selector("...", tools=[...])
    """
    protocol: LLMCallProtocol
    prompt: str = ""
    history: Optional[List["Message"]] = None
    constraint: Optional["Constraint"] = None     # required iff protocol == "structure_output"
    tools: Optional[List["Tool"]] = None          # required iff protocol == "tool_selector"

    def __post_init__(self) -> None:
        if self.protocol == "structure_output" and self.constraint is None:
            raise ValueError(
                "LLMCall(protocol='structure_output') requires a `constraint=` argument."
            )
        if self.protocol == "tool_selector" and not self.tools:
            raise ValueError(
                "LLMCall(protocol='tool_selector') requires a non-empty `tools=` argument."
            )
        if self.protocol == "chat" and (self.constraint is not None or self.tools is not None):
            raise ValueError(
                "LLMCall(protocol='chat') does not accept `constraint` or `tools`."
            )

    @classmethod
    def chat(
        cls,
        prompt: str,
        *,
        history: Optional[List["Message"]] = None,
    ) -> "LLMCall":
        """Construct a ``protocol='chat'`` LLMCall."""
        return cls(protocol="chat", prompt=prompt, history=history)

    @classmethod
    def structure_output(
        cls,
        prompt: str,
        *,
        constraint: "Constraint",
        history: Optional[List["Message"]] = None,
    ) -> "LLMCall":
        """Construct a ``protocol='structure_output'`` LLMCall."""
        return cls(
            protocol="structure_output",
            prompt=prompt,
            history=history,
            constraint=constraint,
        )

    @classmethod
    def tool_selector(
        cls,
        prompt: str,
        *,
        tools: List["Tool"],
        history: Optional[List["Message"]] = None,
    ) -> "LLMCall":
        """Construct a ``protocol='tool_selector'`` LLMCall."""
        return cls(
            protocol="tool_selector",
            prompt=prompt,
            history=history,
            tools=tools,
        )

chat

classmethod
chat(
    prompt: str,
    *,
    history: Optional[List["Message"]] = None
) -> "LLMCall"

Construct a protocol='chat' LLMCall.

Source code in bridgic/amphibious/_type.py
@classmethod
def chat(
    cls,
    prompt: str,
    *,
    history: Optional[List["Message"]] = None,
) -> "LLMCall":
    """Construct a ``protocol='chat'`` LLMCall."""
    return cls(protocol="chat", prompt=prompt, history=history)

structure_output

classmethod
structure_output(
    prompt: str,
    *,
    constraint: "Constraint",
    history: Optional[List["Message"]] = None
) -> "LLMCall"

Construct a protocol='structure_output' LLMCall.

Source code in bridgic/amphibious/_type.py
@classmethod
def structure_output(
    cls,
    prompt: str,
    *,
    constraint: "Constraint",
    history: Optional[List["Message"]] = None,
) -> "LLMCall":
    """Construct a ``protocol='structure_output'`` LLMCall."""
    return cls(
        protocol="structure_output",
        prompt=prompt,
        history=history,
        constraint=constraint,
    )

tool_selector

classmethod
tool_selector(
    prompt: str,
    *,
    tools: List["Tool"],
    history: Optional[List["Message"]] = None
) -> "LLMCall"

Construct a protocol='tool_selector' LLMCall.

Source code in bridgic/amphibious/_type.py
@classmethod
def tool_selector(
    cls,
    prompt: str,
    *,
    tools: List["Tool"],
    history: Optional[List["Message"]] = None,
) -> "LLMCall":
    """Construct a ``protocol='tool_selector'`` LLMCall."""
    return cls(
        protocol="tool_selector",
        prompt=prompt,
        history=history,
        tools=tools,
    )

EnterAgent dataclass

Yielded to suspend on_workflow and switch into on_agent.

A mode-switch signal (not a function call): the workflow generator suspends; a fresh agent generator runs until it exhausts; workflow resumes at the next instruction after this yield. No stack, no recursion — each EnterAgent creates a fresh agent generator.

Delegation is fresh-instance (isolation by construction): a new small-loop OTAContext is built for the sub-flow with goal as its user_input, carrying the OTA context class's declared tools (OTAContext.tool). The sub-run owns its rounds; the parent OTA context is restored (never mutated) when the agent exhausts. The big-loop knowledge context is shared (read-only) across parent and sub-run.

EnterAgent hands the agent a sub-task (goal); it does not control how it thinks. For a single named cognitive step, use ThinkUnit from inside on_agent. Requires the class to override on_agent.

yield EnterAgent(goal="Handle the login popup")

Source code in bridgic/amphibious/_type.py
@dataclass
class EnterAgent:
    """Yielded to suspend ``on_workflow`` and switch into ``on_agent``.

    A **mode-switch** signal (not a function call): the workflow
    generator suspends; a fresh agent generator runs until it exhausts;
    workflow resumes at the next instruction after this yield. No stack,
    no recursion — each EnterAgent creates a fresh agent generator.

    Delegation is **fresh-instance** (isolation by construction): a new
    small-loop ``OTAContext`` is built for the sub-flow with ``goal`` as
    its ``user_input``, carrying the OTA context class's declared tools
    (``OTAContext.tool``). The sub-run owns its ``rounds``; the parent OTA
    context is restored (never mutated) when the agent exhausts. The
    big-loop knowledge context is shared (read-only) across parent and
    sub-run.

    EnterAgent hands the agent a sub-task (``goal``); it does not control
    *how it thinks*. For a single named cognitive step, use ``ThinkUnit``
    from inside ``on_agent``. Requires the class to override ``on_agent``.

    >>> yield EnterAgent(goal="Handle the login popup")
    """
    goal: str = ""

ThinkUnit dataclass

Yielded inside on_agent to invoke a class-level think_unit.

The dispatcher resolves name against the class and runs the associated ThinkUnitDescriptor through AmphibiousAutoma._run_think_unit. Fields beyond name overlay the descriptor's defaults (None = descriptor value). The asend() result is the finishing think's step_content (a str).

result = yield ThinkUnit("main_think") result = yield ThinkUnit("exec_think", until=lambda c: c.done, max_attempts=20)

Source code in bridgic/amphibious/_type.py
@dataclass(frozen=True)
class ThinkUnit:
    """Yielded inside ``on_agent`` to invoke a class-level ``think_unit``.

    The dispatcher resolves ``name`` against the class and runs the
    associated ``ThinkUnitDescriptor`` through
    ``AmphibiousAutoma._run_think_unit``. Fields beyond ``name`` overlay
    the descriptor's defaults (``None`` = descriptor value). The
    ``asend()`` result is the finishing think's ``step_content`` (a
    ``str``).

    >>> result = yield ThinkUnit("main_think")
    >>> result = yield ThinkUnit("exec_think", until=lambda c: c.done, max_attempts=20)
    """
    name: str
    until: Optional[Callable[..., Union[bool, Awaitable[bool]]]] = None
    max_attempts: Optional[int] = None

ThinkAgent dataclass

Yielded to invoke a class-level think_agent declaration by name.

Unlike ThinkUnit (one in-process OTC cycle driven by a CognitiveWorker), ThinkAgent drives an AgentWorker that hands the sub-goal off to an external agent (today: claude code; add others by subclassing BaseAgent). The external agent is bound to the parent's task tools via an in-process MCP server, so every tool call it makes is surfaced back as a decision and executed by _run_action_call — the parent's hooks fire normally.

Fields beyond name overlay the descriptor's defaults (None = descriptor value). CLI-level knobs (allowed_builtin_tools / permission_mode / completion_timeout / …) live on the BaseAgent the AgentWorker wraps — analogous to how LLM / cognitive-policy knobs live on CognitiveWorker, not on ThinkUnit.

The asend() result is the string the external agent passed to agent_done(result=...), or None if the agent exited without signalling.

class MyAutoma(AmphibiousAutoma[OTAContext, Context]): ... write_article = think_agent( ... AgentWorker(ClaudeCodeAgent(allowed_builtin_tools=["Write"])), ... ) ... async def on_agent(self, ota_ctx): ... result = yield ThinkAgent("write_article", goal="Write the article.") ... yield RETURN(result)

Source code in bridgic/amphibious/_type.py
@dataclass(frozen=True)
class ThinkAgent:
    """Yielded to invoke a class-level ``think_agent`` declaration by name.

    Unlike ``ThinkUnit`` (one in-process OTC cycle driven by a
    ``CognitiveWorker``), ``ThinkAgent`` drives an ``AgentWorker`` that
    hands the sub-goal off to an **external** agent (today: ``claude
    code``; add others by subclassing ``BaseAgent``). The external
    agent is bound to the parent's task tools via an in-process MCP
    server, so every tool call it makes is surfaced back as a decision
    and executed by ``_run_action_call`` — the parent's hooks fire
    normally.

    Fields beyond ``name`` overlay the descriptor's defaults (``None`` =
    descriptor value). CLI-level knobs (``allowed_builtin_tools`` /
    ``permission_mode`` / ``completion_timeout`` / …) live on the
    ``BaseAgent`` the ``AgentWorker`` wraps — analogous to how LLM /
    cognitive-policy knobs live on ``CognitiveWorker``, not on
    ``ThinkUnit``.

    The ``asend()`` result is the string the external agent passed to
    ``agent_done(result=...)``, or ``None`` if the agent exited
    without signalling.

    >>> class MyAutoma(AmphibiousAutoma[OTAContext, Context]):
    ...     write_article = think_agent(
    ...         AgentWorker(ClaudeCodeAgent(allowed_builtin_tools=["Write"])),
    ...     )
    ...     async def on_agent(self, ota_ctx):
    ...         result = yield ThinkAgent("write_article", goal="Write the article.")
    ...         yield RETURN(result)
    """
    name: str
    goal: Optional[str] = None
    expose_tools: Optional[List[str]] = None

RETURN dataclass

Yielded to communicate a return value out of an async generator.

PEP 525 forbids return value inside async generators (only bare return is allowed). RETURN(value) is the framework-level workaround: when the dispatcher receives it, it captures RETURN.value, immediately closes the generator, and returns the value to its caller. Anything yielded after a RETURN is unreachable.

For top-level template-method generators (on_agent / on_workflow), the captured value is written to self._final_answer (overriding the auto-capture from history).

Used by: _amphibious_automa.py (_dispatch_step)

Usage:: async def on_agent(self, ota_context, context=None): answer = yield ThinkUnit("main_think", max_attempts=20) yield RETURN(answer) # answer is the finishing think's step_content

Source code in bridgic/amphibious/_type.py
@dataclass(frozen=True)
class RETURN:
    """Yielded to communicate a return value out of an async generator.

    PEP 525 forbids ``return value`` inside async generators (only bare
    ``return`` is allowed). ``RETURN(value)`` is the framework-level
    workaround: when the dispatcher receives it, it captures
    ``RETURN.value``, immediately closes the generator, and returns the
    value to its caller. Anything yielded after a ``RETURN`` is
    unreachable.

    For top-level template-method generators (``on_agent`` /
    ``on_workflow``), the captured value is written to
    ``self._final_answer`` (overriding the auto-capture from history).

    Used by: _amphibious_automa.py (_dispatch_step)

    Usage::
        async def on_agent(self, ota_context, context=None):
            answer = yield ThinkUnit("main_think", max_attempts=20)
            yield RETURN(answer)   # ``answer`` is the finishing think's step_content
    """
    value: Any = None

ErrorStrategy

Bases: Enum

Error handling strategy for worker execution via _run().

Used by: _amphibious_automa.py (_run method), _amphibious_automa.py (ThinkUnitDescriptor)

Source code in bridgic/amphibious/_type.py
class ErrorStrategy(Enum):
    """Error handling strategy for worker execution via ``_run()``.

    Used by: _amphibious_automa.py (_run method), _amphibious_automa.py (ThinkUnitDescriptor)
    """
    RAISE = "raise"    # Re-raise exceptions (default)
    IGNORE = "ignore"  # Silently ignore exceptions
    RETRY = "retry"    # Retry up to max_retries times

ActionResult

Bases: BaseModel

Overall result of the action phase (one or more tool executions).

Used by: _amphibious_automa.py (action_tool_call, _record_trace_step)

Source code in bridgic/amphibious/_type.py
class ActionResult(BaseModel):
    """Overall result of the action phase (one or more tool executions).

    Used by: _amphibious_automa.py (action_tool_call, _record_trace_step)
    """
    model_config = ConfigDict(
        extra="forbid",
        json_schema_extra={
            "required": ["results"],
            "additionalProperties": False,
        }
    )
    results: List[ActionStepResult]

ActionStepResult

Bases: BaseModel

Result of executing one tool in the action phase.

Used by: _amphibious_automa.py (action_tool_call)

Source code in bridgic/amphibious/_type.py
class ActionStepResult(BaseModel):
    """Result of executing one tool in the action phase.

    Used by: _amphibious_automa.py (action_tool_call)
    """
    model_config = ConfigDict(
        extra="forbid",
        json_schema_extra={
            "required": ["tool_id", "tool_name", "tool_arguments", "tool_result", "success"],
            "additionalProperties": False,
        }
    )
    tool_id: str
    tool_name: str
    tool_arguments: Dict[str, Any]
    tool_result: Any
    success: bool = True
    error: Optional[str] = None

ToolResult dataclass

Single tool execution result returned to workflow generator via asend().

Used by: _amphibious_automa.py (state-machine driver), on_workflow user code

Source code in bridgic/amphibious/_type.py
@dataclass
class ToolResult:
    """Single tool execution result returned to workflow generator via asend().

    Used by: _amphibious_automa.py (state-machine driver), on_workflow user code
    """
    tool_name: str
    tool_arguments: Dict[str, Any]
    result: Any
    success: bool = True
    error: Optional[str] = None

TraceStep

Bases: BaseModel

Record of one observe-think-act cycle.

Used by: _amphibious_automa.py (AgentTrace.build)

Source code in bridgic/amphibious/_type.py
class TraceStep(BaseModel):
    """Record of one observe-think-act cycle.

    Used by: _amphibious_automa.py (AgentTrace.build)
    """
    model_config = ConfigDict(extra="forbid")

    name: str
    step_content: str
    tool_calls: List[RecordedToolCall] = Field(default_factory=list)
    observation: Optional[str] = None
    observation_hash: Optional[str] = None
    output_type: StepOutputType = StepOutputType.TOOL_CALLS
    structured_output: Optional[Dict[str, Any]] = None
    structured_output_class: Optional[str] = None
    llm_call_protocol: Optional[str] = None  # set when output_type == LLM_CALL
    think_agent_name: Optional[str] = None   # set when output_type == THINK_AGENT

RecordedToolCall

Bases: BaseModel

A complete record of one tool invocation.

Used by: _amphibious_automa.py (AgentTrace.build)

Source code in bridgic/amphibious/_type.py
class RecordedToolCall(BaseModel):
    """A complete record of one tool invocation.

    Used by: _amphibious_automa.py (AgentTrace.build)
    """
    model_config = ConfigDict(extra="forbid")

    tool_id: Optional[str] = None
    tool_name: str
    tool_arguments: Dict[str, Any]
    tool_result: Any
    success: bool = True
    error: Optional[str] = None

StepOutputType

Bases: str, Enum

Discriminator for the kind of output a trace step produced.

One value per _record_<primitive> family on AmphibiousAutoma (used by: _amphibious_automa.py — AgentTrace + the _record_* methods).

Source code in bridgic/amphibious/_type.py
class StepOutputType(str, Enum):
    """Discriminator for the kind of output a trace step produced.

    One value per ``_record_<primitive>`` family on ``AmphibiousAutoma``
    (used by: _amphibious_automa.py — AgentTrace + the ``_record_*``
    methods).
    """
    TOOL_CALLS = "tool_calls"
    CONTENT_ONLY = "content_only"
    LLM_CALL = "llm_call"
    THINK_AGENT = "think_agent"
    HUMAN_CALL = "human_call"
    ENTER_AGENT = "enter_agent"

human_channel

human_channel(arg: Any = None) -> Any

Decorator that registers an async method as a human-input channel.

Two usage forms::

1
2
3
4
5
@human_channel("feishu")           # explicit channel name
async def ask_feishu(self, prompt: str) -> str: ...

@human_channel                     # bare — channel name = method name
async def terminal(self, prompt: str) -> str: ...

Channel handlers are plain async methods returning str, not generators. They are leaf I/O operations and do not dispatch inner yields.

The framework collects all decorated methods into a class-level _human_channels: Dict[str, str] registry (channel-name → method-name) inside AmphibiousAutoma.__init_subclass__. At dispatch time, HumanCall(channel=...) is routed via this registry.

Used by: AmphibiousAutoma (channel registry), HumanCall dispatch.

Source code in bridgic/amphibious/_amphibious_automa.py
def human_channel(arg: Any = None) -> Any:
    """Decorator that registers an async method as a human-input channel.

    Two usage forms::

        @human_channel("feishu")           # explicit channel name
        async def ask_feishu(self, prompt: str) -> str: ...

        @human_channel                     # bare — channel name = method name
        async def terminal(self, prompt: str) -> str: ...

    Channel handlers are *plain async methods returning ``str``*, not
    generators. They are leaf I/O operations and do not dispatch inner
    yields.

    The framework collects all decorated methods into a class-level
    ``_human_channels: Dict[str, str]`` registry (channel-name →
    method-name) inside ``AmphibiousAutoma.__init_subclass__``. At
    dispatch time, ``HumanCall(channel=...)`` is routed via this
    registry.

    Used by: AmphibiousAutoma (channel registry), HumanCall dispatch.
    """
    # Bare form: @human_channel (no parens) → arg is the method itself.
    if callable(arg) and not isinstance(arg, str):
        method = arg
        setattr(method, _HUMAN_CHANNEL_MARKER, method.__name__)
        return method

    # Parameterised form: @human_channel("name") or @human_channel()
    name: Optional[str] = arg

    def _decorator(method):
        setattr(method, _HUMAN_CHANNEL_MARKER, name or method.__name__)
        return method

    return _decorator

think_unit

think_unit(
    worker: CognitiveWorker,
    *,
    until: Optional[
        Union[
            Callable[..., bool],
            Callable[..., Awaitable[bool]],
        ]
    ] = None,
    max_attempts: int = 1,
    on_error: ErrorStrategy = RAISE,
    max_retries: int = 0
) -> ThinkUnitDescriptor

Declare a think unit, invoked via yield ThinkUnit(name).

Wraps a CognitiveWorker (cloned per invocation for state isolation). A think unit owns only the thinking-orchestration knobs — the toolset comes from the contexts the worker's thinking() assembles, not from here:

  • until — loop condition (stop early when true).
  • max_attempts — OTC cycle cap (default 1).
  • on_error — error policy (default RAISE).
  • max_retries — for the RETRY strategy.

class MyThink(CognitiveWorker): ... async def thinking(self, ota_context, context=None): ... return await self._llm.aselect_tool(messages=[...], tools=[...]) class MyAgent(AmphibiousAutoma[OTAContext, Context]): ... main_think = think_unit(MyThink(), max_attempts=80) ... async def on_agent(self, ota_ctx): ... yield ThinkUnit("main_think")

Source code in bridgic/amphibious/_think_unit.py
def think_unit(
    worker: CognitiveWorker,
    *,
    until: Optional[Union[Callable[..., bool], Callable[..., Awaitable[bool]]]] = None,
    max_attempts: int = 1,
    on_error: ErrorStrategy = ErrorStrategy.RAISE,
    max_retries: int = 0,
) -> ThinkUnitDescriptor:
    """Declare a think unit, invoked via ``yield ThinkUnit(name)``.

    Wraps a ``CognitiveWorker`` (cloned per invocation for state
    isolation). A think unit owns only the thinking-orchestration knobs —
    the toolset comes from the contexts the worker's ``thinking()``
    assembles, not from here:

    * ``until`` — loop condition (stop early when true).
    * ``max_attempts`` — OTC cycle cap (default 1).
    * ``on_error`` — error policy (default RAISE).
    * ``max_retries`` — for the RETRY strategy.

    >>> class MyThink(CognitiveWorker):
    ...     async def thinking(self, ota_context, context=None):
    ...         return await self._llm.aselect_tool(messages=[...], tools=[...])
    >>> class MyAgent(AmphibiousAutoma[OTAContext, Context]):
    ...     main_think = think_unit(MyThink(), max_attempts=80)
    ...     async def on_agent(self, ota_ctx):
    ...         yield ThinkUnit("main_think")
    """
    return ThinkUnitDescriptor(
        worker,
        until=until,
        max_attempts=max_attempts,
        on_error=on_error,
        max_retries=max_retries,
    )

think_agent

think_agent(
    worker: AgentWorker,
    *,
    expose_tools: Optional[List[str]] = None
) -> ThinkAgentDescriptor

Declare a think-agent unit, invoked via yield ThinkAgent(name, ...).

Mirrors think_unit(worker, ...) but wraps an AgentWorker instead of a CognitiveWorker. The worker carries all the delegate-level config (which CLI backend to spawn, which built-in tools to allow, permission mode, completion timeout, …); expose_tools is the descriptor-level filter selecting which project tools from ctx.tools to expose via MCP (None = expose every non-builtin tool).

class ReviewerWorker(AgentWorker): ... async def thinking(self, ota_ctx, big_ctx=None): ... return "Review the file and record findings." ... class MyAutoma(AmphibiousAutoma[OTAContext, Context]): ... reviewer = think_agent( ... ReviewerWorker(ClaudeCodeAgent(allowed_builtin_tools=["Read", "Grep"])), ... ) ... async def on_agent(self, ota_ctx): ... result = yield ThinkAgent("reviewer") ... yield RETURN(result)

Source code in bridgic/amphibious/_think_agent.py
def think_agent(
    worker: AgentWorker,
    *,
    expose_tools: Optional[List[str]] = None,
) -> ThinkAgentDescriptor:
    """Declare a think-agent unit, invoked via ``yield ThinkAgent(name, ...)``.

    Mirrors ``think_unit(worker, ...)`` but wraps an ``AgentWorker``
    instead of a ``CognitiveWorker``. The worker carries all the
    delegate-level config (which CLI backend to spawn, which built-in
    tools to allow, permission mode, completion timeout, …);
    ``expose_tools`` is the descriptor-level filter selecting which
    project tools from ``ctx.tools`` to expose via MCP (``None`` =
    expose every non-builtin tool).

    >>> class ReviewerWorker(AgentWorker):
    ...     async def thinking(self, ota_ctx, big_ctx=None):
    ...         return "Review the file and record findings."
    ...
    >>> class MyAutoma(AmphibiousAutoma[OTAContext, Context]):
    ...     reviewer = think_agent(
    ...         ReviewerWorker(ClaudeCodeAgent(allowed_builtin_tools=["Read", "Grep"])),
    ...     )
    ...     async def on_agent(self, ota_ctx):
    ...         result = yield ThinkAgent("reviewer")
    ...         yield RETURN(result)
    """
    return ThinkAgentDescriptor(worker, expose_tools=expose_tools)

create_project

create_project(
    base_dir: Optional[str] = None,
    task: Optional[str] = None,
) -> Path

Generate amphi.py in the target directory.

Parameters:

Name Type Description Default
base_dir str

Target directory for the generated file. Defaults to the current working directory.

None
task str

Task description, injected as a top-of-file # Task: ... comment. Omitted when not provided.

None

Returns:

Type Description
Path

Path to the generated amphi.py.

Raises:

Type Description
FileExistsError

If amphi.py already exists in the target directory.

Source code in bridgic/amphibious/scaffold.py
def create_project(
    base_dir: Optional[str] = None,
    task: Optional[str] = None,
) -> Path:
    """Generate ``amphi.py`` in the target directory.

    Parameters
    ----------
    base_dir : str, optional
        Target directory for the generated file. Defaults to the current
        working directory.
    task : str, optional
        Task description, injected as a top-of-file ``# Task: ...`` comment.
        Omitted when not provided.

    Returns
    -------
    Path
        Path to the generated ``amphi.py``.

    Raises
    ------
    FileExistsError
        If ``amphi.py`` already exists in the target directory.
    """
    base = Path(base_dir) if base_dir else Path.cwd()
    target = base / _AMPHI_FILENAME

    if target.exists():
        raise FileExistsError(f"File already exists: {target}")

    base.mkdir(parents=True, exist_ok=True)

    task_comment = f"# Task: {task}\n\n" if task else ""
    target.write_text(_AMPHI_PY.format(task_comment=task_comment), encoding="utf-8")

    return target