Skip to content

Commit 59c4a3f

Browse files
feat(agent): add custom-agent self-updates with user isolation (#2713)
* feat(agent): add update_agent tool for in-chat custom-agent self-updates (#2616) Custom agents had no built-in way to persist updates to their own SOUL.md / config.yaml from a normal chat — `setup_agent` was only bound during the bootstrap flow, so when the user asked the agent to refine its description or personality, the agent would shell out via bash/write_file and the edits landed in a temporary sandbox/tool workspace instead of `{base_dir}/agents/{agent_name}/`. Changes: - New `update_agent` builtin tool with partial-update semantics (only the fields you pass are written) and atomic temp-file + os.replace writes so a failed update never corrupts existing SOUL.md / config.yaml. - Lead agent now binds `update_agent` in the non-bootstrap path whenever `agent_name` is set in the runtime context. Default agent (no agent_name) and bootstrap flow are unchanged. - New `<self_update>` system-prompt section is injected for custom agents, instructing them to use `update_agent` — and explicitly NOT bash / write_file — to persist self-updates. - Tests: 11 new cases in `tests/test_update_agent_tool.py` covering validation (missing/invalid agent_name, unknown agent, no fields), partial updates (soul-only, description-only, skills=[] vs omitted), no-op detection, atomic-write safety, and AgentConfig round-tripping; plus 2 new cases in `tests/test_lead_agent_prompt.py` covering the self-update prompt section. - Docs: updated backend/CLAUDE.md builtin tools list and tools.mdx (en/zh) with the new tool description. * feat(agent): isolate custom agents per user Store custom agent definitions under the effective user, keep legacy agents readable until migration, and cover API/tool/migration behavior with tests. Co-authored-by: Cursor <cursoragent@cursor.com> * feat: consistent write/delete targets & add --user-id to migration --------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent e8675f2 commit 59c4a3f

18 files changed

Lines changed: 956 additions & 61 deletions

File tree

backend/CLAUDE.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,8 @@ Proxied through nginx: `/api/langgraph/*` → LangGraph, all other `/api/*` →
263263
- `present_files` - Make output files visible to user (only `/mnt/user-data/outputs`)
264264
- `ask_clarification` - Request clarification (intercepted by ClarificationMiddleware → interrupts)
265265
- `view_image` - Read image as base64 (added only if model supports vision)
266+
- `setup_agent` - Bootstrap-only: persist a brand-new custom agent's `SOUL.md` and `config.yaml`. Bound only when `is_bootstrap=True`.
267+
- `update_agent` - Custom-agent-only: persist self-updates to the current agent's `SOUL.md` / `config.yaml` from inside a normal chat (partial update + atomic write). Bound when `agent_name` is set and `is_bootstrap=False`.
266268
4. **Subagent tool** (if enabled):
267269
- `task` - Delegate to subagent (description, prompt, subagent_type, max_turns)
268270

@@ -354,10 +356,11 @@ Bridges external messaging platforms (Feishu, Slack, Telegram, DingTalk) to the
354356
**Per-User Isolation**:
355357
- Memory is stored per-user at `{base_dir}/users/{user_id}/memory.json`
356358
- Per-agent per-user memory at `{base_dir}/users/{user_id}/agents/{agent_name}/memory.json`
359+
- Custom agent definitions (`SOUL.md` + `config.yaml`) are also per-user at `{base_dir}/users/{user_id}/agents/{agent_name}/`. The legacy shared layout `{base_dir}/agents/{agent_name}/` remains read-only fallback for unmigrated installations
357360
- `user_id` is resolved via `get_effective_user_id()` from `deerflow.runtime.user_context`
358361
- In no-auth mode, `user_id` defaults to `"default"` (constant `DEFAULT_USER_ID`)
359362
- Absolute `storage_path` in config opts out of per-user isolation
360-
- **Migration**: Run `PYTHONPATH=. python scripts/migrate_user_isolation.py` to move legacy `memory.json` and `threads/` into per-user layout; supports `--dry-run`
363+
- **Migration**: Run `PYTHONPATH=. python scripts/migrate_user_isolation.py` to move legacy `memory.json`, `threads/`, and `agents/` into per-user layout. Supports `--dry-run` (preview changes) and `--user-id USER_ID` (assign unowned legacy data to a user, defaults to `default`).
361364

362365
**Data Structure** (stored in `{base_dir}/users/{user_id}/memory.json`):
363366
- **User Context**: `workContext`, `personalContext`, `topOfMind` (1-3 sentence summaries)

backend/app/gateway/routers/agents.py

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from deerflow.config.agents_api_config import get_agents_api_config
1212
from deerflow.config.agents_config import AgentConfig, list_custom_agents, load_agent_config, load_agent_soul
1313
from deerflow.config.paths import get_paths
14+
from deerflow.runtime.user_context import get_effective_user_id
1415

1516
logger = logging.getLogger(__name__)
1617
router = APIRouter(prefix="/api", tags=["agents"])
@@ -86,11 +87,11 @@ def _require_agents_api_enabled() -> None:
8687
)
8788

8889

89-
def _agent_config_to_response(agent_cfg: AgentConfig, include_soul: bool = False) -> AgentResponse:
90+
def _agent_config_to_response(agent_cfg: AgentConfig, include_soul: bool = False, *, user_id: str | None = None) -> AgentResponse:
9091
"""Convert AgentConfig to AgentResponse."""
9192
soul: str | None = None
9293
if include_soul:
93-
soul = load_agent_soul(agent_cfg.name) or ""
94+
soul = load_agent_soul(agent_cfg.name, user_id=user_id) or ""
9495

9596
return AgentResponse(
9697
name=agent_cfg.name,
@@ -116,9 +117,10 @@ async def list_agents() -> AgentsListResponse:
116117
"""
117118
_require_agents_api_enabled()
118119

120+
user_id = get_effective_user_id()
119121
try:
120-
agents = list_custom_agents()
121-
return AgentsListResponse(agents=[_agent_config_to_response(a, include_soul=True) for a in agents])
122+
agents = list_custom_agents(user_id=user_id)
123+
return AgentsListResponse(agents=[_agent_config_to_response(a, include_soul=True, user_id=user_id) for a in agents])
122124
except Exception as e:
123125
logger.error(f"Failed to list agents: {e}", exc_info=True)
124126
raise HTTPException(status_code=500, detail=f"Failed to list agents: {str(e)}")
@@ -144,7 +146,12 @@ async def check_agent_name(name: str) -> dict:
144146
_require_agents_api_enabled()
145147
_validate_agent_name(name)
146148
normalized = _normalize_agent_name(name)
147-
available = not get_paths().agent_dir(normalized).exists()
149+
user_id = get_effective_user_id()
150+
paths = get_paths()
151+
# Treat the name as taken if either the per-user path or the legacy shared
152+
# path holds an agent — picking a name that collides with an unmigrated
153+
# legacy agent would shadow the legacy entry once migration runs.
154+
available = not paths.user_agent_dir(user_id, normalized).exists() and not paths.agent_dir(normalized).exists()
148155
return {"available": available, "name": normalized}
149156

150157

@@ -169,10 +176,11 @@ async def get_agent(name: str) -> AgentResponse:
169176
_require_agents_api_enabled()
170177
_validate_agent_name(name)
171178
name = _normalize_agent_name(name)
179+
user_id = get_effective_user_id()
172180

173181
try:
174-
agent_cfg = load_agent_config(name)
175-
return _agent_config_to_response(agent_cfg, include_soul=True)
182+
agent_cfg = load_agent_config(name, user_id=user_id)
183+
return _agent_config_to_response(agent_cfg, include_soul=True, user_id=user_id)
176184
except FileNotFoundError:
177185
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
178186
except Exception as e:
@@ -202,10 +210,13 @@ async def create_agent_endpoint(request: AgentCreateRequest) -> AgentResponse:
202210
_require_agents_api_enabled()
203211
_validate_agent_name(request.name)
204212
normalized_name = _normalize_agent_name(request.name)
213+
user_id = get_effective_user_id()
214+
paths = get_paths()
205215

206-
agent_dir = get_paths().agent_dir(normalized_name)
216+
agent_dir = paths.user_agent_dir(user_id, normalized_name)
217+
legacy_dir = paths.agent_dir(normalized_name)
207218

208-
if agent_dir.exists():
219+
if agent_dir.exists() or legacy_dir.exists():
209220
raise HTTPException(status_code=409, detail=f"Agent '{normalized_name}' already exists")
210221

211222
try:
@@ -232,8 +243,8 @@ async def create_agent_endpoint(request: AgentCreateRequest) -> AgentResponse:
232243

233244
logger.info(f"Created agent '{normalized_name}' at {agent_dir}")
234245

235-
agent_cfg = load_agent_config(normalized_name)
236-
return _agent_config_to_response(agent_cfg, include_soul=True)
246+
agent_cfg = load_agent_config(normalized_name, user_id=user_id)
247+
return _agent_config_to_response(agent_cfg, include_soul=True, user_id=user_id)
237248

238249
except HTTPException:
239250
raise
@@ -267,13 +278,20 @@ async def update_agent(name: str, request: AgentUpdateRequest) -> AgentResponse:
267278
_require_agents_api_enabled()
268279
_validate_agent_name(name)
269280
name = _normalize_agent_name(name)
281+
user_id = get_effective_user_id()
270282

271283
try:
272-
agent_cfg = load_agent_config(name)
284+
agent_cfg = load_agent_config(name, user_id=user_id)
273285
except FileNotFoundError:
274286
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
275287

276-
agent_dir = get_paths().agent_dir(name)
288+
paths = get_paths()
289+
agent_dir = paths.user_agent_dir(user_id, name)
290+
if not agent_dir.exists() and paths.agent_dir(name).exists():
291+
raise HTTPException(
292+
status_code=409,
293+
detail=(f"Agent '{name}' only exists in the legacy shared layout and is not scoped to a user. Run scripts/migrate_user_isolation.py to move legacy agents into the per-user layout before updating."),
294+
)
277295

278296
try:
279297
# Update config if any config fields changed
@@ -314,8 +332,8 @@ async def update_agent(name: str, request: AgentUpdateRequest) -> AgentResponse:
314332

315333
logger.info(f"Updated agent '{name}'")
316334

317-
refreshed_cfg = load_agent_config(name)
318-
return _agent_config_to_response(refreshed_cfg, include_soul=True)
335+
refreshed_cfg = load_agent_config(name, user_id=user_id)
336+
return _agent_config_to_response(refreshed_cfg, include_soul=True, user_id=user_id)
319337

320338
except HTTPException:
321339
raise
@@ -402,15 +420,22 @@ async def delete_agent(name: str) -> None:
402420
name: The agent name.
403421
404422
Raises:
405-
HTTPException: 404 if agent not found.
423+
HTTPException: 404 if no per-user copy exists; 409 if only a legacy
424+
shared copy exists (suggesting the migration script).
406425
"""
407426
_require_agents_api_enabled()
408427
_validate_agent_name(name)
409428
name = _normalize_agent_name(name)
410-
411-
agent_dir = get_paths().agent_dir(name)
429+
user_id = get_effective_user_id()
430+
paths = get_paths()
431+
agent_dir = paths.user_agent_dir(user_id, name)
412432

413433
if not agent_dir.exists():
434+
if paths.agent_dir(name).exists():
435+
raise HTTPException(
436+
status_code=409,
437+
detail=(f"Agent '{name}' only exists in the legacy shared layout and is not scoped to a user. Run scripts/migrate_user_isolation.py to move legacy agents into the per-user layout before deleting."),
438+
)
414439
raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
415440

416441
try:

backend/packages/harness/deerflow/agents/lead_agent/agent.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def make_lead_agent(config: RunnableConfig):
318318
def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
319319
# Lazy import to avoid circular dependency
320320
from deerflow.tools import get_available_tools
321-
from deerflow.tools.builtins import setup_agent
321+
from deerflow.tools.builtins import setup_agent, update_agent
322322

323323
cfg = _get_runtime_config(config)
324324
resolved_app_config = app_config
@@ -390,6 +390,9 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
390390
state_schema=ThreadState,
391391
)
392392

393+
# Custom agents can update their own SOUL.md / config via update_agent.
394+
# The default agent (no agent_name) does not see this tool.
395+
extra_tools = [update_agent] if agent_name else []
393396
# Default lead agent (unchanged behavior)
394397
return create_agent(
395398
model=create_chat_model(name=model_name, thinking_enabled=thinking_enabled, reasoning_effort=reasoning_effort, app_config=resolved_app_config),
@@ -398,7 +401,8 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
398401
groups=agent_config.tool_groups if agent_config else None,
399402
subagent_enabled=subagent_enabled,
400403
app_config=resolved_app_config,
401-
),
404+
)
405+
+ extra_tools,
402406
middleware=_build_middlewares(config, model_name=model_name, agent_name=agent_name, app_config=resolved_app_config),
403407
system_prompt=apply_prompt_template(
404408
subagent_enabled=subagent_enabled,

backend/packages/harness/deerflow/agents/lead_agent/prompt.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ def _build_subagent_section(max_concurrent: int, *, app_config: AppConfig | None
344344
</role>
345345
346346
{soul}
347+
{self_update_section}
347348
{memory_context}
348349
349350
<thinking_style>
@@ -643,6 +644,26 @@ def get_agent_soul(agent_name: str | None) -> str:
643644
return ""
644645

645646

647+
def _build_self_update_section(agent_name: str | None) -> str:
648+
"""Prompt block that teaches the custom agent to persist self-updates via update_agent."""
649+
if not agent_name:
650+
return ""
651+
return f"""<self_update>
652+
You are running as the custom agent **{agent_name}** with a persisted SOUL.md and config.yaml.
653+
654+
When the user asks you to update your own description, personality, behaviour, skill set, tool groups, or default model,
655+
you MUST persist the change with the `update_agent` tool. Do NOT use `bash`, `write_file`, or any sandbox tool to edit
656+
SOUL.md or config.yaml — those write into a temporary sandbox/tool workspace and the changes will be lost on the next turn.
657+
658+
Rules:
659+
- Always pass the FULL replacement text for `soul` (no patch semantics). Start from your current SOUL above and apply the user's edits.
660+
- Only pass the fields that should change. Omit the others to preserve them.
661+
- Pass `skills=[]` to disable all skills, or omit `skills` to keep the existing whitelist.
662+
- After `update_agent` returns successfully, tell the user the change is persisted and will take effect on the next turn.
663+
</self_update>
664+
"""
665+
666+
646667
def get_deferred_tools_prompt_section(*, app_config: AppConfig | None = None) -> str:
647668
"""Generate <available-deferred-tools> block for the system prompt.
648669
@@ -772,6 +793,7 @@ def apply_prompt_template(
772793
prompt = SYSTEM_PROMPT_TEMPLATE.format(
773794
agent_name=agent_name or "DeerFlow 2.0",
774795
soul=get_agent_soul(agent_name),
796+
self_update_section=_build_self_update_section(agent_name),
775797
skills_section=skills_section,
776798
deferred_tools_section=deferred_tools_section,
777799
memory_context=memory_context,

0 commit comments

Comments
 (0)