-
Notifications
You must be signed in to change notification settings - Fork 313
feat(agent-server): add /goal agent-server endpoint, background loop, and stop/resume #3770
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
c32f5dc
feat: add /goal SDK core (judge-driven goal-completion loop)
VascoSch92 fb705c3
feat: add /goal agent-server endpoint, background loop, and stop/resume
VascoSch92 2e37bea
chore(sdk): tidy /goal core — temp-dir demo persistence, drop unneede…
VascoSch92 68a7ca9
Merge branch 'vasco/goal-sdk' into vasco/goal-agent-server
VascoSch92 5ee822d
Merge branch 'main' into vasco/goal-sdk
VascoSch92 e384cd5
Merge branch 'vasco/goal-sdk' into vasco/goal-agent-server
VascoSch92 c96ebb4
feat(goal): carry per-round judge verdict on goal status events
VascoSch92 610bbcd
Merge remote-tracking branch 'origin/main' into vasco/goal-agent-server
openhands-agent a7f463b
fix(agent-server): emit interrupted status when the goal loop hits an…
VascoSch92 2d4dae6
fix(agent-server): refuse /goal when a conversation run is already in…
VascoSch92 7195211
fix(agent-server): refuse /goal when a conversation run is already in…
VascoSch92 e041754
chore: Remove PR-only artifacts [automated]
0131ce8
Merge branch 'main' into vasco/goal-agent-server
simonrosenberg 2c61ff2
Merge branch 'main' into vasco/goal-agent-server
VascoSch92 dc3f8dc
Clarify goal loop naming in agent server
enyst 6e9e355
Merge branch 'main' into vasco/goal-agent-server
VascoSch92 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # `/goal` shared-history demo | ||
|
|
||
| Proves that the `/goal` loop writes into the **same** conversation history as the | ||
| main chat — it drives the `Conversation` you pass in, it does **not** fork or | ||
| create a sidecar conversation. | ||
|
|
||
| ## Run | ||
|
|
||
| ```bash | ||
| # Deterministic, no network (scripted TestLLMs) — always works: | ||
| uv run python .pr/goal_shared_history.py | ||
|
|
||
| # Real agent doing real work (creates files, runs pytest) — opt in explicitly: | ||
| GOAL_DEMO_REAL=1 LLM_API_KEY=sk-... LLM_MODEL=gpt-5.5 \ | ||
| uv run python .pr/goal_shared_history.py | ||
| ``` | ||
|
|
||
| ## What to look for | ||
|
|
||
| The script sends a normal "main conversation" message, then runs `run_goal(...)` | ||
| on the **same** `Conversation`. The `PROOF` section at the end shows: | ||
|
|
||
| ``` | ||
| same conversation id .............. True | ||
| only one Conversation object ...... True (no fork was created) | ||
| event log GREW in place ........... 3 -> 7 | ||
| main-convo events still present ... True | ||
| goal objective is in THIS log ..... True | ||
| goal outcome ...................... complete (after 2 round(s)) | ||
| ``` | ||
|
|
||
| i.e. the goal's objective, the agent's work, the judge-driven followups, and the | ||
| completion are all appended to the **one** `conversation.state.events` log under | ||
| the **one** `conversation.id` — alongside (not replacing) the main-convo events. | ||
|
|
||
| ## Seeing what the LLM is doing | ||
|
|
||
| The demo passes `visualizer=None` to keep the proof output clean. To watch the | ||
| agent's activity: | ||
|
|
||
| - **Live**: drop `visualizer=None` (the default is `DefaultConversationVisualizer`), | ||
| and every event — messages, tool calls, observations — prints as it happens. | ||
| - **After the fact**: the script ends with a `REPLAY` section that renders the | ||
| saved history through the visualizer. Because every turn is persisted in | ||
| `conversation.state.events`, you can replay it any time: | ||
|
|
||
| ```python | ||
| from openhands.sdk.conversation.visualizer import DefaultConversationVisualizer | ||
| viz = DefaultConversationVisualizer() | ||
| for event in conversation.state.events: | ||
| viz.on_event(event) | ||
| ``` | ||
|
|
||
| In the deterministic (no-key) run the agent only emits scripted text, so you see | ||
| messages. In real mode (`GOAL_DEMO_REAL=1`) you also see the actual terminal | ||
| commands, file edits, and `pytest` output the agent runs. | ||
|
|
||
| ## How this maps to the agent server | ||
|
|
||
| `run_goal` (used here) and the agent server's `EventService.start_goal` use the | ||
| same mechanism: they drive a single `Conversation`/`_conversation`, so every | ||
| event lands in that conversation's shared log and streams to subscribers. A | ||
| `POST /conversations/{id}/goal` endpoint runs the loop in the background on the | ||
| **existing** conversation — same history as the main chat. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| """Runnable proof that the ``/goal`` loop writes into the SAME conversation history. | ||
|
|
||
| What it does: | ||
| 1. Sends a normal "main conversation" message and runs the agent. | ||
| 2. Runs a ``/goal`` loop on the *same* ``Conversation`` object. | ||
| 3. Prints the single shared event log and checks that the main-conversation | ||
| events are still there, untouched, with the goal's objective / agent work / | ||
| judge-driven followups / completion appended after them. | ||
|
|
||
| The point: ``run_goal`` drives the conversation you pass in (it does not fork or | ||
| spin up a sidecar), so everything lands in one ``conversation.state.events`` log | ||
| under one ``conversation.id``. The agent-server ``EventService.start_goal`` uses | ||
| the same mechanism on its single ``_conversation``, so this proves the property | ||
| both paths rely on. | ||
|
|
||
| Run it two ways: | ||
| # Deterministic, no network (scripted TestLLMs) -- always works, quick check: | ||
| uv run python .pr/goal_shared_history.py | ||
|
|
||
| # Real agent doing real work (creates files, runs pytest) -- opt in explicitly: | ||
| GOAL_DEMO_REAL=1 LLM_API_KEY=sk-... LLM_MODEL=gpt-5.5 \ | ||
| uv run python .pr/goal_shared_history.py | ||
| """ | ||
|
|
||
| import os | ||
| import tempfile | ||
|
|
||
| from openhands.sdk import LLM, Agent, Conversation, Tool | ||
| from openhands.sdk.conversation.goal import run_goal | ||
| from openhands.sdk.conversation.visualizer import DefaultConversationVisualizer | ||
| from openhands.sdk.event import LLMConvertibleEvent | ||
| from openhands.sdk.llm import Message, TextContent, content_to_str | ||
| from openhands.sdk.testing import TestLLM | ||
| from openhands.tools.file_editor import FileEditorTool | ||
| from openhands.tools.terminal import TerminalTool | ||
|
|
||
|
|
||
| def dump_history(conversation, title: str) -> list: | ||
| """Print the conversation's full event log and return its events.""" | ||
| events = list(conversation.state.events) | ||
| print(f"\n===== {title} =====") | ||
| print(f"conversation id : {conversation.id}") | ||
| print(f"total events : {len(events)}") | ||
| for i, ev in enumerate(events): | ||
| if isinstance(ev, LLMConvertibleEvent): | ||
| text = " ".join(content_to_str(ev.to_llm_message().content)) | ||
| text = text.strip().replace("\n", " ") | ||
| print(f" [{i:>2}] {ev.to_llm_message().role:<9} {text[:96]}") | ||
| else: | ||
| print(f" [{i:>2}] {type(ev).__name__}") | ||
| return events | ||
|
|
||
|
|
||
| def _scripted(*texts: str, usage_id: str) -> TestLLM: | ||
| return TestLLM.from_messages( | ||
| [Message(role="assistant", content=[TextContent(text=t)]) for t in texts], | ||
| usage_id=usage_id, | ||
| ) | ||
|
|
||
|
|
||
| def build(real: bool): | ||
| """Return (agent, judge_llm, main_message, objective, max_iterations).""" | ||
| if real: | ||
| llm = LLM( | ||
| usage_id="agent", | ||
| model=os.getenv("LLM_MODEL", "gpt-5.5"), | ||
| api_key=os.getenv("LLM_API_KEY"), | ||
| base_url=os.getenv("LLM_BASE_URL"), | ||
| ) | ||
| agent = Agent( | ||
| llm=llm, | ||
| tools=[Tool(name=TerminalTool.name), Tool(name=FileEditorTool.name)], | ||
| ) | ||
| judge_llm = llm.model_copy(update={"usage_id": "goal-judge"}) | ||
| objective = ( | ||
| "Create mathx.py with an add(a, b) function and test_mathx.py with a " | ||
| "pytest test for it. The goal is complete only when `python -m pytest " | ||
| "-q` passes. Finish each turn with the finish tool." | ||
| ) | ||
| return ( | ||
| agent, | ||
| judge_llm, | ||
| "Say hello and tell me which directory you are in.", | ||
| objective, | ||
| 5, | ||
| ) | ||
|
|
||
| # Deterministic path: scripted agent (one content-only reply per run) + a | ||
| # judge that says "not done" once, then "done". | ||
| agent = Agent( | ||
| llm=_scripted( | ||
| "Hello! I am working in the demo workspace.", # main turn | ||
| "I drafted mathx.py and a pytest for it.", # goal round 1 | ||
| "Fixed it -- mathx.py and test_mathx.py now pass.", # goal round 2 | ||
| usage_id="agent", | ||
| ), | ||
| tools=[], | ||
| ) | ||
| judge_llm = _scripted( | ||
| '{"score": 0.3, "complete": false, "missing": "tests not passing yet"}', | ||
| '{"score": 1.0, "complete": true, "missing": ""}', | ||
| usage_id="goal-judge", | ||
| ) | ||
| return agent, judge_llm, "Say hello.", "Make `pytest` pass for mathx.py.", 5 | ||
|
|
||
|
|
||
| def main() -> None: | ||
| # Real mode is explicit opt-in so the deterministic demo always works, | ||
| # even when a (possibly stale) LLM_API_KEY is present in the environment. | ||
| real = os.getenv("GOAL_DEMO_REAL") == "1" | ||
| print(f"mode: {'REAL LLM' if real else 'DETERMINISTIC (scripted TestLLM)'}") | ||
|
|
||
| agent, judge_llm, main_message, objective, max_iters = build(real) | ||
| workspace = tempfile.mkdtemp(prefix="goal-demo-") | ||
| # visualizer=None keeps the output focused on the proof below. | ||
| conversation = Conversation( | ||
| agent=agent, workspace=workspace, visualizer=None, persistence_dir=workspace | ||
| ) | ||
| convo_id = conversation.id | ||
|
|
||
| # 1) A normal "main conversation" turn. | ||
| conversation.send_message(main_message) | ||
| conversation.run() | ||
| main_events = dump_history(conversation, "AFTER MAIN CONVERSATION TURN") | ||
| main_ids = [ev.id for ev in main_events] | ||
|
|
||
| # 2) A /goal loop on the SAME conversation object. | ||
| print(f"\n>>> running /goal: {objective}\n") | ||
| outcome = run_goal(conversation, objective, judge_llm, max_iterations=max_iters) | ||
|
|
||
| all_events = dump_history(conversation, "AFTER /goal LOOP (SAME CONVERSATION)") | ||
| all_ids = [ev.id for ev in all_events] | ||
|
|
||
| # 3) Prove it is one shared history. | ||
| objective_in_log = any( | ||
| objective[:20] in " ".join(content_to_str(ev.to_llm_message().content)) | ||
| for ev in all_events | ||
| if isinstance(ev, LLMConvertibleEvent) | ||
| ) | ||
| print("\n===== PROOF (shared history) =====") | ||
| print(f"same conversation id .............. {conversation.id == convo_id}") | ||
| print("only one Conversation object ...... True (no fork was created)") | ||
| print(f"event log GREW in place ........... {len(main_ids)} -> {len(all_ids)}") | ||
| print(f"main-convo events still present ... {all_ids[: len(main_ids)] == main_ids}") | ||
| print(f"goal objective is in THIS log ..... {objective_in_log}") | ||
| print( | ||
| f"goal outcome ...................... {outcome.status} " | ||
| f"(after {outcome.iterations} round(s))" | ||
| ) | ||
| print(f"\nworkspace: {workspace}") | ||
|
|
||
| # Visualize the whole thing AFTER the fact. Because every turn (main + goal) | ||
| # is persisted in conversation.state.events, we can replay the conversation | ||
| # through the SDK's visualizer at any time -- here, after the run finished. | ||
| # (For LIVE output instead, drop `visualizer=None` above; the default | ||
| # DefaultConversationVisualizer then prints each event as it happens.) | ||
| print("\n===== REPLAY (visualizing the saved conversation) =====") | ||
| visualizer = DefaultConversationVisualizer() | ||
| for event in conversation.state.events: | ||
| visualizer.on_event(event) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.