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)
2123cannot read its environment, where the model's key is.
2224
2325The model's key is read from the binding's variable and passed with each request; it is in no event, and the
2931import json
3032import os
3133from pathlib import Path
34+ import signal
3235import sys
3336from typing import Any , Callable
3437import 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+
167221def _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
0 commit comments