The platform for continuously improving AI agents.
import json
import os
import threading
from datetime import UTC, datetime
from pathlib import Path
from uuid import UUID
from openhands.sdk import LLM
from pydantic import SecretStr
from agent_runtime.openhands_session import deliver_context, deliver_message, open_conversation
from agent_runtime.research_disposition import TRANSPORT_UNAVAILABLE, execution_exit_code
from agent_runtime.research_events import SDKProjection
from agent_runtime.runtime_transport import RuntimeClient, RuntimeUnavailableError
def text_content(content):
return "\n".join(item.get("text", "") for item in content or [] if item.get("type") == "text")
def projection(event):
timestamp = datetime.fromisoformat(event["timestamp"])
if timestamp.tzinfo is None:
# The pinned SDK writes local wall time; executor images run with TZ=UTC.
timestamp = timestamp.replace(tzinfo=UTC)
value = {
"id": event["id"],
"parent_id": event.get("parent_id"),
"timestamp": timestamp.isoformat(),
}
kind = event["kind"]
if kind == "ActionEvent":
value |= {
"kind": "action",
"text": text_content(event.get("thought")),
"tool": event["tool_name"],
"tool_call_id": event["tool_call_id"],
"arguments": json.loads(event["tool_call"]["arguments"]),
}
elif kind == "ObservationEvent":
value |= {
"kind": "observation",
"tool": event["tool_name"],
"action_id": event["action_id"],
"observation": event["observation"],
}
elif kind == "MessageEvent":
message = event["llm_message"]
value |= {
"kind": "message",
"role": message["role"],
"text": text_content(message.get("content")),
"sender": event.get("sender"),
}
elif kind == "SystemPromptEvent":
value["kind"] = "system"
elif kind == "ConversationErrorEvent":
value["kind"] = "error"
elif kind == "AgentErrorEvent":
value |= {
"kind": "tool_error",
"tool": event["tool_name"],
"tool_call_id": event["tool_call_id"],
"text": event["error"],
"classification": event.get("classification"),
}
else:
value["kind"] = "context"
return SDKProjection.model_validate(value).model_dump(mode="json")
def run(client):
config = client.post("bootstrap")
identifier = UUID(config["conversation_id"])
persistence = Path("/state")
cursor = config["projected_sequence"]
projection_lock = threading.Lock()
stopped = threading.Event()
transport_failed = threading.Event()
heartbeat_failed = threading.Event()
stop_reason = None
def flush():
nonlocal cursor
with projection_lock:
paths = sorted((persistence / identifier.hex / "events").glob("event-*.json"))
for path in paths[cursor:]:
client.post(
"events",
{"sequence": cursor, "event": projection(json.loads(path.read_text()))},
)
cursor += 1
def dispatch(action_id, tool, arguments):
nonlocal stop_reason
flush()
result = client.post(
"tools", {"action_id": action_id, "tool": tool, "arguments": arguments}
)
if result.get("data", {}).get("reason") == "unread_user_message":
stop_reason = "amendment"
conversation.interrupt()
elif (
(
tool in {"wait", "ask_user", "request_access"}
or (tool == "eval_set" and arguments.get("operation") == "draft")
)
and result.get("accepted")
and result.get("data", {}).get("running") is not False
):
stop_reason = "wait"
conversation.pause()
return result
conversation = open_conversation(
identifier=identifier,
persistence=persistence,
workspace="/work",
resume=os.environ.get("RESEARCH_RESUME") == "1",
llm=LLM(
model=config["model"],
api_key=SecretStr(config["api_key"]),
base_url=config["base_url"],
# The platform's relay serves chat completions only; the SDK would pick the
# Responses API for some models.
api_mode="chat",
num_retries=0,
stream=True,
),
prompt=config["prompt"],
definitions=config["tools"],
dispatch=dispatch,
callbacks=[lambda event: flush()],
required_actions=config["required_actions"],
max_iterations=24,
)
flush()
deliver_context(conversation, config["context"])
for message in config["messages"]:
event_id = deliver_message(conversation, identifier=message["id"], text=message["text"])
flush()
client.post("messages", {"message_id": message["id"], "event_id": event_id})
def keep_alive():
nonlocal stop_reason
while not stopped.wait(10):
try:
status = client.post("heartbeat")
if stopped.is_set():
return
client.token = status["token"]
if status["messages"] or status["state"] != "running":
stop_reason = "amendment" if status["messages"] else "platform_stop"
conversation.interrupt()
except Exception as error:
if not stopped.is_set():
if isinstance(error, RuntimeUnavailableError):
transport_failed.set()
else:
heartbeat_failed.set()
conversation.pause()
return
heartbeat_thread = threading.Thread(target=keep_alive, daemon=True)
heartbeat_thread.start()
previous_events = {event.id for event in conversation.state.events}
try:
conversation.run()
flush()
finally:
stopped.set()
heartbeat_thread.join(timeout=190)
outcome = execution_exit_code(
"error" if heartbeat_failed.is_set() else conversation.state.execution_status.value,
errors=[
event.code
for event in conversation.state.events
if event.id not in previous_events
and type(event).__name__ == "ConversationErrorEvent"
],
stop_reason=stop_reason,
transport_failed=(
transport_failed.is_set() or client.transport_failed or heartbeat_thread.is_alive()
),
)
conversation.close()
return outcome
def main():
client = RuntimeClient(os.environ["RESEARCH_API_URL"], os.environ["RESEARCH_RUNTIME_TOKEN"])
try:
return run(client)
except Exception:
if client.transport_failed:
return TRANSPORT_UNAVAILABLE
raise
if __name__ == "__main__":
raise SystemExit(main())