Repository navigation
Closed
Description
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:
LocalRunLoopvsRemoteRunLoop. - 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/finishRemote (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
Toolremains 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
RunLoopprotocol: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 storedwith_params) - Drives the
Conversation.run()loop in-process.
- Calls
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,Toolwithaction_type/observation_typekinds andparams). - 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}/messagesPOST /conversations/{id}/run(optionalmax_iters)GET /conversations/{id}/events?after=nGET /conversations/{id}/statusPOST /conversations/{id}/pausePOST /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:
breakBreaking Changes (intentional; early project)
- Forbid calling
Tool.create(...)outside a RunLoop.- We keep
.create(...)but enforce it’s called only byRunLoop(local or remote server).
- We keep
- 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:
LocalRunLoopcalls.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:- Deserializes the Agent/Tool/LLM spec
- Calls
.create(**params)per tool to attach executors - Constructs
Conversationand 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 requireconversation.start(loop)soon after. Early project = we can land this as a breaking change quickly.
Five-layer sanity check (Linus-style)
- Real problem? Yes — two parallel definitions (spec vs impl) are a mess. This collapses to one spec.
- Simpler way? Yes — specs everywhere, executors only at runtime, one explicit RunLoop.
- What will it break? Direct calls to
Tool.create()by users. We’re early; acceptable. - Special cases eliminated? Local vs remote is now just two RunLoop classes. Same models.
- 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
- Add
Tool.with_params(...); forbid user.create()outside a RunLoop (raise). - Implement
RunLoopinterface; shipLocalRunLoopandRemoteRunLoop(HTTP/JSON). - Add
conversation.start(loop)and wire it through. - Update server to materialize executors on
POST /conversations. - Migrate examples; add docs and a tiny “local vs remote” diff guide.
Metadata
Metadata
Assignees
Labels
No labels
Activity
xingyaoww commentedon Sep 12, 2025
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.
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)
xingyaoww commentedon Sep 12, 2025
closed in favor of #218 -> seems cleaner to me