Skip to content

Commit 769203a

Browse files
mini-swe-agent: what the post-PR audit found
- A wrong key or model id found by the first model call (a 401, a 404, or the 400 DeepSeek answers a wrong key with) starts no session: the events are held back until the model answers, so the acting agent raises rather than score an empty answer on every task. A 400 is no longer retried by mini-swe-agent. - A `<backend>/<model>` reference takes the litellm model classes only: another class would send the binding's key and URL to its own service. - At the Base Agent's timeout the running command is killed too (it runs in a session of its own, which the process group's kill does not reach on macOS). - mini-swe-agent's own MSWEA_GLOBAL_CONFIG_DIR is its sign-in home; the login refusal names the agent; the tutorial says how far the key is kept from the commands.
1 parent b5047fc commit 769203a

6 files changed

Lines changed: 151 additions & 15 deletions

File tree

‎docs/tutorials/mini-swe-agent.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ agent:
4141
params:
4242
web_search: false # set either way for every CLI agent; mini-swe-agent has none
4343
model_class: litellm # or litellm_textbased: one ```mswea_bash_command block per response
44+
# (a <backend>/<model> reference takes these two only)
4445
config: agent/mini.yaml # optional: a mini-swe-agent config merged over Hermit's
4546
step_limit: 50 # model calls per task (the config's agent.step_limit wins)
4647
prompt: "{question}" # the task text (default: the task's prompt, question, instruction or input)
@@ -63,15 +64,18 @@ The model is a [backend reference](../guides/model-backends.md); mini-swe-agent
6364
backend's URL with its key. The key is passed with each request and written nowhere; the agent's commands see `env`
6465
and a few basic variables (`PATH`, `HOME`, `LANG`, ...) only, and on Linux mini-swe-agent's process is made
6566
non-dumpable, so a command cannot read its environment either (on macOS a command run as you can, with `ps eww`).
66-
That keeps the key out of what the agent reads; it does not confine the commands, which the run's sandbox does
67-
(`sandbox.enabled`, Linux with bubblewrap): there the agent reaches its model and nothing else.
67+
That keeps the key out of mini-swe-agent's commands and process, not out of every process that holds it: with the
68+
sandbox off, Hermit's own process (started with the key exported) runs as you too, as for every CLI agent. Only the
69+
run's sandbox confines the commands (`sandbox.enabled`, Linux with bubblewrap): there the agent reaches its model and
70+
nothing else.
6871

6972
Tokens are read from the responses and priced at the backend's `prices`; without a price the cost is unknown.
7073
mini-swe-agent's own cost tracking is off, so its `cost_limit` never stops a task: `step_limit` and `timeout_s` do
7174
(at `timeout_s` the process is stopped), and one request is bounded by 600 seconds. A failed model call (a context
7275
overflow) ends the task with no answer, its tokens still counted; a provider that could not serve (a rate limit, an
7376
outage, past mini-swe-agent's own retries) runs the task again (`retries`). A setting that would fail every task (no
74-
model, a `config` that names the model) starts no session and is reported as the agent's error, not as an answer.
77+
model, a `config` that names the model, a wrong key or model id found by the first call) starts no session and is
78+
reported as the agent's error, not as an answer. At `timeout_s` the command that is running is stopped too.
7579

7680
`config` is a mini-swe-agent config file merged over Hermit's the way `mini -c` merges files: change
7781
`agent.step_limit`, the templates, `model.model_kwargs` (temperature, `max_tokens`) or the `environment` section

‎hermit/agent/acting/workspace.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ def _check(backend: str, params: dict) -> str:
277277
if params.get("login") not in (None, "chatgpt"):
278278
raise ValueError(f"agent.params.login is chatgpt or absent, not {params['login']!r}")
279279
if params.get("login") and backend != "codex":
280-
raise ValueError("login: chatgpt is Codex's sign-in; agent claude-code takes its own")
280+
name = "claude-code" if backend == "claude" else backend
281+
raise ValueError(f"login: chatgpt is Codex's sign-in; agent {name} takes its own")
281282
if params.get("login") and (not params.get("model") or params.get("binding")):
282283
raise ValueError("with login: chatgpt, agent.params.model is a Codex model name, not empty or a "
283284
"<backend>/<model> reference")

