Commit Β·
3c91fc8
1
Parent(s): e229826
feat: kill sandbox processes and cancel HF jobs on user interrupt
Browse filesWhen the user clicks cancel, long-running sandbox commands and HF jobs
now actually stop instead of running to completion in the background.
- Sandbox server: track PIDs with Popen, add /api/kill endpoint
- Sandbox client: add kill_all() method
- HF jobs: track running job IDs in session, cancel on interrupt
- Agent loop: cleanup on cancel in both run_agent and exec_approval
- exec_approval: add cancellation support (was completely missing)
- Sandbox title: set descriptive name instead of inheriting template
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (5)
145 unmodified lines14614714814915015112 unmodified lines16416516616716816977 unmodified lines24724824925025125225325425525625725825926026126226391 unmodified lines355356357358359360361362147 unmodified lines51051151251351451577 unmodified lines593594595596597598144 unmodified lines743744745746747748749750751752753754755756757758145 unmodified linesreturn Falseasync def _compact_and_notify(session: Session) -> None:"""Run compaction and send event if context was reduced."""old_length = session.context_manager.context_length12 unmodified lines)class Handlers:"""Handler functions for each operation type"""77 unmodified linesmessages = session.context_manager.get_messages()tools = session.tool_router.get_tool_specs_for_llm()try:# ββ Stream the LLM response ββββββββββββββββββββββββββllm_params = _resolve_hf_router_params(session.config.model_name)response = await acompletion(messages=messages,tools=tools,tool_choice="auto",stream=True,stream_options={"include_usage": True},timeout=600, # 10 min β long tool-use turns can take a while**llm_params,)full_content = ""tool_calls_acc: dict[int, dict] = {}91 unmodified lines)await session.send_event(Event(event_type="error",data={"error": f"Output truncated β retrying with smaller content ({dropped_names})"},))iteration += 1147 unmodified linesawait gather_taskexcept asyncio.CancelledError:passbreakcancel_task.cancel()77 unmodified linesbreakif session.is_cancelled:await session.send_event(Event(event_type="interrupted"))elif not errored:await session.send_event(144 unmodified linesreturn (tc, tool_name, output, success, was_edited)# Execute all approved tools concurrently and wait for ALL to completeif approved_tasks:results = await asyncio.gather(*[execute_tool(tc, tool_name, tool_args, was_edited)for tc, tool_name, tool_args, was_edited in approved_tasks],return_exceptions=True,)# Process results and add to contextfor result in results:if isinstance(result, Exception):145 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117212 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521677 unmodified lines29429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933091 unmodified lines422423424425426427428429147 unmodified lines57757857958058158258377 unmodified lines661662663664665666667144 unmodified lines812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848145 unmodified linesreturn False# -- LLM retry constants --------------------------------------------------_MAX_LLM_RETRIES = 3_LLM_RETRY_DELAYS = [5, 15, 30] # seconds between retriesdef _is_transient_error(error: Exception) -> bool:"""Return True for errors that are likely transient and worth retrying."""err_str = str(error).lower()transient_patterns = ["timeout", "timed out","429", "rate limit", "rate_limit","503", "service unavailable","502", "bad gateway","500", "internal server error","overloaded", "capacity","connection reset", "connection refused", "connection error","eof", "broken pipe",]return any(pattern in err_str for pattern in transient_patterns)async def _compact_and_notify(session: Session) -> None:"""Run compaction and send event if context was reduced."""old_length = session.context_manager.context_length12 unmodified lines)async def _cleanup_on_cancel(session: Session) -> None:"""Kill sandbox processes and cancel HF jobs when the user interrupts."""# Kill active sandbox processessandbox = getattr(session, "sandbox", None)if sandbox:try:await asyncio.to_thread(sandbox.kill_all)logger.info("Killed sandbox processes on cancel")except Exception as e:logger.warning("Failed to kill sandbox processes: %s", e)# Cancel running HF jobsjob_ids = list(session._running_job_ids)if job_ids:from huggingface_hub import HfApiapi = HfApi(token=session.hf_token)for job_id in job_ids:try:await asyncio.to_thread(api.cancel_job, job_id=job_id)logger.info("Cancelled HF job %s on interrupt", job_id)except Exception as e:logger.warning("Failed to cancel HF job %s: %s", job_id, e)session._running_job_ids.clear()class Handlers:"""Handler functions for each operation type"""77 unmodified linesmessages = session.context_manager.get_messages()tools = session.tool_router.get_tool_specs_for_llm()try:# ββ Stream the LLM response (with retry for transient errors) ββllm_params = _resolve_hf_router_params(session.config.model_name)response = Nonefor _llm_attempt in range(_MAX_LLM_RETRIES):try:response = await acompletion(messages=messages,tools=tools,tool_choice="auto",stream=True,stream_options={"include_usage": True},timeout=600,**llm_params,)breakexcept ContextWindowExceededError:raiseexcept Exception as e:if _llm_attempt < _MAX_LLM_RETRIES - 1 and _is_transient_error(e):_delay = _LLM_RETRY_DELAYS[_llm_attempt]logger.warning("Transient LLM error (attempt %d/%d): %s β retrying in %ds",_llm_attempt + 1, _MAX_LLM_RETRIES, e, _delay,)await session.send_event(Event(event_type="tool_log",data={"tool": "system", "log": f"LLM connection error, retrying in {_delay}s..."},))await asyncio.sleep(_delay)continueraisefull_content = ""tool_calls_acc: dict[int, dict] = {}91 unmodified lines)await session.send_event(Event(event_type="tool_log",data={"tool": "system", "log": f"Output truncated β retrying with smaller content ({dropped_names})"},))iteration += 1147 unmodified linesawait gather_taskexcept asyncio.CancelledError:passawait _cleanup_on_cancel(session)breakcancel_task.cancel()77 unmodified linesbreakif session.is_cancelled:await _cleanup_on_cancel(session)await session.send_event(Event(event_type="interrupted"))elif not errored:await session.send_event(144 unmodified linesreturn (tc, tool_name, output, success, was_edited)# Execute all approved tools concurrently (cancellable)if approved_tasks:gather_task = asyncio.ensure_future(asyncio.gather(*[execute_tool(tc, tool_name, tool_args, was_edited)for tc, tool_name, tool_args, was_edited in approved_tasks],return_exceptions=True,))cancel_task = asyncio.ensure_future(session._cancelled.wait())done, _ = await asyncio.wait([gather_task, cancel_task],return_when=asyncio.FIRST_COMPLETED,)if cancel_task in done:gather_task.cancel()try:await gather_taskexcept asyncio.CancelledError:passawait _cleanup_on_cancel(session)await session.send_event(Event(event_type="interrupted"))session.increment_turn()await session.auto_save_if_needed()returncancel_task.cancel()results = gather_task.result()# Process results and add to contextfor result in results:if isinstance(result, Exception):
102 unmodified lines103104105106107108102 unmodified linesself._cancelled = asyncio.Event()self.pending_approval: Optional[dict[str, Any]] = Noneself.sandbox = None# Session trajectory loggingself.logged_events: list[dict] = []102 unmodified lines103104105106107108109102 unmodified linesself._cancelled = asyncio.Event()self.pending_approval: Optional[dict[str, Any]] = Noneself.sandbox = Noneself._running_job_ids: set[str] = set() # HF job IDs currently executing# Session trajectory loggingself.logged_events: list[dict] = []
530 unmodified lines53153253353453553617 unmodified lines554555556557558559530 unmodified linesnamespace=self.namespace,)# Send job URL immediately after job creation (before waiting for completion)if self.session and self.tool_call_id:await self.session.send_event(17 unmodified linesnamespace=self.namespace,)# Notify frontend of final statusif self.session and self.tool_call_id:await self.session.send_event(530 unmodified lines53153253353453553653753853954017 unmodified lines558559560561562563564565566567530 unmodified linesnamespace=self.namespace,)# Track job ID for cancellation on interruptif self.session:self.session._running_job_ids.add(job.id)# Send job URL immediately after job creation (before waiting for completion)if self.session and self.tool_call_id:await self.session.send_event(17 unmodified linesnamespace=self.namespace,)# Untrack job ID (completed or failed, no longer needs cancellation)if self.session:self.session._running_job_ids.discard(job.id)# Notify frontend of final statusif self.session and self.tool_call_id:await self.session.send_event(
96 unmodified lines9798991001011021031 unmodified line10510610710810911024 unmodified lines135136137138139140141142143144145146147148149150151152153412 unmodified lines56656756856957057196 unmodified lines_SANDBOX_SERVER = '''\"""Minimal FastAPI server for sandbox operations."""import os, subprocess, pathlibfrom fastapi import FastAPIfrom pydantic import BaseModelfrom typing import Optional1 unmodified lineapp = FastAPI()class BashReq(BaseModel):command: strwork_dir: str = "/app"24 unmodified lines@app.post("/api/bash")def bash(req: BashReq):try:r = subprocess.run(req.command, shell=True, capture_output=True, text=True,cwd=req.work_dir, timeout=req.timeout,)output = r.stdout + r.stderrif len(output) > 30000:output = output[:30000] + "\\n... (truncated)"return {"success": r.returncode == 0, "output": output, "error": "" if r.returncode == 0 else f"Exit code {r.returncode}"}except subprocess.TimeoutExpired:return {"success": False, "output": "", "error": f"Timeout after {req.timeout}s"}except Exception as e:return {"success": False, "output": "", "error": str(e)}@app.post("/api/read")def read(req: ReadReq):try:412 unmodified lines},)# ββ Tool schemas & dispatch βββββββββββββββββββββββββββββββββββTOOLS = {96 unmodified lines9798991001011021031 unmodified line10510610710810911011111211311424 unmodified lines139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187412 unmodified lines60060160260360460560660760860996 unmodified lines_SANDBOX_SERVER = '''\"""Minimal FastAPI server for sandbox operations."""import os, subprocess, pathlib, signal, threadingfrom fastapi import FastAPIfrom pydantic import BaseModelfrom typing import Optional1 unmodified lineapp = FastAPI()# Track active bash processes so they can be killed on cancel_active_procs = {} # pid -> subprocess.Popen_proc_lock = threading.Lock()class BashReq(BaseModel):command: strwork_dir: str = "/app"24 unmodified lines@app.post("/api/bash")def bash(req: BashReq):try:proc = subprocess.Popen(req.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,text=True, cwd=req.work_dir, start_new_session=True,)with _proc_lock:_active_procs[proc.pid] = proctry:stdout, stderr = proc.communicate(timeout=req.timeout)output = stdout + stderrif len(output) > 30000:output = output[:30000] + "\\n... (truncated)"return {"success": proc.returncode == 0, "output": output, "error": "" if proc.returncode == 0 else f"Exit code {proc.returncode}"}except subprocess.TimeoutExpired:try:os.killpg(os.getpgid(proc.pid), signal.SIGKILL)except OSError:proc.kill()proc.wait()return {"success": False, "output": "", "error": f"Timeout after {req.timeout}s"}finally:with _proc_lock:_active_procs.pop(proc.pid, None)except Exception as e:return {"success": False, "output": "", "error": str(e)}@app.post("/api/kill")def kill_all():"""Kill all active bash processes. Called when user cancels."""with _proc_lock:pids = list(_active_procs.keys())killed = []for pid in pids:try:os.killpg(os.getpgid(pid), signal.SIGTERM)killed.append(pid)except OSError:try:os.kill(pid, signal.SIGKILL)killed.append(pid)except OSError:passreturn {"success": True, "output": f"Killed {len(killed)} process(es): {killed}", "error": ""}@app.post("/api/read")def read(req: ReadReq):try:412 unmodified lines},)def kill_all(self) -> ToolResult:"""Kill all active bash processes on the sandbox. Used on cancellation."""return self._call("kill", {})# ββ Tool schemas & dispatch βββββββββββββββββββββββββββββββββββTOOLS = {
26 unmodified lines27282930313233343536374 unmodified lines42434445464748495051525354555641 unmodified lines989910010110210310410510610710810926 unmodified linesisinstance(script, str)and script.strip() == scriptand not any(c in script for c in "\r\n\0")and (script.startswith("/") or script.startswith("./") or script.startswith("../")))async def resolve_sandbox_script(sandbox: Any, script: str) -> tuple[str | None, str | None]:"""Read a file from the sandbox if *script* looks like a path.Returns:4 unmodified linesif not sandbox or not _looks_like_path(script):return None, Nonetry:result = await asyncio.to_thread(sandbox.bash, f"cat {shlex.quote(script)}")if result.success and result.output:return result.output, Nonereturn None, f"Failed to read {script} from sandbox: {result.error}"except Exception as e:return None, f"Failed to read {script} from sandbox: {e}"# ββ Tool name mapping (short agent names β Sandbox client names) ββββββ41 unmodified linesEvent(event_type="tool_log", data={"tool": "sandbox", "log": msg}),)kwargs = {"owner": owner, "hardware": hardware, "token": token, "log": _log, **create_kwargs}if hardware != "cpu-basic":kwargs["sleep_time"] = 2700sb = await asyncio.to_thread(Sandbox.create, **kwargs)session.sandbox = sb# Inject the OAuth token into the sandbox so Hub operations work inside itawait asyncio.to_thread(api.add_space_secret, sb.space_id, "HF_TOKEN", token)26 unmodified lines27282930313233343536373839404142434 unmodified lines484950515253545556575859606141 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113226 unmodified linesisinstance(script, str)and script.strip() == scriptand not any(c in script for c in "\r\n\0")and (script.startswith("/")or script.startswith("./")or script.startswith("../")))async def resolve_sandbox_script(sandbox: Any, script: str) -> tuple[str | None, str | None]:"""Read a file from the sandbox if *script* looks like a path.Returns:4 unmodified linesif not sandbox or not _looks_like_path(script):return None, Nonetry:result = await asyncio.to_thread(sandbox.bash, f"cat {shlex.quote(script)}")if result.success and result.output:return result.output, Nonereturn None, f"Failed to read {script} from sandbox: {result.error}"except Exception as e:return None, f"Failed to read {script} from sandbox: {e}"# ββ Tool name mapping (short agent names β Sandbox client names) ββββββ41 unmodified linesEvent(event_type="tool_log", data={"tool": "sandbox", "log": msg}),)kwargs = {"owner": owner,"hardware": hardware,"token": token,"log": _log,**create_kwargs,}if hardware != "cpu-basic":kwargs["sleep_time"] = 2700sb = await asyncio.to_thread(Sandbox.create, **kwargs)session.sandbox = sb# Set a descriptive title (template title is inherited on duplicate)from huggingface_hub import metadata_updateawait asyncio.to_thread(metadata_update,sb.space_id,{"title": "ml-agent sandbox"},repo_type="space",overwrite=True,token=token,)# Inject the OAuth token into the sandbox so Hub operations work inside itawait asyncio.to_thread(api.add_space_secret, sb.space_id, "HF_TOKEN", token)
agent/core/agent_loop.py+104-14
agent/core/session.py+1
agent/tools/jobs_tool.py+8
agent/tools/sandbox_client.py+48-10
agent/tools/sandbox_tool.py+29-6