Skip to content

Proposal: Spec-only Tools + Explicit RunLoop (Local/Remote) with Remote Execution #213

Closed

Description

@xingyaoww

Proposal: Spec-only Tools + Explicit RunLoop (Local/Remote) with Remote Execution

Why

  • One set of Pydantic models for everything. Tools are specs; executors are runtime-only. No duplicated “local vs remote” definitions.
  • Make the execution boundary explicit and swappable: LocalRunLoop vs RemoteRunLoop.
  • Keep the user code nearly identical; “flip a switch” to run remotely.

Target UX (unchanged authoring, explicit runloop)

Local

from openhands.sdk import LLM, Agent, Conversation, Message, TextContent
from openhands.tools import execute_bash_tool, str_replace_editor_tool, task_tracker_tool
from openhands.runtime import LocalRunLoop

llm = LLM(model="...", base_url="...", api_key=...)
tools = [
    execute_bash_tool.with_params(working_dir=os.getcwd()),
    str_replace_editor_tool,                                  # no params
    task_tracker_tool.with_params(save_dir=os.getcwd()),
]
agent = Agent(llm=llm, tools=tools)

conversation = Conversation(agent=agent)

with LocalRunLoop() as loop:           # executor materialization happens here
    conversation.start(loop)           # explicit, replaces implicit .run()
    conversation.send_message(
        Message(role="user", content=[TextContent(text="Hello!")])
    )
    conversation.run()                 # drives the loop until pause/finish

Remote (same specs; only the runloop changes)

from openhands.runtime import RemoteRunLoop

with RemoteRunLoop(
    base_url="https://openhands.example.com",
    api_key="***",
) as loop:
    conversation.start(loop)           # same Conversation/Agent/Tool objects
    conversation.send_message(
        Message(role="user", content=[TextContent(text="Do the thing")])
    )
    conversation.run()

Key point: No different models for remote. We serialize the same Pydantic objects and create executors only on the remote runner.


Design

1) Tools are specs; executors are runtime-only

  • Tool remains a Pydantic model: { name, description, action_type, observation_type, annotations, meta, params }
  • New helper: Tool.with_params(**kwargs) → returns a new spec instance storing runtime parameters (e.g., working_dir="/...").
  • No .create() in user code.
    .create() is called only inside a RunLoop (local or remote). This preserves a single definition while supporting multiple runtimes.

2) Explicit RunLoop as a context manager

  • RunLoop protocol:
    class RunLoop(Protocol):
        def __enter__(self) -> "RunLoop": ...
        def __exit__(self, exc_type, exc, tb): ...
        def materialize(self, agent: Agent) -> Agent
        def step(self, conversation: Conversation) -> None
        def close(self) -> None
  • Two implementations:
    • LocalRunLoop
      • Calls .create() for each tool spec to attach a local executor (using stored with_params)
      • Drives the Conversation.run() loop in-process.
    • RemoteRunLoop
      • Serializes the same Agent/Tool/LLM specs to JSON
      • Calls server endpoints to create a remote Conversation
      • Server materializes executors by calling each tool’s .create() with params; no client executors
      • step()/run() forward to server

3) Conversation API changes

  • New: conversation.start(loop: RunLoop)
    • Registers the loop, triggers tool materialization (local or remote), and binds the conversation id (remote returns server id).
  • conversation.run()
    • Delegates stepping to the bound loop until finished / waiting for confirmation / paused.
  • conversation.pause()/close()/get_events()/get_status()
    • Delegate to loop (local in-process vs remote HTTP).

4) Remote execution details

  • Wire format: the same Pydantic models (LLM, Agent, Tool with action_type/observation_type kinds and params).
  • Server: takes the submitted specs, calls .create() per tool to attach server-side executors (e.g., BashExecutor, FileEditorExecutor), then runs the loop.
  • Endpoints (clean & minimal):
    • POST /conversations → body: {agent_spec, conversation_id?, persist?} → returns {id}
    • POST /conversations/{id}/messages
    • POST /conversations/{id}/run (optional max_iters)
    • GET /conversations/{id}/events?after=n
    • GET /conversations/{id}/status
    • POST /conversations/{id}/pause
    • POST /conversations/{id}/close
  • Security/Isolation:
    • API key auth (Bearer).
    • Tool allowlist & per-tool parameter validation on server.
    • Workspace jail (chroot/container), user mapping, resource limits.
    • Server never trusts client executors; only server executes.

Example: What actually happens

LocalRunLoop

class LocalRunLoop:
    def __enter__(self): return self
    def __exit__(self, *exc): self.close()

    def materialize(self, agent: Agent) -> Agent:
        # Convert Tool specs → Tools with executors
        realized = {}
        for t in agent.tools:
            # ONLY here are executors created
            realized[t.name] = t.create(**(t.meta or {}))  # uses stored params
        return agent.model_copy(update={"tools": list(realized.values())})

    def step(self, conversation: Conversation) -> None:
        # Advance one agent step; used by conversation.run()
        conversation._step_once_local()

    def close(self): ...

RemoteRunLoop

class RemoteRunLoop:
    def __init__(self, base_url: str, api_key: str): ...
    def __enter__(self): self._client = HttpClient(...); return self
    def __exit__(self, *exc): self.close()

    def materialize(self, agent: Agent) -> Agent:
        # Send the spec to server — no executors client-side
        self._conv_id = self._client.create_conversation(agent_spec=agent)
        return agent  # unchanged spec; remote holds executors

    def step(self, conversation: Conversation) -> None:
        self._client.run(self._conv_id, max_iters=1)

    def close(self):
        if self._conv_id:
            self._client.close(self._conv_id)

Conversation integration