‎hermit/agent/base/cli.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -923,7 +923,7 @@ class MiniSweAgent(CliAgent):
923923
binding the resolved `<backend>/<model>` reference (hermit.agent.model.backends): its URL, key variable,
924924
extra body and price
925925
model_class litellm (its bash tool, the default) or litellm_textbased (one ```mswea_bash_command block per
926-
response); any mini-swe-agent model class name
926+
response); without a binding, any mini-swe-agent model class name
927927
effort sent as litellm's reasoning_effort
928928
config a mini-swe-agent config file merged over Hermit's (agent.step_limit, the templates,
929929
model.model_kwargs, environment.timeout, ...); not its model name or class, nor its environment
@@ -942,14 +942,18 @@ class MiniSweAgent(CliAgent):
942942
isolations = ("none", "sandbox")
943943
home_var, user_folder = "MSWEA_GLOBAL_CONFIG_DIR", ".mini-swe-agent"
944944
home_files = (".env",) # its global config: the keys `mini-extra config` keeps
945+
binding_classes = ("litellm", "litellm_textbased") # the model classes that call a binding's endpoint (chat)
945946
turn_done = "message" # an assistant's, which `served` looks for
946947

947948
def __init__(self, settings: dict | None = None, model: Any = None):
948949
super().__init__({"stdin": True, "tools_env": "HERMIT_TOOLS_URL", **(settings or {})}, model)
949950

950951
@classmethod
951952
def user_home(cls) -> Path:
952-
"""mini-swe-agent's own global config directory (platformdirs' user config dir)."""
953+
"""mini-swe-agent's own global config directory: MSWEA_GLOBAL_CONFIG_DIR, else platformdirs' user config
954+
dir."""
955+
if os.environ.get("MSWEA_GLOBAL_CONFIG_DIR"):
956+
return Path(os.environ["MSWEA_GLOBAL_CONFIG_DIR"])
953957
try:
954958
from platformdirs import user_config_dir
955959
except ImportError: # mini-swe-agent, which brings platformdirs, is not installed
@@ -968,6 +972,11 @@ def run(self, prompt, *, workspace=None, tools: Sequence[Tool] = (), limits: Lim
968972
raise Unsupported("mini-swe-agent has no web search: set web_search false")
969973
if not (self.settings.get("binding") or self.settings.get("model")):
970974
raise ValueError("mini-swe-agent needs a model: a <backend>/<model> reference or a litellm model id")
975+
model_class = self.settings.get("model_class") or "litellm"
976+
if self.settings.get("binding") and model_class not in self.binding_classes:
977+
# another class sends what it is given to its own service: the binding's key and URL among it
978+
raise Unsupported(f"mini-swe-agent's model_class {model_class!r} calls its own service; a "
979+
f"<backend>/<model> reference takes {' or '.join(self.binding_classes)}")
971980
return super().run(prompt, workspace=workspace, tools=tools, limits=limits, session=session, roles=roles)
972981

973982
def prepare_home(self, home, roles, tools_url, tools_name):

‎hermit/agent/base/mini_swe_agent_env.py‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,20 @@
1818
import json
1919
import os
2020
import shlex
21+
import signal
22+
import subprocess
2123
from typing import Any
2224
import urllib.error
2325
import urllib.request
2426

25-
from minisweagent.environments.local import LocalEnvironment, LocalEnvironmentConfig, _run
27+
from minisweagent.environments.local import LocalEnvironment, LocalEnvironmentConfig
2628

2729
TOOL_COMMAND = "hermit-tool"
2830
TOOLS_ENV = "HERMIT_TOOLS_URL" # the tool server's JSON entrance, as the Base Agent passes it
2931
BASIC_ENV = ("PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE", "TERM", "TMPDIR",
3032
"TZ")
3133
CALL_TIMEOUT_S = 600
34+
RUNNING: set[int] = set() # the process groups of the commands running now (stop_commands)
3235

3336

3437
class HermitEnvironmentConfig(LocalEnvironmentConfig):
@@ -112,6 +115,33 @@ def _tool(self, words: list[str]) -> dict[str, Any]:
112115
return _out(f"Error: {type(exc).__name__}: {exc}", 1)
113116

114117

118+
def _run(command: str, cwd: str, env: dict[str, str], timeout: int) -> subprocess.CompletedProcess[str]:
119+
"""mini-swe-agent's own _run (a command in a process group of its own, the group killed at its timeout), with
120+
the group recorded while it runs, so that stop_commands reaches it."""
121+
process = subprocess.Popen(command, shell=True, text=True, cwd=cwd, env=env, encoding="utf-8", errors="replace",
122+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
123+
RUNNING.add(process.pid)
124+
try:
125+
stdout, _ = process.communicate(timeout=timeout)
126+
except subprocess.TimeoutExpired:
127+
os.killpg(process.pid, signal.SIGKILL)
128+
stdout, _ = process.communicate()
129+
raise subprocess.TimeoutExpired(command, timeout, output=stdout)
130+
finally:
131+
RUNNING.discard(process.pid)
132+
return subprocess.CompletedProcess(command, process.returncode, stdout=stdout)
133+
134+
135+
def stop_commands() -> None:
136+
"""Kill the commands running now: each runs in a session of its own, which a kill of this process's group does
137+
not reach (on macOS nothing else finds them: the Base Agent's stop walks /proc)."""
138+
for pid in list(RUNNING):
139+
try:
140+
os.killpg(pid, signal.SIGKILL)
141+
except (ProcessLookupError, PermissionError):
142+
pass
143+
144+
115145
def text(result: Any) -> str:
116146
"""A tool result as the text a model reads: a result's own `text` field, else its JSON (as Session.text)."""
117147
if isinstance(result, dict) and isinstance(result.get("text"), str):
@@ -135,4 +165,4 @@ def _out(text: str, returncode: int) -> dict[str, Any]:
135165
"exception_info": ""}
136166

137167

138-
__all__ = ["BASIC_ENV", "HermitEnvironment", "HermitEnvironmentConfig", "TOOL_COMMAND", "TOOLS_ENV"]
168+
__all__ = ["BASIC_ENV", "HermitEnvironment", "HermitEnvironmentConfig", "TOOL_COMMAND", "TOOLS_ENV", "stop_commands"]

‎hermit/agent/base/mini_swe_agent_run.py‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
{"type": "error", "message": "<exception>: <text>", "unavailable": true} # then the process exits 1;
1616
# `unavailable`: the provider could not serve (after mini-swe-agent's retries)
1717
18-
A setting that fails before the session (no model, a config that names the model or the environment class) is
19-
reported on stderr, with no event, and the process exits 2: the Base Agent's caller sees a session that never
20-
started, not a wrong answer. On Linux the process makes itself non-dumpable, so the commands it runs (the same user)
18+
A setting that fails before the session (a config that names the model or the environment class), or a first model
19+
call that fails for a setting (a wrong key, a model that does not exist), is reported on stderr, with no event, and
20+
the process exits 2: the Base Agent's caller sees a session that never started, not a wrong answer. Until the model
21+
has answered, the events are held back for that reason (Stream). At SIGTERM (the Base Agent's timeout) the running
22+
commands are killed too. On Linux the process makes itself non-dumpable, so the commands it runs (the same user)
2123
cannot read its environment, where the model's key is.
2224
2325
The model's key is read from the binding's variable and passed with each request; it is in no event, and the
@@ -29,6 +31,7 @@
2931
import json
3032
import os
3133
from pathlib import Path
34+
import signal
3235
import sys
3336
from typing import Any, Callable
3437
import uuid
@@ -85,7 +88,12 @@ def bound_model(model_class: type, binding: dict | None) -> type:
8588
settings["api_base"] = binding["base_url"]
8689
settings["api_key"] = os.environ.get(binding.get("api_key_env") or "", "") or PLACEHOLDER_KEY
8790

91+
import litellm
92+
8893
class Bound(model_class):
94+
# a 400 is the request's: sent again it fails again (a wrong key on DeepSeek is one), so it is not retried
95+
abort_exceptions = [*getattr(model_class, "abort_exceptions", []), litellm.exceptions.BadRequestError]
96+
8997
def _query(self, messages, **kwargs):
9098
return super()._query(messages, **{**settings, **kwargs})
9199

@@ -164,6 +172,52 @@ def reply(messages: list[dict]) -> str:
164172
return ""
165173

166174

175+
def _setup_error(exc: Exception) -> bool:
176+
"""Whether the first model call failed for a setting every task shares: the key, the model id, a parameter. The
177+
first request holds only the system message and the task, so a 400 then is the settings' (some providers answer
178+
a wrong key with one), unless it is the task's size or content."""
179+
import litellm
180+
e = litellm.exceptions
181+
if isinstance(exc, (e.ContextWindowExceededError, e.ContentPolicyViolationError)):
182+
return False
183+
return isinstance(exc, (e.AuthenticationError, e.PermissionDeniedError, e.NotFoundError, e.BadRequestError))
184+
185+
186+
class Stream:
187+
"""The events on stdout. Until the model has answered once they are held back: a call that fails then for a
188+
setting every task shares (a wrong key, a model that does not exist) is reported as a session that never started
189+
(stderr, no event), not as a task without an answer."""
190+
191+
def __init__(self, started: dict):
192+
self.started, self.held = started, []
193+
194+
@property
195+
def answered(self) -> bool:
196+
return self.held is None
197+
198+
def __call__(self, event: dict) -> None:
199+
if self.held is None:
200+
_emit(event)
201+
return
202+
self.held.append(event)
203+
message = event.get("message") or {}
204+
if message.get("role") == "assistant" or event.get("usage"): # a response, a format error's included
205+
self.flush()
206+
207+
def flush(self) -> None:
208+
if self.held is not None:
209+
for event in [self.started, *self.held]:
210+
_emit(event)
211+
self.held = None
212+
213+
214+
def _stop(signum, frame) -> None:
215+
"""The Base Agent stops this process at its timeout: the commands running in sessions of their own go too."""
216+
from hermit.agent.base.mini_swe_agent_env import stop_commands
217+
stop_commands()
218+
os._exit(128 + signum)
219+
220+
167221
def _unavailable(exc: Exception) -> bool:
168222
"""Whether the provider could not serve (a rate limit, an outage, no connection), not the request was wrong."""
169223
import litellm
@@ -189,24 +243,30 @@ def main(argv: list[str] | None = None) -> int:
189243
parser.add_argument("--stdin", action="store_true")
190244
args = parser.parse_args(argv)
191245
_not_dumpable()
246+
signal.signal(signal.SIGTERM, _stop)
192247
prompt = sys.stdin.read() if args.stdin else (args.prompt or "")
193248
settings = json.loads(args.settings.read_text())
194249
args.last.write_text("", encoding="utf-8")
250+
stream = Stream({"type": "session.started", "session": uuid.uuid4().hex,
251+
"model": (settings.get("binding") or {}).get("litellm") or settings.get("model")})
195252
try:
196-
agent, block = build(settings, args.cwd, _emit)
253+
agent, block = build(settings, args.cwd, stream)
197254
except Exception as exc: # a setting that fails every task: no session starts, nothing is an event
198255
print(f"hermit mini-swe-agent: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
199256
return 2
200-
_emit({"type": "session.started", "session": uuid.uuid4().hex,
201-
"model": (settings.get("binding") or {}).get("litellm") or settings.get("model")})
202257
try:
203258
agent.run(prompt, adapter_context=block)
204-
except Exception as exc: # the run's exit message is already in the stream (DefaultAgent adds it)
259+
except Exception as exc: # the run's exit message is in the stream (DefaultAgent adds it)
260+
if not stream.answered and _setup_error(exc):
261+
print(f"hermit mini-swe-agent: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
262+
return 2
263+
stream.flush()
205264
event = {"type": "error", "message": f"{type(exc).__name__}: {exc}"}
206265
if _unavailable(exc):
207266
event["unavailable"] = True
208267
_emit(event)
209268
return 1 # no answer: the last message of a run that broke off is none
269+
stream.flush()
210270
args.last.write_text(reply(agent.messages), encoding="utf-8")
211271
return 0
212272

‎tests/core/test_mini_swe_agent.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,33 @@ def test_a_provider_that_stops_serving_midway_is_tried_again_not_scored(tmp_path
210210
assert out.output == "ok" and out.extra["attempts"] == 2 and len(server.requests) == 4
211211

212212

213+
@pytest.mark.parametrize("status,error", [(401, "Incorrect API key provided."), (404, "The model m does not exist."),
214+
(400, "Authentication Fails, Your api key is invalid")]) # DeepSeek's
215+
def test_a_wrong_key_or_model_on_the_first_call_stops_the_agent_rather_than_score(tmp_path, monkeypatch, scripted,
216+
status, error):
217+
"""A setting every task shares, found wrong by the first model call, is no task's wrong answer: no session starts
218+
(the events are held back until the model answers) and the acting agent raises."""
219+
monkeypatch.setenv("HERMIT_TEST_KEY", KEY)
220+
server = scripted([(status, error)])
221+
with pytest.raises(RuntimeError, match="before starting a session"):
222+
load_agent("mini-swe-agent", params(server), tmp_path).run({"id": "t10", "prompt": "Go."}, None)
223+
assert len(server.requests) == 1
224+
225+
226+
def test_a_timeout_stops_the_command_that_is_running(tmp_path, monkeypatch, scripted):
227+
"""A command runs in a session of its own, which the Base Agent's kill of the process group does not reach (on
228+
macOS nothing else finds it): the process kills it when it is stopped. The delay is what the test holds."""
229+
import time
230+
monkeypatch.setenv("HERMIT_TEST_KEY", KEY)
231+
marker = tmp_path / "still-running"
232+
server = scripted([bash(f"sleep 6; touch {marker}", "c1")])
233+
started = time.time()
234+
out = load_agent("mini-swe-agent", params(server, timeout_s=5), tmp_path).run({"id": "t11", "prompt": "Go."}, None)
235+
assert out.extra["timed_out"] is True and len(server.requests) == 1
236+
time.sleep(max(0.0, started + 9 - time.time())) # past when the command would have finished
237+
assert not marker.exists()
238+
239+
213240
def test_a_module_in_the_workspace_is_not_imported_by_minis_process(tmp_path, monkeypatch, scripted):
214241
"""The process runs in the workspace; a task's file named like a module it imports (a repository with its own
215242
`yaml.py`) must not replace that module in the process that holds the model's key."""
@@ -244,6 +271,11 @@ def test_what_mini_swe_agent_cannot_do_is_refused(tmp_path, monkeypatch, scripte
244271
agent.configured(**setting).run("x", workspace=tmp_path)
245272
with pytest.raises(ValueError, match="needs a model"):
246273
make("mini-swe-agent", {"web_search": False}).run("x", workspace=tmp_path)
274+
# another model class calls its own service with what it is given: never a binding's key and URL
275+
bound = make("mini-swe-agent", {"web_search": False, "binding": {"base_url": "http://x", "model": "m"},
276+
"model_class": "openrouter"})
277+
with pytest.raises(Unsupported, match="calls its own service"):
278+
bound.run("x", workspace=tmp_path)
247279
# a config that names the model or the environment class fails every task: no session starts, and the acting
248280
# agent reports the error rather than score an empty answer
249281
server = scripted([])

0 commit comments

Comments
 (0)