fix(setup-agent): prevent data loss when setup fails on existing agen… (#2254)

* fix(setup-agent): prevent data loss when setup fails on existing agent directory

Record whether the agent directory pre-existed before mkdir, and only
run shutil.rmtree cleanup when the directory was newly created during
this call. Previously, any failure would delete the entire directory
including pre-existing SOUL.md and config.yaml.

* fix: address PR review — init variables before try, remove unused result

* style: fix ruff I001 import block formatting in test file

* style: add missing blank lines between top-level definitions in test file
This commit is contained in:
imhaoran
2026-04-20 20:17:30 +08:00
committed by GitHub
parent f2013f47aa
commit fc94e90f6c
2 changed files with 91 additions and 2 deletions
@@ -27,11 +27,13 @@ def setup_agent(
agent_name: str | None = runtime.context.get("agent_name") if runtime.context else None
agent_dir = None
is_new_dir = False
try:
agent_name = validate_agent_name(agent_name)
paths = get_paths()
agent_dir = paths.agent_dir(agent_name) if agent_name else paths.base_dir
is_new_dir = not agent_dir.exists()
agent_dir.mkdir(parents=True, exist_ok=True)
if agent_name:
@@ -58,8 +60,8 @@ def setup_agent(
except Exception as e:
import shutil
if agent_name and agent_dir is not None and agent_dir.exists():
# Cleanup the custom agent directory only if it was created but an error occurred during setup
if agent_name and is_new_dir and agent_dir is not None and agent_dir.exists():
# Cleanup the custom agent directory only if it was newly created during this call
shutil.rmtree(agent_dir)
logger.error(f"[agent_creator] Failed to create agent '{agent_name}': {e}", exc_info=True)
return Command(update={"messages": [ToolMessage(content=f"Error: {e}", tool_call_id=runtime.tool_call_id)]})