Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(copilot): Make Trigger Agent creation more consistent (#13309)

Reinier van der Leer5b9ff5a81464
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index e9361252f5..7a843389a6 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -910,10 +910,20 @@ async def delete_library_agent(
graph_id = library_agent.agentGraphId
- # Clean up associated schedules and webhooks BEFORE deleting the agent
- # This prevents executions from starting after agent deletion
+ # Clean up everything that drives this agent BEFORE deleting it, so
+ # nothing keeps firing against a half-deleted agent (schedules, webhooks,
+ # and the trigger agents that exist solely to run it).
await _cleanup_schedules_for_graph(graph_id=graph_id, user_id=user_id)
await _cleanup_webhooks_for_graph(graph_id=graph_id, user_id=user_id)
+ # A trigger agent is a hidden agent whose graph runs this (action) agent
+ # via an AgentExecutorBlock; once the action agent is gone it has no
+ # purpose and is never shown on its own, so it must be cleaned up too.
+ # Skip when deleting a hidden agent — triggers don't have triggers, which
+ # also bounds the recursion at one level.
+ if not library_agent.isHidden:
+ await _cleanup_trigger_agents_for_graph(
+ action_graph_id=graph_id, user_id=user_id, soft_delete=soft_delete
+ )
# Delete the library agent after cleanup
if soft_delete:
@@ -930,6 +940,76 @@ async def delete_library_agent(
raise NotFoundError(f"Library agent #{library_agent_id} not found")
+async def _cleanup_trigger_agents_for_graph(
+ action_graph_id: str, user_id: str, soft_delete: bool
+) -> None:
+ """Delete hidden trigger agents that exist only to drive the given action
+ agent.
+
+ Trigger agents reference their action (parent) agent via an
+ AgentExecutorBlock ``graph_id``. When the action agent is deleted they're
+ orphaned — and since they're never listed on their own, they'd linger
+ invisibly. Delete each trigger whose ONLY AgentExecutorBlock sink is the
+ deleted action agent; keep any trigger that also drives a different agent.
+ """
+ triggers = await prisma.models.LibraryAgent.prisma().find_many(
+ where=_trigger_agent_where(user_id, action_graph_id),
+ )
+
+ for trigger in triggers:
+ if await _trigger_targets_other_graph(
+ trigger_graph_id=trigger.agentGraphId,
+ trigger_graph_version=trigger.agentGraphVersion,
+ action_graph_id=action_graph_id,
+ user_id=user_id,
+ ):
+ logger.info(
+ "Keeping trigger agent %s — it drives agents other than %s",
+ trigger.id,
+ action_graph_id,
+ )
+ continue
+ try:
+ await delete_library_agent(
+ library_agent_id=trigger.id,
+ user_id=user_id,
+ soft_delete=soft_delete,
+ )
+ logger.info(
+ "Deleted trigger agent %s orphaned by action agent %s",
+ trigger.id,
+ action_graph_id,
+ )
+ except NotFoundError:
+ # Already gone (e.g. concurrent delete) — nothing to do.
+ pass
+
+
+async def _trigger_targets_other_graph(
+ trigger_graph_id: str,
+ trigger_graph_version: int,
+ action_graph_id: str,
+ user_id: str,
+) -> bool:
+ """Whether the trigger agent drives any action agent OTHER than the one
+ being deleted — i.e. has an AgentExecutorBlock whose ``graph_id`` is set
+ and differs from ``action_graph_id``. Such triggers are kept; the deleted
+ agent isn't their only sink. A node with no ``graph_id`` is malformed and
+ doesn't count as a distinct target, so it never keeps an orphan alive."""
+ executor_nodes = await prisma.models.AgentNode.prisma().find_many(
+ where={
+ "agentGraphId": trigger_graph_id,
+ "agentGraphVersion": trigger_graph_version,
+ "agentBlockId": _AGENT_EXECUTOR_BLOCK_ID,
+ # Defense-in-depth: scope to the owner. The caller already found
+ # this trigger under the same user, so this is belt-and-braces.
+ "AgentGraph": {"is": {"userId": user_id}},
+ },
+ )
+ targets = {dict(node.constantInput).get("graph_id") for node in executor_nodes}
+ return any(target and target != action_graph_id for target in targets)
+
+
async def _cleanup_schedules_for_graph(graph_id: str, user_id: str) -> None:
"""
Clean up all schedules for a specific graph and user.
@@ -2095,6 +2175,38 @@ async def fork_library_agent(
_AGENT_EXECUTOR_BLOCK_ID = "e189baac-8c20-45a1-94a7-55177ea42565"
+def _trigger_agent_where(
+ user_id: str, parent_graph_id: str
+) -> prisma.types.LibraryAgentWhereInput:
+ """Where-clause selecting a parent's trigger agents: the user's active,
+ hidden agents whose graph runs the parent via an AgentExecutorBlock
+ referencing its ``graph_id``. Shared by ``list_trigger_agents`` and the
+ delete cascade so the derived relationship is defined in one place and
+ can't drift between them."""
+ return {
+ "userId": user_id,
+ "isHidden": True,
+ "isDeleted": False,
+ "isArchived": False,
+ "AgentGraph": {
+ "is": {
+ "Nodes": {
+ "some": {
+ "agentBlockId": _AGENT_EXECUTOR_BLOCK_ID,
+ "constantInput": cast(
+ prisma.types.JsonFilter,
+ {
+ "path": ["graph_id"],
+ "equals": prisma.Json(parent_graph_id),
+ },
+ ),
+ }
+ }
+ }
+ },
+ }
+
+
async def list_trigger_agents(
user_id: str,
library_agent_id: str,
@@ -2117,28 +2229,7 @@ async def list_trigger_agents(
triggers, schedule_info = await asyncio.gather(
prisma.models.LibraryAgent.prisma().find_many(
- where={
- "userId": user_id,
- "isHidden": True,
- "isDeleted": False,
- "isArchived": False,
- "AgentGraph": {
- "is": {
- "Nodes": {
- "some": {
- "agentBlockId": _AGENT_EXECUTOR_BLOCK_ID,
- "constantInput": cast(
- prisma.types.JsonFilter,
- {
- "path": ["graph_id"],
- "equals": prisma.Json(parent_graph_id),
- },
- ),
- }
- }
- }
- },
- },
+ where=_trigger_agent_where(user_id, parent_graph_id),
include=library_agent_include(
user_id, include_nodes=False, include_executions=False
),
diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.py
index 94deebe6ba..4603f4ed64 100644
--- a/autogpt_platform/backend/backend/api/features/library/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py
@@ -1,13 +1,17 @@
+import json
from contextlib import asynccontextmanager
from datetime import datetime
+from typing import cast
from unittest.mock import AsyncMock, MagicMock, patch
import prisma.enums
+import prisma.fields
import prisma.models
import pytest
from backend.data.db import connect
from backend.data.includes import library_agent_include
+from backend.util.exceptions import NotFoundError
from . import db
from . import model as library_model
@@ -811,3 +815,270 @@ async def test_fetch_execution_counts_uses_group_by(mocker):
},
count=True,
)
+
+
+def _library_agent_prisma(
+ *,
+ id: str,
+ graph_id: str,
+ is_hidden: bool,
+ user_id: str = "test-user",
+) -> prisma.models.LibraryAgent:
+ """Build a minimal LibraryAgent prisma row for delete-cascade tests."""
+ return prisma.models.LibraryAgent(
+ id=id,
+ userId=user_id,
+ agentGraphId=graph_id,
+ settings="{}", # type: ignore
+ agentGraphVersion=1,
+ isCreatedByUser=True,
+ isDeleted=False,
+ isArchived=False,
+ isHidden=is_hidden,
+ createdAt=datetime.now(),
+ updatedAt=datetime.now(),
+ isFavorite=False,
+ useGraphIsActiveVersion=True,
+ AgentGraph=prisma.models.AgentGraph(
+ id=graph_id,
+ version=1,
+ name="Agent",
+ description="",
+ userId=user_id,
+ isActive=True,
+ createdAt=datetime.now(),
+ ),
+ )
+
+
+async def test_delete_library_agent_cascades_to_trigger_agents(mocker):
+ """Deleting an action (parent) agent must also clean up the hidden
+ trigger agents that exist only to drive it."""
+ action = _library_agent_prisma(
+ id="action-id", graph_id="action-graph", is_hidden=False
+ )
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_unique = mocker.AsyncMock(return_value=action)
+ mock_prisma.return_value.update_many = mocker.AsyncMock(return_value=1)
+ mocker.patch.object(db, "_cleanup_schedules_for_graph", new=mocker.AsyncMock())
+ mocker.patch.object(db, "_cleanup_webhooks_for_graph", new=mocker.AsyncMock())
+ cascade = mocker.patch.object(
+ db, "_cleanup_trigger_agents_for_graph", new=mocker.AsyncMock()
+ )
+
+ await db.delete_library_agent("action-id", "test-user", soft_delete=True)
+
+ cascade.assert_awaited_once_with(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=True
+ )
+
+
+async def test_delete_library_agent_skips_cascade_for_hidden_agent(mocker):
+ """A trigger agent (hidden) has no triggers of its own, so deleting one
+ must NOT kick off a cascade lookup."""
+ trigger = _library_agent_prisma(id="trig-id", graph_id="trig-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_unique = mocker.AsyncMock(return_value=trigger)
+ mock_prisma.return_value.update_many = mocker.AsyncMock(return_value=1)
+ mocker.patch.object(db, "_cleanup_schedules_for_graph", new=mocker.AsyncMock())
+ mocker.patch.object(db, "_cleanup_webhooks_for_graph", new=mocker.AsyncMock())
+ cascade = mocker.patch.object(
+ db, "_cleanup_trigger_agents_for_graph", new=mocker.AsyncMock()
+ )
+
+ await db.delete_library_agent("trig-id", "test-user", soft_delete=True)
+
+ cascade.assert_not_called()
+
+
+async def test_cleanup_trigger_agents_deletes_sole_sink_trigger(mocker):
+ """A trigger whose only AgentExecutorBlock sink is the deleted action
+ agent gets deleted."""
+ trigger = _library_agent_prisma(id="trig-id", graph_id="trig-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=[trigger])
+ mocker.patch.object(
+ db, "_trigger_targets_other_graph", new=mocker.AsyncMock(return_value=False)
+ )
+ recursive_delete = mocker.patch.object(
+ db, "delete_library_agent", new=mocker.AsyncMock()
+ )
+
+ await db._cleanup_trigger_agents_for_graph(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=True
+ )
+
+ recursive_delete.assert_awaited_once_with(
+ library_agent_id="trig-id", user_id="test-user", soft_delete=True
+ )
+ # Candidate query must be scoped to hidden, non-deleted agents of the
+ # user whose graph runs the action agent via AgentExecutorBlock.
+ where = mock_prisma.return_value.find_many.call_args.kwargs["where"]
+ assert where["userId"] == "test-user"
+ assert where["isHidden"] is True
+ assert where["isDeleted"] is False
+ assert where["isArchived"] is False
+ nodes_some = where["AgentGraph"]["is"]["Nodes"]["some"]
+ assert nodes_some["agentBlockId"] == db._AGENT_EXECUTOR_BLOCK_ID
+ assert nodes_some["constantInput"]["equals"] == prisma.Json("action-graph")
+
+
+async def test_cleanup_trigger_agents_keeps_trigger_with_other_sinks(mocker):
+ """A trigger that also drives a different action agent is kept — the
+ deleted agent is not its only sink."""
+ trigger = _library_agent_prisma(id="trig-id", graph_id="trig-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=[trigger])
+ mocker.patch.object(
+ db, "_trigger_targets_other_graph", new=mocker.AsyncMock(return_value=True)
+ )
+ recursive_delete = mocker.patch.object(
+ db, "delete_library_agent", new=mocker.AsyncMock()
+ )
+
+ await db._cleanup_trigger_agents_for_graph(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=True
+ )
+
+ recursive_delete.assert_not_called()
+
+
+def _executor_node(graph_id: str | None, node_id: str = "n") -> prisma.models.AgentNode:
+ """Build an AgentExecutorBlock node targeting ``graph_id`` (omit the key
+ when None). ``constantInput`` is passed as a JSON *string* on purpose:
+ Prisma model construction validates Json fields from raw JSON and parses
+ them, so ``node.constantInput`` is a dict afterward — matching how Prisma
+ deserializes DB rows (a plain dict here raises a Json validation error)."""
+ payload = {"graph_id": graph_id} if graph_id is not None else {}
+ return prisma.models.AgentNode(
+ id=node_id,
+ agentBlockId=db._AGENT_EXECUTOR_BLOCK_ID,
+ agentGraphId="trig-graph",
+ agentGraphVersion=1,
+ # Prisma Json fields validate from a raw JSON string and parse it, so
+ # cast str -> fields.Json (a plain dict raises a Json validation error).
+ constantInput=cast(prisma.fields.Json, json.dumps(payload)),
+ metadata=cast(prisma.fields.Json, "{}"),
+ )
+
+
+async def _trigger_targets_other(mocker, nodes) -> bool:
+ mock_prisma = mocker.patch("prisma.models.AgentNode.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=nodes)
+ return await db._trigger_targets_other_graph(
+ trigger_graph_id="trig-graph",
+ trigger_graph_version=1,
+ action_graph_id="action-graph",
+ user_id="test-user",
+ )
+
+
+async def test_trigger_targets_other_graph_detects_extra_sink(mocker):
+ """True when the trigger has an AgentExecutorBlock pointing at a graph
+ other than the one being deleted, False when all sinks point at it."""
+ assert (
+ await _trigger_targets_other(
+ mocker,
+ [_executor_node("other-graph", "n1"), _executor_node("action-graph", "n2")],
+ )
+ is True
+ )
+ assert (
+ await _trigger_targets_other(mocker, [_executor_node("action-graph")]) is False
+ )
+
+
+async def test_trigger_targets_other_graph_empty_nodes(mocker):
+ """No AgentExecutorBlock nodes → not targeting anything else → the trigger
+ is treated as a sole-sink orphan and will be deleted."""
+ assert await _trigger_targets_other(mocker, []) is False
+
+
+async def test_trigger_targets_other_graph_ignores_missing_graph_id(mocker):
+ """A malformed node with no graph_id is not a distinct target, so it never
+ keeps an orphan alive: alongside a sole action-graph sink the result is
+ still False."""
+ assert (
+ await _trigger_targets_other(
+ mocker, [_executor_node(None, "n1"), _executor_node("action-graph", "n2")]
+ )
+ is False
+ )
+
+
+async def test_cleanup_trigger_agents_handles_concurrent_delete(mocker):
+ """If a trigger is already gone (recursive delete raises NotFoundError),
+ the cleanup loop swallows it and continues."""
+ trigger = _library_agent_prisma(id="trig-id", graph_id="trig-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=[trigger])
+ mocker.patch.object(
+ db, "_trigger_targets_other_graph", new=mocker.AsyncMock(return_value=False)
+ )
+ mocker.patch.object(
+ db,
+ "delete_library_agent",
+ new=mocker.AsyncMock(side_effect=NotFoundError("gone")),
+ )
+
+ # Must not raise.
+ await db._cleanup_trigger_agents_for_graph(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=True
+ )
+
+
+async def test_cleanup_trigger_agents_propagates_soft_delete_false(mocker):
+ """soft_delete=False reaches the recursive delete_library_agent call."""
+ trigger = _library_agent_prisma(id="trig-id", graph_id="trig-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=[trigger])
+ mocker.patch.object(
+ db, "_trigger_targets_other_graph", new=mocker.AsyncMock(return_value=False)
+ )
+ recursive_delete = mocker.patch.object(
+ db, "delete_library_agent", new=mocker.AsyncMock()
+ )
+
+ await db._cleanup_trigger_agents_for_graph(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=False
+ )
+
+ recursive_delete.assert_awaited_once_with(
+ library_agent_id="trig-id", user_id="test-user", soft_delete=False
+ )
+
+
+async def test_cleanup_trigger_agents_processes_each_independently(mocker):
+ """With several candidates, only the sole-sink triggers are deleted; ones
+ that also drive another agent are kept."""
+ sole = _library_agent_prisma(id="sole", graph_id="sole-graph", is_hidden=True)
+ multi = _library_agent_prisma(id="multi", graph_id="multi-graph", is_hidden=True)
+ mock_prisma = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_prisma.return_value.find_many = mocker.AsyncMock(return_value=[sole, multi])
+ # sole → no other sink (delete); multi → has another sink (keep)
+ mocker.patch.object(
+ db,
+ "_trigger_targets_other_graph",
+ new=mocker.AsyncMock(side_effect=[False, True]),
+ )
+ recursive_delete = mocker.patch.object(
+ db, "delete_library_agent", new=mocker.AsyncMock()
+ )
+
+ await db._cleanup_trigger_agents_for_graph(
+ action_graph_id="action-graph", user_id="test-user", soft_delete=True
+ )
+
+ recursive_delete.assert_awaited_once_with(
+ library_agent_id="sole", user_id="test-user", soft_delete=True
+ )
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
index b6b73107a6..7eaa1d7140 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
@@ -161,6 +161,13 @@ descriptions; read and follow those when `find_block` surfaces a match.
### Key Rules
+- **Prefer pure logic over AI**: AI blocks (text generation, orchestrators)
+ cost orders of magnitude more than deterministic blocks. When a task has an
+ equivalent non-AI solution — e.g. parsing, filtering, math, string formatting,
+ date handling, conditionals, code execution — use the deterministic block
+ (e.g. `CodeExecutionBlock`, `ConditionBlock`) instead of an LLM. Reserve AI
+ for what genuinely needs it (open-ended reasoning, summarization, generation).
+ Don't spend the user's money on AI for work plain logic can do.
- **Name & description**: Include `name` and `description` in the agent JSON
when creating a new agent, or when editing and the agent's purpose changed.
Without these the agent gets a generic default name.
@@ -436,66 +443,67 @@ saves a run as one). See each tool's description for arguments.
### Building Trigger Agents
-A **trigger agent** is a scheduled agent that watches for changes in an
-external source (e.g. email inbox, RSS feed, API) and runs a parent agent
-or AutoPilot session for each new item. Trigger agents are hidden from the
-user's library but listed under the parent agent's triggers.
-
-**Pattern: Fetch → Compare → Store → Sink**
-
-1. **Fetch current state**: Use a data-fetching block (e.g. RSS, email,
- HTTP request) to get the latest items from the source.
-2. **Retrieve stored state**: Use `RetrieveInformationBlock`
- (ID: `d8710fc9-6e29-481e-a7d5-165eb16f8471`) with scope `within_agent`
- to load the previously stored state (e.g. list of seen item IDs).
-3. **Compare**: Use a `CodeExecutionBlock` to diff the fetched items
- against the stored state. Output the new items (if any).
-4. **Store updated state**: Use `PersistInformationBlock`
- (ID: `1d055e55-a2b9-4547-8311-907d05b0304d`) with scope `within_agent`
- to save the current state for the next run.
+A **trigger agent** is a hidden, scheduled agent that watches an external
+source (email, RSS, API) and runs a separate **action agent** (a.k.a.
+**parent agent**) once per detected change. It's listed under the parent's
+triggers, not in the user's library.
+
+**Split into two agents (REQUIRED):** when the goal is to **poll a source and
+act only when a change/event is detected**, build **TWO SEPARATE agents** — an
+action agent that handles ONE event, and a trigger agent that polls and
+invokes it via `AgentExecutorBlock`. Never merge polling + action into one
+scheduled agent: it runs on every poll, so its run list is mostly empty polls
+and the user can't tell which runs did anything. Splitting gives the action
+agent **one run per real event** — the history users actually want.
+
+**Boundary — do NOT over-split:** an agent that does the same work and emits
+output every run (e.g. "email me prices every morning") stays a **single
+scheduled agent**. Only split when some runs would otherwise do nothing.
+
+**Trigger-agent pattern: Fetch → Compare → Store → Sink**
+
+1. **Fetch**: a data-fetching block (RSS, email, HTTP request) gets the
+ latest items from the source.
+2. **Retrieve stored state**: `RetrieveInformationBlock`
+ (ID: `d8710fc9-6e29-481e-a7d5-165eb16f8471`), scope `within_agent`, loads
+ previously-seen item IDs.
+3. **Compare**: a `CodeExecutionBlock` diffs fetched items against stored
+ state and outputs the new ones (if any).
+4. **Store updated state**: `PersistInformationBlock`
+ (ID: `1d055e55-a2b9-4547-8311-907d05b0304d`), scope `within_agent`, saves
+ the current state for next run.
5. **Sink** — for each new item, do one of:
- - **Run an agent**: Use `AgentExecutorBlock`
- (ID: `e189baac-8c20-45a1-94a7-55177ea42565`) to run the parent
- agent with the new item as input.
- - **Start an AutoPilot session**: Use `AutoPilotBlock`
- (ID: `c069dc6b-c3ed-4c12-b6e5-d47361e64ce6`) with a prompt
- describing the new item (e.g. "New email from {sender} about
+ - **Run the action agent (preferred)**: `AgentExecutorBlock`
+ (ID: `e189baac-8c20-45a1-94a7-55177ea42565`) runs the parent agent with
+ the new item as input — one parent run per event.
+ - **Start an AutoPilot session** (only when there's no reusable action
+ agent): `AutoPilotBlock` (ID: `c069dc6b-c3ed-4c12-b6e5-d47361e64ce6`)
+ with a prompt describing the item (e.g. "New email from {sender} about
{subject}. Analyze and draft a reply.").
-**Creating a trigger agent:**
-
-1. Build the trigger agent JSON following the pattern above. When using
- the AgentExecutorBlock sink, set its `graph_id` (in `input_default`)
- to the parent agent's graph_id — this is how the trigger is linked
- to the parent agent.
-2. Save it with `is_hidden=true` via `create_agent` so it doesn't
- clutter the user's library.
-3. Schedule it to run on a cron interval (e.g. every 15 minutes:
- `*/15 * * * *`) using `run_agent` with `schedule_name` and `cron`.
-
-The parent → trigger relationship is **derived from the graph
-contents**: any hidden agent whose graph contains an AgentExecutorBlock
-referencing the parent's graph_id is listed under that parent's
-triggers. No explicit linking is needed.
-
-**Inspecting an agent's existing triggers:**
-
-- Use `list_agent_triggers` with the parent's `library_agent_id` to see
- all triggers configured for that agent — both trigger agents
- (`kind="agent"`) and webhook presets (`kind="webhook"`). Use this
- before adding a new trigger (to avoid duplicates) or before deleting
- one (to find the right ID). For `kind="webhook"` triggers it also
- returns the `webhook_url` — give that to the user verbatim if they need
- to (re)configure their external service.
-
-**Managing schedules:**
-
-- Use `list_schedules` to see existing schedules (optionally filtered by
- `graph_id`).
-- Use `delete_schedule` with a `schedule_id` to remove one.
-- To change a schedule's cron, delete it and re-create via `run_agent`
- with the new `cron`.
-
-**Note**: When a trigger agent is edited and a new version is created,
-the existing schedule will still run the old version. Delete the old
-schedule and re-create it with the new version after editing.
+**Creating the two agents:**
+
+1. Build and save the **action agent** first, visibly (`create_agent`); it
+ takes a single event as input. Reuse an existing agent if one fits.
+2. Read its `graph_id`, `graph_version`, `input_schema`, and `output_schema`
+ via `find_library_agent` to wire the `AgentExecutorBlock`.
+3. Build the **trigger agent** with the pattern above; set its
+ `AgentExecutorBlock` `graph_id` (in `input_default`) to the action agent's
+ `graph_id`, and save with `is_hidden=true`.
+4. Schedule it on a cron interval (e.g. `*/15 * * * *`) via `run_agent` with
+ `schedule_name` and `cron`.
+
+The parent → trigger link is **derived from graph contents**: any hidden
+agent whose graph contains an `AgentExecutorBlock` referencing the parent's
+`graph_id` is listed under that parent's triggers — no explicit linking
+needed.
+
+**Managing triggers:** `list_agent_triggers` (parent's `library_agent_id`)
+lists trigger agents (`kind="agent"`) and webhook presets (`kind="webhook"`);
+check it before adding or deleting one. For `kind="webhook"` triggers it also
+returns the `webhook_url` — give that to the user verbatim if they need to
+(re)configure their external service. `list_schedules` (optionally filtered by
+`graph_id`) and `delete_schedule` manage schedules — change a cron by deleting
+and re-creating via `run_agent`. **Note**: editing a trigger agent makes a new
+version, but the old schedule keeps running the old one — delete and re-create
+the schedule after editing.
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
index d4d7a48f9f..e22ea45398 100644
--- a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide_test.py
@@ -33,6 +33,23 @@ def test_guide_contains_trigger_agents_heading():
assert f"\n### {_TRIGGER_AGENTS_HEADING}" in guide
+def test_guide_mandates_separate_trigger_and_action_agents():
+ """OPEN-3155: the trigger-agents guidance must tell the model to split
+ polling and action into two separate agents (not one scheduled agent that
+ runs every poll). If this phrase is reworded, update the sentinel here —
+ but keep the two-agent-separation guidance present."""
+ guide = _load_guide()
+ assert "TWO SEPARATE agents" in guide
+
+
+def test_guide_warns_against_over_splitting_scheduled_agents():
+ """OPEN-3155: the guidance must also warn against over-splitting — a plain
+ 'do X on a schedule' agent that acts every run should stay a single agent.
+ Guards the boundary clause from being dropped in future edits."""
+ guide = _load_guide()
+ assert "do NOT over-split" in guide
+
+
def test_strip_h3_section_preserves_following_sections():
"""A future H3 section appended after the gated one must survive
the strip — that's the whole reason the gating is section-aware