class Conversation:
    def start(self, loop: RunLoop) -> None:
        self._loop = loop
        # Replace agent with materialized agent (local) or bind remote id
        self.agent = loop.materialize(self.agent)

    def run(self, max_iters: int | None = None) -> None:
        iters = 0
        while True:
            st = self.get_status()
            if st["agent_finished"] or st["agent_paused"] or st["agent_waiting_for_confirmation"]:
                break
            self._loop.step(self)
            iters += 1
            if max_iters and iters >= max_iters:
                break

Breaking Changes (intentional; early project)

  • Forbid calling Tool.create(...) outside a RunLoop.
    • We keep .create(...) but enforce it’s called only by RunLoop (local or remote server).
  • Introduce Tool.with_params(...) (stores params in the spec).
  • Add conversation.start(loop); conversation.run() now assumes a loop is bound.

Migration is trivial: replace user-side .create(...) with .with_params(...), add a one-liner with LocalRunLoop(): conversation.start(loop).


Special Cases / Extensibility

User-defined tools

  • Users define MyAction, MyObservation, MyTool(Tool[...]) — one spec.
  • They implement MyTool.create(**params) to return a Tool with the proper executor (runtime-only).
  • Local: LocalRunLoop calls .create() in-process.
    Remote: server calls .create() (user’s package must be installed server-side).

Advanced overrides

  • If users pass custom callbacks, microagents, etc., they are part of the same spec and serialize cleanly. Execution happens in the loop’s runtime (local or remote). No second copy of data structures.

Server notes

  • Use the existing FastAPI server skeleton; it already maps 1-1 to Conversation.
  • On POST /conversations, the server:
    1. Deserializes the Agent/Tool/LLM spec
    2. Calls .create(**params) per tool to attach executors
    3. Constructs Conversation and retains it in memory or persistent store
  • All later calls are by conversation id.
  • Auth: Bearer token.
  • Sandbox: per-conversation working dir, allowlist for tools, resource limits.

Backward compatibility

  • Keep the old .run() behavior working if a loop was started implicitly, but warn and require conversation.start(loop) soon after. Early project = we can land this as a breaking change quickly.

Five-layer sanity check (Linus-style)

  1. Real problem? Yes — two parallel definitions (spec vs impl) are a mess. This collapses to one spec.
  2. Simpler way? Yes — specs everywhere, executors only at runtime, one explicit RunLoop.
  3. What will it break? Direct calls to Tool.create() by users. We’re early; acceptable.
  4. Special cases eliminated? Local vs remote is now just two RunLoop classes. Same models.
  5. Practical? Yes — we already have the server routes and Pydantic. Remote is just (de)serialization + server-side .create().

Decision

✅ Worth doing — It removes duplicated abstractions and makes remote execution a flip of the runloop, without forking models.

Plan

  1. Add Tool.with_params(...); forbid user .create() outside a RunLoop (raise).
  2. Implement RunLoop interface; ship LocalRunLoop and RemoteRunLoop (HTTP/JSON).
  3. Add conversation.start(loop) and wire it through.
  4. Update server to materialize executors on POST /conversations.
  5. Migrate examples; add docs and a tiny “local vs remote” diff guide.

Activity

  1. xingyaoww commented on Sep 12, 2025

    @xingyaoww
    ContributorAuthor

    After thinking more about this remote re execution paradigm, I feel like this might just complicate things a lot, especially if we want to start two conversations (run two agents), and the have them talk to each other via but setting one conversation's send_message function as the tool executor for another one.

    from openhands.core import LLM, Agent, Tool, Conversation, ConversationStatus
    
    llm = LLM(
      model="claude-sonnet-4",
      api_key="your_api_key_here",
    )
    
    delegate_agent = Agent(llm=llm, tools=[])
    def create_conversation(msg):
    	conversation = Conversation(delegate_agent)
    	conversation.start_thread()
    	conversation.send_message("Say hello to 'world'")
    	conversation.run()
    
    tools = [
      Tool(
        name="create_conversation",
        description="Create new conversation",
        callback=create_conversation,
        inputSchema={'type': 'string', 'description': 'Create a new OpenHands conversation to do a subtask'}
      ),
    ]
    
    base_agent = Agent(llm=llm, tools=tools)
    base_conversation = Conversation(agent)
    base_conversation.send_message("Create 3 OpenHands conversations that each flips a coin and report the results")
    
    base_conversation.run()
     
    if conversation.state.status == ConversationStatus.ERROR:
      raise Exception("Error!")
    else:
      print("Agent finished")

    If you are writing it with 100% local SDK (like above), it is easy. But if you do it in a remote way, you are essentially running a program on client side that try to act as the bridge between two remote conversations (which could be inside ONE container - that's said, if we want two agents from two containers to talk to each other, this design might be helpful -- but this is unlikely to happen anytime soon)

    An extreme simple way to archive the same goal here would be: do not try to be generic, instead, we implement a "OpenHands production agent" that hard code the list of tools and only leave a few configurable like "work_dir". And then we expose a few API for this agent (eg pause, start, run, send message, similar to conversation); but it is on a higher abstraction layer than conversation --- under the hood it is totally possible for the agent to leverage multiple conversations, talk to another agent via convo callback, but it is just not exposed through API.

    I imagine OpenHands Server in OpenHands repo will likely go with the latter route (nested runtime), but it is unclear whether we want to abstract the agent out and build a mini server for it?

    And if we go with latter, I think the "concept of Agent configuration" will also gets harder to define, since the already customized production agents does not tied to the AgentBase class interface we have in SDK (eg it can be multiple agent instances under the hood with the multiple conversions running)

  2. xingyaoww commented on Sep 12, 2025

    @xingyaoww
    ContributorAuthor

    closed in favor of #218 -> seems cleaner to me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions