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(platform): standing work — routines for experts and Otto, repeating or once (#14688)

Nicholas Tindleab790ba79bf5
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 2ccf96a516..0457055845 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -65,6 +65,21 @@ from backend.api.features.experts.models import (
decode_day_one,
decode_voice_preferences,
)
+from backend.api.features.experts.routine_jobs import (
+ mark_routine_unscheduled as mark_routine_unscheduled,
+)
+from backend.api.features.experts.routine_jobs import (
+ record_routine_fired as record_routine_fired,
+)
+from backend.api.features.experts.routine_jobs import (
+ record_routine_thread as record_routine_thread,
+)
+from backend.api.features.experts.routines import create_routine as create_routine
+from backend.api.features.experts.routines import disable_routine as disable_routine
+from backend.api.features.experts.routines import enable_routine as enable_routine
+from backend.api.features.experts.routines import get_routine as get_routine
+from backend.api.features.experts.routines import install_routines
+from backend.api.features.experts.routines import list_routines as list_routines
from backend.api.features.experts.workflow_chain import (
build_workflow_chain,
integration_providers,
@@ -950,6 +965,7 @@ async def _hire_expert_impl(
failed = await _install_preloads(expert.id, user_id, template.Workflows or [])
await _install_bundled_skills(user_id, expert.id, template.id)
+ await install_routines(expert.id, await _template_routines(template.id))
hydrated = await prisma.models.Expert.prisma().find_unique(
where={"id": expert.id}, include=_WORKFLOW_INCLUDE
@@ -1754,6 +1770,16 @@ async def _install_preloads(
return failed
+async def _template_routines(
+ template_id: str,
+) -> list[prisma.models.ExpertRoutine]:
+ """The proposals a template ships, in the order the roster declares them."""
+ return await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": template_id},
+ order=[{"createdAt": "asc"}, {"id": "asc"}],
+ )
+
+
async def _install_bundled_skills(
user_id: str, expert_id: str, template_id: str
) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index f4506bc5cd..a17fbdfa70 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -1,4 +1,5 @@
import asyncio
+import itertools
import re
import uuid
from contextlib import asynccontextmanager
@@ -17,7 +18,14 @@ import pytest
import pytest_asyncio
import backend.api.features.store.model as store_model
-from backend.api.features.experts import experts_db, raise_attachments, scheduling, seed
+from backend.api.features.experts import (
+ experts_db,
+ raise_attachments,
+ routine_jobs,
+ routines,
+ scheduling,
+ seed,
+)
from backend.api.features.experts.models import (
EXPERT_DAY_ONE_MAX_ITEMS,
ExpertBundledSkill,
@@ -4242,6 +4250,7 @@ async def test_seed_roster_rescopes_untouched_hires_and_spares_edited_ones(
"boundaries": "Never invent customer evidence.",
"day_one": [],
"preloads": [],
+ "routines": [],
}
monkeypatch.setattr(seed, "ROSTER", [entry])
(template_id,) = await seed.seed_roster()
@@ -5878,3 +5887,607 @@ async def test_update_soul_skips_writing_style_when_voice_unchanged(
),
)
emit.assert_not_called()
+
+
+# =============================================================================
+# Routines: the lifecycle against a real database
+# =============================================================================
+
+
+def _fake_scheduler() -> AsyncMock:
+ """Stands in for the scheduler service, which these tests do not run.
+
+ Each ``add_copilot_turn_schedule`` hands back a distinct id, so a test can
+ tell one-job-per-cron from one-job-reused.
+ """
+ scheduler = AsyncMock()
+ counter = itertools.count(1)
+ scheduler.add_copilot_turn_schedule = AsyncMock(
+ side_effect=lambda **_: SimpleNamespace(id=f"routine-sched-{next(counter)}")
+ )
+ scheduler.pause_schedule = AsyncMock(return_value=True)
+ scheduler.resume_schedule = AsyncMock(return_value=True)
+ scheduler.delete_schedule = AsyncMock(return_value=None)
+ scheduler.get_execution_schedules = AsyncMock(return_value=[])
+ return scheduler
+
+
+async def _template_with_routine(**overrides) -> prisma.models.Expert:
+ """A roster template shipping one proposal, off and reaching nothing."""
+ template = await _seed_template(name="Routiner", preload_listings=[])
+ data: prisma.types.ExpertRoutineCreateInput = {
+ "expertId": template.id,
+ "key": "queue-sweep",
+ "title": "Sweep the queue",
+ "prompt": "Read the queue and stage a draft per item.",
+ "crons": ["H 9 * * 1-5"],
+ "asks": ["Where is the queue?"],
+ **overrides,
+ }
+ await prisma.models.ExpertRoutine.prisma().create(data=data)
+ return template
+
+
[email protected](loop_scope="session")
+async def test_hire_copies_routines_switched_off_with_no_schedule(
+ server: SpinTestServer, test_user
+):
+ """The whole promise of a seeded routine: it arrives, and it does nothing
+ until somebody says so. A row with a scheduleId here would be a cadence
+ firing unattended from the day of hire."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+ assert [r.key for r in installed] == ["queue-sweep"]
+ assert installed[0].enabled is False
+ assert installed[0].customized is False
+ assert installed[0].grants_credentials is False
+ # The line the fire-time mute reads: somebody else wrote this prompt.
+ assert installed[0].source == "TEMPLATE"
+ rows = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": hired.expert.id}
+ )
+ assert rows[0].scheduleIds == []
+ assert rows[0].sessionId is None
+
+
[email protected](loop_scope="session")
+async def test_a_routine_with_unanswered_asks_refuses_to_be_scheduled(
+ server: SpinTestServer, test_user
+):
+ """Enabling straight off the template would run somebody's account against
+ a guess, every weekday, with nobody watching."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+
+ with pytest.raises(routines.RoutineUnansweredAsksError):
+ await experts_db.enable_routine(test_user.id, hired.expert.id, installed[0].id)
+
+ rows = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"id": installed[0].id}
+ )
+ assert rows[0].enabledAt is None
+ assert rows[0].scheduleIds == []
+
+
[email protected](loop_scope="session")
+async def test_enabling_a_routine_resolves_it_and_creates_one_job_per_cron(
+ server: SpinTestServer, test_user
+):
+ template = await _template_with_routine(crons=["H 9 * * 1-5", "H 13 * * 1-5"])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ enabled = await experts_db.enable_routine(
+ test_user.id,
+ hired.expert.id,
+ installed[0].id,
+ prompt="Read the support queue and stage a draft per ticket.",
+ )
+
+ assert enabled.enabled is True
+ assert enabled.customized is True
+ assert enabled.prompt.startswith("Read the support queue")
+ # H is resolved before anything reaches APScheduler, which has never heard
+ # of it. Asserted against the resolver rather than "the two minutes
+ # differ": the minute is one byte of a digest modulo 60, so two fire times
+ # of one routine collide about once in sixty runs, and that assertion
+ # failed on its own with nothing changed.
+ assert all(not c.startswith("H ") for c in enabled.crons)
+ assert enabled.crons == [
+ routine_jobs.spread_cron(cron, seed=f"{test_user.id}:queue-sweep:{index}")
+ for index, cron in enumerate(["H 9 * * 1-5", "H 13 * * 1-5"])
+ ]
+ rows = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"id": installed[0].id}
+ )
+ assert len(rows[0].scheduleIds) == 2
+
+
[email protected](loop_scope="session")
+async def test_a_roster_edit_never_rewrites_a_routine_that_is_running(
+ server: SpinTestServer, test_user
+):
+ """The rule the whole sync hangs on: once a routine is on, or once its
+ owner has changed anything about it, what it does is theirs."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(
+ test_user.id, hired.expert.id, installed[0].id, prompt="The owner's words."
+ )
+
+ entry: seed.RosterEntry = {
+ **seed.ROSTER[0],
+ "name": template.name,
+ "routines": [
+ {
+ "key": "queue-sweep",
+ "title": "Rewritten by the roster",
+ "prompt": "The roster's words.",
+ "crons": ["H 6 * * *"],
+ "asks": [],
+ "session_mode": "THREAD",
+ }
+ ],
+ }
+ await seed._sync_hired_routines(template.id, entry)
+
+ after = await experts_db.list_routines(test_user.id, hired.expert.id)
+ assert after[0].prompt == "The owner's words."
+ assert after[0].title == "Sweep the queue"
+
+
[email protected](loop_scope="session")
+async def test_a_roster_edit_refreshes_a_routine_offer_nobody_has_taken(
+ server: SpinTestServer, test_user
+):
+ """The other half of the same rule: an untouched, still-off proposal is an
+ offer, and refreshing an offer reaches people who hired last month."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ entry: seed.RosterEntry = {
+ **seed.ROSTER[0],
+ "name": template.name,
+ "routines": [
+ {
+ "key": "queue-sweep",
+ "title": "Sweep the queue, better worded",
+ "prompt": "The roster's improved words.",
+ "crons": ["H 6 * * *"],
+ "asks": ["Where is the queue?"],
+ "session_mode": "THREAD",
+ }
+ ],
+ }
+ await seed._sync_hired_routines(template.id, entry)
+
+ after = await experts_db.list_routines(test_user.id, hired.expert.id)
+ assert after[0].title == "Sweep the queue, better worded"
+ assert after[0].enabled is False
+
+
[email protected](loop_scope="session")
+async def test_an_expert_can_record_a_routine_it_agreed_in_conversation(
+ server: SpinTestServer, test_user
+):
+ """A raised expert has no template, so this is the only way it gets any
+ standing work at all."""
+ template = await _seed_template(name="Routineless", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ created = await experts_db.create_routine(
+ test_user.id,
+ hired.expert.id,
+ title="Morning triage",
+ prompt="Read overnight tickets and rank them.",
+ crons=["H 8 * * 1-5"],
+ session_mode="FRESH",
+ )
+
+ assert created.key is None
+ assert created.enabled is False
+ assert created.customized is True
+ assert created.session_mode == "FRESH"
+ # No third party in the prompt, so it is not muted like a template.
+ assert created.source == "OWNER"
+ assert created.grants_credentials is True
+ assert [
+ r.id for r in await experts_db.list_routines(test_user.id, hired.expert.id)
+ ] == [created.id]
+
+
[email protected](loop_scope="session")
+async def test_a_routine_belongs_to_its_owner_only(
+ server: SpinTestServer, test_user, other_user
+):
+ """The routine id is the only handle a caller needs, so it is the only
+ thing standing between somebody and another account's standing work."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+
+ with (
+ patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ),
+ pytest.raises(routines.RoutineNotFoundError),
+ ):
+ await experts_db.enable_routine(
+ other_user.id, hired.expert.id, installed[0].id, prompt="Mine now."
+ )
+ with pytest.raises(routines.RoutineNotFoundError):
+ await experts_db.create_routine(
+ other_user.id,
+ hired.expert.id,
+ title="Mine now",
+ prompt="Do my bidding.",
+ crons=["H 8 * * *"],
+ )
+ assert await experts_db.list_routines(other_user.id, hired.expert.id) == []
+
+
[email protected](loop_scope="session")
+async def test_archiving_stops_routines_and_re_hire_resumes_exactly_those(
+ server: SpinTestServer, test_user
+):
+ """Archiving has to stop a routine re-arming forever, and re-hire has to
+ bring back what archiving stopped — never one switched off on purpose."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+ scheduler = _fake_scheduler()
+ with patch.object(routine_jobs, "get_scheduler_client", return_value=scheduler):
+ running = await experts_db.enable_routine(
+ test_user.id, hired.expert.id, installed[0].id, prompt="Running."
+ )
+ off = await experts_db.create_routine(
+ test_user.id,
+ hired.expert.id,
+ title="Left off",
+ prompt="Off.",
+ crons=["H 7 * * *"],
+ )
+
+ with (
+ patch.object(routine_jobs, "get_scheduler_client", return_value=scheduler),
+ patch.object(scheduling, "get_scheduler_client", return_value=scheduler),
+ ):
+ await experts_db.archive_expert(test_user.id, hired.expert.id)
+ paused = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": hired.expert.id}
+ )
+ by_id = {row.id: row for row in paused}
+ assert by_id[running.id].pausedByExpertArchive is True
+ assert by_id[off.id].pausedByExpertArchive is False
+
+ with (
+ patch.object(routine_jobs, "get_scheduler_client", return_value=scheduler),
+ patch.object(scheduling, "get_scheduler_client", return_value=scheduler),
+ ):
+ await experts_db.hire_expert(test_user.id, template.id, None)
+ revived = {
+ row.id: row
+ for row in await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": hired.expert.id}
+ )
+ }
+ assert revived[running.id].pausedByExpertArchive is False
+ assert revived[running.id].enabledAt is not None
+ assert revived[off.id].enabledAt is None
+
+
[email protected](loop_scope="session")
+async def test_the_account_holds_routines_of_its_own(server: SpinTestServer, test_user):
+ """Otto is the platform's default assistant, not a row in ``Expert``, so
+ its standing work hangs off the owner. Without this the only way to defer
+ repeating work from an Otto chat was a follow-up pinned to whatever chat
+ the user happened to be in."""
+ created = await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Weekly calendar read",
+ prompt="Read the week ahead and flag the conflicts.",
+ crons=["H 8 * * 1"],
+ )
+
+ assert created.expert_id is None
+ assert created.source == "OWNER"
+ assert [r.id for r in await experts_db.list_routines(test_user.id)] == [created.id]
+
+
[email protected](loop_scope="session")
+async def test_an_accounts_routines_and_an_experts_do_not_leak_into_each_other(
+ server: SpinTestServer, test_user
+):
+ """``expertId IS NULL`` is load-bearing in the account query: without it,
+ asking Otto for its routines would answer with every expert's as well."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ mine = await experts_db.create_routine(
+ test_user.id, None, title="Mine", prompt="Mine.", crons=["H 8 * * 1"]
+ )
+
+ account = await experts_db.list_routines(test_user.id)
+ expert = await experts_db.list_routines(test_user.id, hired.expert.id)
+ assert [r.id for r in account] == [mine.id]
+ assert [r.key for r in expert] == ["queue-sweep"]
+
+
[email protected](loop_scope="session")
+async def test_an_account_routine_belongs_to_one_account_only(
+ server: SpinTestServer, test_user, other_user
+):
+ mine = await experts_db.create_routine(
+ test_user.id, None, title="Mine", prompt="Mine.", crons=["H 8 * * 1"]
+ )
+
+ assert await experts_db.list_routines(other_user.id) == []
+ with (
+ patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ),
+ pytest.raises(routines.RoutineNotFoundError),
+ ):
+ await experts_db.enable_routine(
+ other_user.id, None, mine.id, prompt="Mine now."
+ )
+
+
[email protected](loop_scope="session")
+async def test_a_one_shot_gets_a_row_and_exactly_one_job(
+ server: SpinTestServer, test_user
+):
+ """ "Check the deploy at six" is a row like anything else, so it can be
+ listed, reworded and cancelled — and later counted."""
+ run_at = datetime.now(timezone.utc) + timedelta(hours=2)
+ created = await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Check the deploy",
+ prompt="Check whether the deploy finished.",
+ run_at=run_at,
+ )
+ scheduler = _fake_scheduler()
+ with patch.object(routine_jobs, "get_scheduler_client", return_value=scheduler):
+ enabled = await experts_db.enable_routine(test_user.id, None, created.id)
+
+ assert enabled.crons == []
+ assert enabled.run_at is not None
+ assert enabled.enabled is True
+ assert len(scheduler.add_copilot_turn_schedule.await_args_list) == 1
+ call = scheduler.add_copilot_turn_schedule.await_args.kwargs
+ assert call["cron"] is None
+ assert call["run_at"] is not None
+ assert call["routine_id"] == created.id
+
+
[email protected](loop_scope="session")
+async def test_a_spent_one_shot_stops_reading_as_scheduled(
+ server: SpinTestServer, test_user
+):
+ """APScheduler drops the job once it fires. The row outlives it on purpose,
+ so something has to say it has run — otherwise it goes on describing itself
+ as scheduled for a time that has passed."""
+ created = await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Check the deploy",
+ prompt="Check it.",
+ run_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ )
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(test_user.id, None, created.id)
+
+ await experts_db.record_routine_fired(created.id)
+
+ after = await experts_db.list_routines(test_user.id)
+ assert after[0].enabled is False
+ assert after[0].run_at is not None
+
+
[email protected](loop_scope="session")
+async def test_firing_a_recurring_routine_does_not_spend_it(
+ server: SpinTestServer, test_user
+):
+ """A cadence's next run is the point of it; only a one-shot is spent."""
+ created = await experts_db.create_routine(
+ test_user.id, None, title="Weekly", prompt="Weekly.", crons=["H 8 * * 1"]
+ )
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(test_user.id, None, created.id)
+
+ await experts_db.record_routine_fired(created.id)
+
+ assert (await experts_db.list_routines(test_user.id))[0].enabled is True
+
+
[email protected](loop_scope="session")
+async def test_re_arming_a_one_shot_at_a_time_that_has_passed_is_refused(
+ server: SpinTestServer, test_user
+):
+ """Firing immediately and never firing are both plausible readings of a
+ past time, and neither is what the owner asked for."""
+ created = await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Check the deploy",
+ prompt="Check it.",
+ run_at=datetime.now(timezone.utc) + timedelta(hours=2),
+ )
+ with (
+ patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ),
+ pytest.raises(ValueError),
+ ):
+ await experts_db.enable_routine(
+ test_user.id,
+ None,
+ created.id,
+ run_at=datetime.now(timezone.utc) - timedelta(minutes=1),
+ )
+
+
[email protected](loop_scope="session")
+async def test_a_routine_runs_on_a_cadence_or_at_a_time_but_not_both(
+ server: SpinTestServer, test_user
+):
+ with pytest.raises(ValueError):
+ await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Both",
+ prompt="Both.",
+ crons=["H 8 * * 1"],
+ run_at=datetime.now(timezone.utc) + timedelta(hours=1),
+ )
+ with pytest.raises(ValueError):
+ await experts_db.create_routine(
+ test_user.id, None, title="Neither", prompt="Neither."
+ )
+
+
[email protected](loop_scope="session")
+async def test_losing_its_last_job_switches_a_routine_off(
+ server: SpinTestServer, test_user
+):
+ """The fire path removes a job whose chat is gone. A row left saying it is
+ on with nothing behind it is the one state the owner cannot act on: the UI
+ offers to switch off something that is already not running."""
+ created = await experts_db.create_routine(
+ test_user.id,
+ None,
+ title="Pinned somewhere deleted",
+ prompt="Read it.",
+ crons=["H 8 * * 1", "H 13 * * 1"],
+ )
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(test_user.id, None, created.id)
+ row = await prisma.models.ExpertRoutine.prisma().find_unique(
+ where={"id": created.id}
+ )
+ assert row is not None
+ first, second = row.scheduleIds
+
+ await experts_db.mark_routine_unscheduled(created.id, first)
+ # One fire time lost out of two is still a running routine.
+ assert (await experts_db.list_routines(test_user.id))[0].enabled is True
+
+ await experts_db.mark_routine_unscheduled(created.id, second)
+ after = await experts_db.list_routines(test_user.id)
+ assert after[0].enabled is False
+ assert (
+ await prisma.models.ExpertRoutine.prisma().find_unique(where={"id": created.id})
+ ).scheduleIds == []
+
+
[email protected](loop_scope="session")
+async def test_an_unknown_schedule_id_leaves_the_routine_alone(
+ server: SpinTestServer, test_user
+):
+ """The cleanup is keyed on a job the row actually holds, so a stale or
+ replayed call cannot switch off a routine that is running fine."""
+ created = await experts_db.create_routine(
+ test_user.id, None, title="Fine", prompt="Fine.", crons=["H 8 * * 1"]
+ )
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(test_user.id, None, created.id)
+
+ await experts_db.mark_routine_unscheduled(created.id, "some-other-job")
+
+ assert (await experts_db.list_routines(test_user.id))[0].enabled is True
+
+
[email protected](loop_scope="session")
+async def test_changing_a_running_routines_cadence_retires_the_old_jobs(
+ server: SpinTestServer, test_user
+):
+ """Editing in place is the point of the row — the routine keeps its thread
+ and its history. But the jobs behind it are replaced, and an old one left
+ armed would go on firing the cadence the owner just changed away from,
+ forever, with the row insisting it runs at the new time."""
+ created = await experts_db.create_routine(
+ test_user.id, None, title="Morning", prompt="Read it.", crons=["H 8 * * 1"]
+ )
+ scheduler = _fake_scheduler()
+ with patch.object(routine_jobs, "get_scheduler_client", return_value=scheduler):
+ await experts_db.enable_routine(test_user.id, None, created.id)
+ first = (
+ await prisma.models.ExpertRoutine.prisma().find_unique(
+ where={"id": created.id}
+ )
+ ).scheduleIds
+ await experts_db.enable_routine(
+ test_user.id, None, created.id, crons=["H 17 * * 5"]
+ )
+
+ deleted = {c.args[0] for c in scheduler.delete_schedule.await_args_list}
+ assert set(first) <= deleted
+ after = await prisma.models.ExpertRoutine.prisma().find_unique(
+ where={"id": created.id}
+ )
+ assert after is not None
+ assert not set(after.scheduleIds) & set(first)
+ assert after.crons[0].endswith(" 17 * * 5")
+
+
[email protected](loop_scope="session")
+async def test_a_routine_switched_off_can_be_switched_back_on(
+ server: SpinTestServer, test_user
+):
+ """The asks are answered once and the answers live in the row. Reading only
+ the current call meant a routine that was set up, run, and switched off
+ could never run again: its questions are still listed, and there is no way
+ to answer them a second time."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ await experts_db.enable_routine(
+ test_user.id,
+ hired.expert.id,
+ installed[0].id,
+ prompt="Read the support queue.",
+ )
+ await experts_db.disable_routine(test_user.id, hired.expert.id, installed[0].id)
+ again = await experts_db.enable_routine(
+ test_user.id, hired.expert.id, installed[0].id
+ )
+
+ assert again.enabled is True
+ # And it comes back as what the owner set up, not as the template's draft.
+ assert again.prompt == "Read the support queue."
+
+
[email protected](loop_scope="session")
+async def test_a_routine_proposal_nobody_answered_still_refuses(
+ server: SpinTestServer, test_user
+):
+ """The other half: relaxing the check must not let an untouched template
+ routine schedule itself against guesses."""
+ template = await _template_with_routine()
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ installed = await experts_db.list_routines(test_user.id, hired.expert.id)
+
+ with pytest.raises(routines.RoutineUnansweredAsksError):
+ await experts_db.enable_routine(test_user.id, hired.expert.id, installed[0].id)
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index 5533b761ff..0080be4f52 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -197,6 +197,46 @@ _DAY_ONE_ITEMS: TypeAdapter[list[ExpertDayOneItem]] = TypeAdapter(
)
+class ExpertRoutine(BaseModel):
+ """Standing work done unattended, as the API and the fire path see it.
+
+ A template's row is a proposal; a hire's row is that proposal until
+ somebody switches it on. A row the owner dictated is neither — it is
+ already theirs.
+ """
+
+ id: str
+ # None when this is the account's own standing work rather than an
+ # expert's: Otto is the default assistant, not a row in Expert.
+ expert_id: str | None = None
+ # Roster/shared slug; None when this one was authored in conversation.
+ key: str | None = None
+ title: str
+ prompt: str
+ # Exactly one of ``crons`` and ``run_at`` is set.
+ crons: list[str] = []
+ run_at: datetime | None = None
+ # What must be asked before this can run. Non-empty on a proposal nobody
+ # has answered yet, and answering them is what makes it runnable.
+ asks: list[str] = []
+ session_mode: str = "THREAD"
+ session_id: str | None = None
+ # "TEMPLATE" (someone else wrote the prompt) or "OWNER" (the owner did).
+ # What the fire-time turn may reach hangs off this.
+ source: str = "TEMPLATE"
+ enabled: bool = False
+ # True once the owner resolved the proposal, after which no roster edit
+ # touches this row again.
+ customized: bool = False
+ # Whether this routine's turns may reach the owner's connected services.
+ # Always False on anything a template shipped.
+ grants_credentials: bool = False
+
+ @property
+ def recurring(self) -> bool:
+ return bool(self.crons)
+
+
class Expert(BaseModel):
id: str
name: str
diff --git a/autogpt_platform/backend/backend/api/features/experts/routine_jobs.py b/autogpt_platform/backend/backend/api/features/experts/routine_jobs.py
new file mode 100644
index 0000000000..6df9f5f3b1
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/experts/routine_jobs.py
@@ -0,0 +1,249 @@
+"""The scheduler side of a routine: its jobs, and what a firing turn writes back.
+
+Split from ``routines``, which owns the record and what its owner does to it.
+Everything here is the other half — one APScheduler job per fire time, the
+Jenkins-style ``H`` minute resolved before anything reaches a trigger, and the
+handful of writes a running job makes to the row behind it (the thread it
+minted, the one-shot it spent, the job it lost).
+"""
+
+import hashlib
+import logging
+from datetime import datetime, timezone
+
+import prisma.models
+import prisma.types
+
+from backend.util.clients import get_scheduler_client
+
+logger = logging.getLogger(__name__)
+
+# Jenkins's spelling for "some minute inside this hour, consistently" —
+# a thing plain cron has no syntax for. Resolved to a real minute at
+# install time by ``spread_cron``; never persisted or handed to APScheduler.
+_SPREAD_MINUTE = "H"
+
+
+async def pause_routines_for_archive(user_id: str, expert_id: str) -> None:
+ """Stop an archived expert's routines from waking the scheduler forever.
+
+ The fire path already refuses an archived expert, but a recurring job that
+ is merely refused keeps its next run time, so it re-arms on every tick and
+ stays listed as a scheduled chat for an expert the owner has let go.
+
+ Only routines this call actually pauses are marked, so reviving restores
+ exactly them — one the owner had switched off themselves must not come
+ back running.
+ """
+ scheduler = get_scheduler_client()
+ for row in await _enabled_routines(expert_id):
+ paused_any = False
+ for schedule_id in row.scheduleIds:
+ try:
+ paused_any |= await scheduler.pause_schedule(
+ schedule_id, user_id=user_id
+ )
+ except Exception as e:
+ logger.warning(
+ f"Failed to pause routine schedule #{schedule_id} while "
+ f"detaching expert #{expert_id}: {type(e).__name__}: {e}"
+ )
+ if paused_any:
+ await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": row.id}, data={"pausedByExpertArchive": True}
+ )
+
+
+async def resume_routines_after_revive(user_id: str, expert_id: str) -> None:
+ """Reverse of ``pause_routines_for_archive``, for re-hire.
+
+ Scoped to rows archiving paused. APScheduler recomputes the next fire from
+ the trigger, so a long-archived expert picks up at her next cadence instead
+ of replaying every run she missed.
+ """
+ scheduler = get_scheduler_client()
+ rows = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": expert_id, "pausedByExpertArchive": True}
+ )
+ for row in rows:
+ resumed_all = True
+ for schedule_id in row.scheduleIds:
+ try:
+ await scheduler.resume_schedule(schedule_id, user_id=user_id)
+ except Exception as e:
+ resumed_all = False
+ logger.warning(
+ f"Failed to resume routine schedule #{schedule_id} while "
+ f"reviving expert #{expert_id}: {type(e).__name__}: {e}"
+ )
+ if not resumed_all:
+ # The marker is the only record that archiving is what stopped
+ # these. Clearing it after a failed resume strands the schedule
+ # paused with nothing left to say it should not be — and the next
+ # re-hire, which is the natural retry, would skip the row.
+ continue
+ await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": row.id}, data={"pausedByExpertArchive": False}
+ )
+
+
+async def record_routine_thread(routine_id: str, session_id: str) -> None:
+ """Remember the thread a THREAD routine minted on its first fire.
+
+ Guarded so the first fire to get there wins: two ticks racing must not
+ leave the routine pointing at a thread the other one is writing to.
+ """
+ await prisma.models.ExpertRoutine.prisma().update_many(
+ where={"id": routine_id, "sessionId": None},
+ data={"sessionId": session_id},
+ )
+
+
+async def record_routine_fired(routine_id: str) -> None:
+ """Mark a one-shot spent, once its turn has been dispatched.
+
+ APScheduler drops the job itself, so without this the row would keep
+ saying it is scheduled for a time that has passed. Recurring routines are
+ left alone: their next run is the point of them.
+ """
+ await prisma.models.ExpertRoutine.prisma().update_many(
+ where={"id": routine_id, "firedAt": None, "NOT": [{"runAt": None}]},
+ data={"firedAt": datetime.now(timezone.utc)},
+ )
+
+
+async def mark_routine_unscheduled(routine_id: str, schedule_id: str) -> None:
+ """Drop a job the fire path removed, and switch the routine off if it was
+ the last one.
+
+ The scheduler self-deletes a job whose target chat is gone or whose scope
+ no longer matches. Without this the row keeps saying it is on while nothing
+ behind it can fire — a state the owner cannot act on, because switching it
+ off is the only thing offered and it is already off in every sense that
+ matters.
+
+ Left enabled when other jobs survive: a routine that fires at 08:30 and
+ 13:00 and lost one of them is still running, and a reader has the remaining
+ ``scheduleIds`` to say so.
+ """
+ row = await prisma.models.ExpertRoutine.prisma().find_unique(
+ where={"id": routine_id}
+ )
+ if row is None or schedule_id not in row.scheduleIds:
+ return
+ remaining = [sid for sid in row.scheduleIds if sid != schedule_id]
+ data: prisma.types.ExpertRoutineUpdateInput = {"scheduleIds": remaining}
+ if not remaining:
+ data["enabledAt"] = None
+ await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": routine_id}, data=data
+ )
+
+
+def spread_cron(cron: str, *, seed: str) -> str:
+ """Resolve a Jenkins-style ``H`` minute to a concrete one.
+
+ Five different experts all want "Monday at 9". Someone who hires three of
+ them has three routines waking in the same minute, against a cap on how many
+ chat turns can run at once — and the ones that miss out do not fail loudly,
+ they simply never happen, so the owner's Monday briefing is just absent with
+ nothing on screen to explain it.
+
+ Plain cron cannot express "some minute in this hour": ``*`` means all sixty.
+ So a roster cron says ``H 9 * * 1`` — borrowing Jenkins's ``H`` — and this
+ picks the minute from who the owner is and which routine it is. The same
+ routine for the same person lands on the same minute every week, and two
+ accounts' morning sweeps almost never share one.
+
+ It spreads; it does not guarantee. A digest byte modulo 60 collides about
+ once in sixty for any given pair, so two of one owner's routines can still
+ land together — this turns a certainty into a small chance, which for five
+ personas that all literally say "9am" is the whole of the win. Making it a
+ guarantee needs allocation against what the owner already has, and the
+ firing that loses a collision needs queueing rather than dropping; both are
+ worth doing and neither is this function.
+
+ Only ``H`` is resolved. A cron that names a minute means that minute, from a
+ roster author who wrote 07:40 on purpose as much as from an owner who asked
+ for 10am — the implicit version of this used to move both.
+ """
+ fields = cron.split()
+ if len(fields) != 5 or fields[0] != _SPREAD_MINUTE:
+ return cron
+ # hashlib, not hash(): Python salts the builtin per process, which would
+ # give the same routine a different minute after every deploy.
+ digest = hashlib.sha256(seed.encode()).digest()
+ fields[0] = str(digest[0] % 60)
+ return " ".join(fields)
+
+
+async def create_routine_schedules(
+ *,
+ user_id: str,
+ expert_id: str | None,
+ row: prisma.models.ExpertRoutine,
+ prompt: str,
+ crons: list[str],
+ run_at: datetime | None,
+ session_id: str | None,
+ user_timezone: str,
+) -> list[str]:
+ scheduler = get_scheduler_client()
+ created: list[str] = []
+ # A one-shot is one job with no cron; a cadence is one job per cron. Both
+ # carry ``routine_id``, which is what tells the fire path there is a row
+ # behind this turn deciding where it lands and how far it can reach.
+ plan: list[tuple[str | None, datetime | None]] = (
+ [(None, run_at)] if run_at is not None else [(cron, None) for cron in crons]
+ )
+ try:
+ for cron, at in plan:
+ info = await scheduler.add_copilot_turn_schedule(
+ user_id=user_id,
+ session_id=session_id,
+ message=prompt,
+ cron=cron,
+ run_at=at,
+ name=row.title,
+ user_timezone=user_timezone,
+ expert_id=expert_id,
+ routine_id=row.id,
+ )
+ created.append(info.id)
+ except Exception:
+ # All or nothing: a routine that fires at 08:30 but not at 13:00 is a
+ # quieter lie than one that does not fire at all.
+ for schedule_id in created:
+ try:
+ await scheduler.delete_schedule(schedule_id, user_id=user_id)
+ except Exception as e:
+ logger.warning(
+ f"Leaked routine schedule #{schedule_id} for routine "
+ f"#{row.id} after a failed enable: {type(e).__name__}: {e}"
+ )
+ raise
+ return created
+
+
+async def delete_routine_schedules(
+ user_id: str, row: prisma.models.ExpertRoutine
+) -> None:
+ scheduler = get_scheduler_client()
+ for schedule_id in row.scheduleIds:
+ try:
+ await scheduler.delete_schedule(schedule_id, user_id=user_id)
+ except Exception as e:
+ # Best effort, like the preload path. A job we cannot delete
+ # fires into a row that has already moved on — switched off, or
+ # switched to a new cadence — and the fire-time lookup is what
+ # reconciles it.
+ logger.warning(
+ f"Could not delete routine schedule #{schedule_id}: "
+ f"{type(e).__name__}: {e}"
+ )
+
+
+async def _enabled_routines(expert_id: str) -> list[prisma.models.ExpertRoutine]:
+ return await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": expert_id, "NOT": [{"enabledAt": None}], "firedAt": None}
+ )
diff --git a/autogpt_platform/backend/backend/api/features/experts/routines.py b/autogpt_platform/backend/backend/api/features/experts/routines.py
new file mode 100644
index 0000000000..c2def226b1
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/experts/routines.py
@@ -0,0 +1,454 @@
+"""Standing work done unattended: the lifecycle of ExpertRoutine.
+
+A routine is a prompt on a cadence that fires as a copilot turn.
+``schedule_followup`` is the primitive underneath; this module owns the durable
+record around it — the cadence, the thread, how far it may reach, and whether
+it is switched on. An expert owns routines, and so does the account itself:
+Otto is the platform's default assistant rather than a row in ``Expert``, so
+its standing work hangs off the owner directly.
+
+Four rules run through everything here:
+
+* **A seeded routine arrives off.** Hiring copies the template's proposals with
+ no scheduler job at all, so a routine nobody asked for costs nothing and
+ fires nothing. Off is the absence of a job, not a paused one.
+* **A seeded routine reaches nothing.** Until its owner says otherwise, a
+ ``TEMPLATE`` routine's fire-time turn is refused every tool that carries a
+ credential outward, so it can read, think, and write to its own thread and no
+ further. That is the rule ``PreloadSeed.cron`` states for preloads, made
+ enforceable.
+* **An owner's own routine is not a template.** A routine dictated in the
+ owner's chat has no third party in its prompt, so it runs with the reach
+ ``schedule_followup`` has always had. Muting it would buy nothing: the same
+ words typed into the same chat already run unmuted.
+* **Switching one on resolves it.** The template ships a proposal; the owner's
+ answers become the prompt and the cadence that actually run, and from then on
+ the row is theirs.
+
+The scheduler side — the jobs themselves, the ``H`` minute, and the writes a
+firing turn makes back to the row — lives in ``routine_jobs``.
+"""
+
+import logging
+from datetime import datetime, timezone
+
+import prisma.enums
+import prisma.models
+import prisma.types
+from apscheduler.triggers.cron import CronTrigger
+
+from backend.api.features.experts.models import ExpertRoutine
+from backend.api.features.experts.routine_jobs import (
+ create_routine_schedules,
+ delete_routine_schedules,
+ spread_cron,
+)
+from backend.data.user import get_user_by_id
+from backend.util.clients import get_scheduler_client
+from backend.util.timezone_utils import get_user_timezone_or_utc
+
+logger = logging.getLogger(__name__)
+
+
+def to_model(row: prisma.models.ExpertRoutine) -> ExpertRoutine:
+ return ExpertRoutine(
+ id=row.id,
+ expert_id=row.expertId,
+ key=row.key,
+ title=row.title,
+ prompt=row.prompt,
+ crons=row.crons,
+ run_at=row.runAt,
+ asks=row.asks,
+ # ``str``, not ``.value``: the generated type says StrEnum but Prisma
+ # hydrates a row with a plain string, so ``.value`` type-checks and then
+ # raises. StrEnum subclasses str, so this is right for both.
+ session_mode=str(row.sessionMode),
+ session_id=row.sessionId,
+ source=str(row.source),
+ # A spent one-shot is not on. Its row outlives its job so it can still
+ # be listed and counted, and without this it would keep describing
+ # itself as scheduled long after the only thing it did was happen.
+ enabled=row.enabledAt is not None and row.firedAt is None,
+ customized=row.customizedAt is not None,
+ grants_credentials=row.grantsCredentials,
+ )
+
+
+async def get_routine(routine_id: str) -> ExpertRoutine | None:
+ """Load one routine by id, for the fire path.
+
+ Unscoped by owner on purpose: the caller is the scheduler dispatching a job
+ it already persisted, and the job's own ``user_id`` is what every ownership
+ check downstream runs against. Every user-facing path goes through
+ ``_owned_routine`` instead.
+ """
+ row = await prisma.models.ExpertRoutine.prisma().find_unique(
+ where={"id": routine_id}
+ )
+ return to_model(row) if row is not None else None
+
+
+class RoutineNotFoundError(Exception):
+ """No such routine on this owner."""
+
+
+class RoutineUnansweredAsksError(Exception):
+ """The routine still has questions nobody answered.
+
+ A seeded proposal names what it needs to know — which repo, which inbox,
+ what hour. Scheduling it before those are answered would run it against
+ guesses on somebody's account, every day, unattended.
+ """
+
+
+async def install_routines(
+ expert_id: str, template_routines: list[prisma.models.ExpertRoutine]
+) -> None:
+ """Copy a template's routine proposals onto a new hire, all switched off.
+
+ Deliberately creates no scheduler jobs: a cadence that fires unattended
+ from the day of hire is a much bigger promise than a skill, and nobody has
+ made it yet. The rows exist so the expert can offer them on its first turn.
+ """
+ for routine in template_routines:
+ data: prisma.types.ExpertRoutineCreateInput = {
+ "expertId": expert_id,
+ "key": routine.key,
+ "title": routine.title,
+ "prompt": routine.prompt,
+ "crons": routine.crons,
+ "asks": routine.asks,
+ "sessionMode": routine.sessionMode,
+ # Spelled out rather than left to the column default: this is the
+ # line that decides a hired routine reaches nothing, and a default
+ # is a thing somebody edits without reading what it was holding up.
+ "source": prisma.enums.ExpertRoutineSource.TEMPLATE,
+ }
+ try:
+ await prisma.models.ExpertRoutine.prisma().create(data=data)
+ except Exception:
+ # Honest partial hire, same as a failed preload: the expert is
+ # still worth having without one of its offers.
+ logger.exception(
+ f"Failed to install routine {routine.key!r} on expert #{expert_id}"
+ )
+
+
+async def list_routines(
+ user_id: str, expert_id: str | None = None
+) -> list[ExpertRoutine]:
+ """One owner's routines: an expert's, or the account's own when *expert_id*
+ is None."""
+ rows = await prisma.models.ExpertRoutine.prisma().find_many(
+ where=_owner_where(user_id, expert_id),
+ order=[{"createdAt": "asc"}, {"id": "asc"}],
+ )
+ return [to_model(row) for row in rows]
+
+
+async def enable_routine(
+ user_id: str,
+ expert_id: str | None,
+ routine_id: str,
+ *,
+ prompt: str | None = None,
+ crons: list[str] | None = None,
+ run_at: datetime | None = None,
+ session_mode: str | None = None,
+ pinned_session_id: str | None = None,
+ grants_credentials: bool | None = None,
+) -> ExpertRoutine:
+ """Switch a routine on, resolving the proposal into what actually runs.
+
+ *prompt*, *crons* and *run_at* are the owner's answers. Passing any of them
+ marks the row customized, which takes it out of reach of every later roster
+ edit — from here on what this routine does is the owner's, not the
+ template's.
+
+ *session_mode* rewrites the row, not just its ``sessionId``: a row whose
+ mode still read THREAD while its id pointed at a real chat fired correctly
+ by luck and described itself wrongly everywhere else — in the tool's
+ confirmation, in the context block, and in any UI reading the row.
+
+ Creates one scheduler job per cron, or exactly one for a ``run_at``. A
+ partial failure leaves nothing behind: a routine that fires at 08:30 but
+ not at 13:00 is a quieter lie than one that does not fire at all.
+ """
+ row = await _owned_routine(user_id, expert_id, routine_id)
+ resolved_prompt = prompt or row.prompt
+ customized = prompt is not None or crons is not None or run_at is not None
+ # ``customizedAt``, not just this call: the asks are answered once, and the
+ # answers live in the row from then on. Reading only the current call meant
+ # a routine that was set up, run, and switched off could never be switched
+ # back on — its questions are still listed, and the owner has no way to
+ # answer them a second time.
+ if row.asks and not customized and row.customizedAt is None:
+ raise RoutineUnansweredAsksError(
+ f"'{row.title}' needs answers before it can run: " + "; ".join(row.asks)
+ )
+
+ user = await get_user_by_id(user_id)
+ user_timezone = get_user_timezone_or_utc(user.timezone if user else None)
+
+ # Naming either one switches the routine to that shape, so an owner can
+ # turn "every morning" into "once, tomorrow" without deleting anything.
+ # Naming neither keeps whatever the row already holds.
+ if crons is not None and run_at is not None:
+ raise ValueError("Give a cadence or a single time, not both.")
+ if crons is not None:
+ source_crons, resolved_run_at = crons, None
+ elif run_at is not None:
+ source_crons, resolved_run_at = [], run_at
+ else:
+ source_crons, resolved_run_at = list(row.crons), row.runAt
+
+ # Resolved on every path, so an ``H`` that reaches here from the template
+ # or straight back from the model never gets as far as APScheduler, which
+ # has no idea what it means.
+ resolved_crons = [
+ spread_cron(cron, seed=f"{user_id}:{row.key or row.id}:{index}")
+ for index, cron in enumerate(source_crons)
+ ]
+ if bool(resolved_crons) == (resolved_run_at is not None):
+ raise ValueError(
+ "A routine runs either on a cadence or once at a time, not both "
+ "and not neither."
+ )
+ for cron in resolved_crons:
+ CronTrigger.from_crontab(cron, timezone=user_timezone)
+ # A spent one-shot switched on again needs a new time: re-arming it at the
+ # old one would either fire immediately or never, and neither is a thing
+ # the owner asked for.
+ if resolved_run_at is not None and resolved_run_at <= datetime.now(timezone.utc):
+ raise ValueError("That time has already passed; give a future one.")
+
+ mode = _session_mode(session_mode or str(row.sessionMode))
+ # Only PINNED names a session up front. THREAD leaves it null for the first
+ # fire to mint; FRESH leaves it null for good.
+ pinned = (
+ (pinned_session_id or row.sessionId)
+ if mode == prisma.enums.ExpertRoutineSession.PINNED
+ else None
+ )
+ if mode == prisma.enums.ExpertRoutineSession.PINNED and not pinned:
+ # The scheduler reads a null session as "fire into a fresh chat", so
+ # without this the row would say PINNED and behave like FRESH. The tool
+ # always supplies one; this closes the RPC path, which does not.
+ raise ValueError("A PINNED routine needs the chat it should fire into.")
+ schedule_ids = await create_routine_schedules(
+ user_id=user_id,
+ expert_id=expert_id,
+ row=row,
+ prompt=resolved_prompt,
+ crons=resolved_crons,
+ run_at=resolved_run_at,
+ session_id=pinned,
+ user_timezone=user_timezone,
+ )
+ now = datetime.now(timezone.utc)
+ data: prisma.types.ExpertRoutineUpdateInput = {
+ "prompt": resolved_prompt,
+ "crons": resolved_crons,
+ "runAt": resolved_run_at,
+ "scheduleIds": schedule_ids,
+ "sessionMode": mode,
+ "sessionId": pinned,
+ "enabledAt": now,
+ # Re-arming a spent one-shot makes it pending again; leaving the old
+ # stamp would enable a row that still reads as already run.
+ "firedAt": None,
+ }
+ # ``None`` means "leave the grant as it is", which is what an owner
+ # adjusting a cadence expects. Only an explicit answer moves it, in either
+ # direction, so a rewording never quietly widens what a routine can touch.
+ if grants_credentials is not None:
+ data["grantsCredentials"] = grants_credentials
+ if customized:
+ data["customizedAt"] = now
+ try:
+ updated = await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": row.id}, data=data
+ )
+ except Exception:
+ # The jobs exist and nothing records them, so they would fire forever
+ # with no row able to name or remove them. Undo them and leave the
+ # caller in the state they started in.
+ await _drop_schedules(user_id, schedule_ids)
+ raise
+ if updated is None:
+ await _drop_schedules(user_id, schedule_ids)
+ raise RoutineNotFoundError(routine_id)
+ # Switching on a routine that was already on is how a cadence gets changed,
+ # and its old jobs are still armed. Cleared last, and only once the row
+ # names the new ones: a failure here leaves an extra run to explain, while
+ # clearing first would leave a routine that says it is running and is not.
+ await delete_routine_schedules(user_id, row)
+ return to_model(updated)
+
+
+def _session_mode(value: str) -> prisma.enums.ExpertRoutineSession:
+ """Parse a mode name, defaulting to THREAD rather than raising.
+
+ The value arrives as a model argument, and a typo should give the routine
+ its own thread — the safe, memory-keeping default — rather than fail a call
+ the owner has already agreed to.
+ """
+ try:
+ return prisma.enums.ExpertRoutineSession(value.upper())
+ except ValueError:
+ logger.warning("Unknown routine session mode %r; using THREAD", value)
+ return prisma.enums.ExpertRoutineSession.THREAD
+
+
+async def create_routine(
+ user_id: str,
+ expert_id: str | None,
+ *,
+ title: str,
+ prompt: str,
+ crons: list[str] | None = None,
+ run_at: datetime | None = None,
+ session_mode: str | None = None,
+ session_id: str | None = None,
+ grants_credentials: bool = True,
+) -> ExpertRoutine:
+ """Record standing work worked out with the owner in conversation.
+
+ ``key`` stays null: this came from a conversation rather than a roster, so
+ nothing syncs it and no roster edit can ever reach it. It is created OFF for
+ the same reason a seeded one is — agreeing what a routine should say is not
+ agreeing that it should start running, and enabling is a second step the
+ owner can still stop.
+
+ ``customizedAt`` is stamped at birth: there was no proposal to resolve, so
+ the row is the owner's from its first moment. ``source`` is OWNER for the
+ same reason, and that is what lets it run with the reach an ordinary
+ follow-up has: the prompt is the owner's own words, typed into their own
+ chat. *grants_credentials* still defaults true rather than being assumed,
+ so an owner who wants a routine that only reads and drafts can say so.
+ """
+ await _owned_owner(user_id, expert_id)
+ if not title.strip() or not prompt.strip():
+ raise ValueError("A routine needs a title and a prompt.")
+ if bool(crons) == (run_at is not None):
+ raise ValueError(
+ "A routine runs either on a cadence or once at a time, not both "
+ "and not neither."
+ )
+ if run_at is not None and run_at <= datetime.now(timezone.utc):
+ raise ValueError("That time has already passed; give a future one.")
+ mode = _session_mode(session_mode or "THREAD")
+ data: prisma.types.ExpertRoutineCreateInput = {
+ "title": title.strip(),
+ "prompt": prompt.strip(),
+ "crons": crons or [],
+ "runAt": run_at,
+ "sessionMode": mode,
+ "sessionId": (
+ session_id if mode == prisma.enums.ExpertRoutineSession.PINNED else None
+ ),
+ "source": prisma.enums.ExpertRoutineSource.OWNER,
+ "grantsCredentials": grants_credentials,
+ "customizedAt": datetime.now(timezone.utc),
+ }
+ if expert_id is None:
+ data["userId"] = user_id
+ else:
+ data["expertId"] = expert_id
+ created = await prisma.models.ExpertRoutine.prisma().create(data=data)
+ return to_model(created)
+
+
+async def disable_routine(
+ user_id: str, expert_id: str | None, routine_id: str
+) -> ExpertRoutine:
+ """Switch a routine off, deleting its jobs but keeping the row.
+
+ The resolved prompt and cadence survive, so switching it back on later
+ restores what the owner set up rather than reverting to the proposal.
+ """
+ row = await _owned_routine(user_id, expert_id, routine_id)
+ await delete_routine_schedules(user_id, row)
+ updated = await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": row.id},
+ data={
+ "scheduleIds": [],
+ "enabledAt": None,
+ "pausedByExpertArchive": False,
+ },
+ )
+ if updated is None:
+ raise RoutineNotFoundError(routine_id)
+ return to_model(updated)
+
+
+async def _drop_schedules(user_id: str, schedule_ids: list[str]) -> None:
+ """Remove jobs that were created for a row write that never landed."""
+ scheduler = get_scheduler_client()
+ for schedule_id in schedule_ids:
+ try:
+ await scheduler.delete_schedule(schedule_id, user_id=user_id)
+ except Exception as e:
+ logger.warning(
+ f"Leaked routine schedule #{schedule_id} after a failed "
+ f"enable write: {type(e).__name__}: {e}"
+ )
+
+
+def _owner_where(
+ user_id: str, expert_id: str | None
+) -> prisma.types.ExpertRoutineWhereInput:
+ """The one place that says what "yours" means for a routine.
+
+ An expert's routines are reached through the expert, so the owner check is
+ the join and an archived or template expert has none. The account's own are
+ reached directly, and ``expertId: None`` is load-bearing: without it this
+ would also match every routine belonging to every expert the user owns.
+ """
+ if expert_id is None:
+ return {"userId": user_id, "expertId": None}
+ return {
+ "expertId": expert_id,
+ "Expert": {
+ "is": {
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ }
+ },
+ }
+
+
+async def _owned_owner(user_id: str, expert_id: str | None) -> None:
+ """The ownership check ``_owned_routine`` gets for free from its where
+ clause, for the create path that has no routine to look up yet.
+
+ The account is always its own owner, so only the expert case can fail.
+ """
+ if expert_id is None:
+ return
+ expert = await prisma.models.Expert.prisma().find_first(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ }
+ )
+ if expert is None:
+ raise RoutineNotFoundError(expert_id)
+
+
+async def _owned_routine(
+ user_id: str, expert_id: str | None, routine_id: str
+) -> prisma.models.ExpertRoutine:
+ row = await prisma.models.ExpertRoutine.prisma().find_first(
+ # Scoped rather than trusting the caller's ids: this is the only
+ # ownership check between a routine id and somebody else's standing
+ # work.
+ where={"id": routine_id, **_owner_where(user_id, expert_id)}
+ )
+ if row is None:
+ raise RoutineNotFoundError(routine_id)
+ return row
diff --git a/autogpt_platform/backend/backend/api/features/experts/routines_test.py b/autogpt_platform/backend/backend/api/features/experts/routines_test.py
new file mode 100644
index 0000000000..952d0b60a9
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/experts/routines_test.py
@@ -0,0 +1,221 @@
+"""Tests for expert routines: the roster invariants and the cadence spread.
+
+The DB-backed lifecycle (install, enable, disable, archive) is covered in
+``experts_db_test``; what lives here is everything checkable without one —
+which is deliberately where the safety rules sit, so a roster edit that would
+ship unattended standing work fails in a fast test rather than on someone's
+account.
+"""
+
+from apscheduler.triggers.cron import CronTrigger
+
+from backend.api.features.experts import seed
+from backend.api.features.experts.routine_jobs import spread_cron
+from backend.api.features.experts.routines import _session_mode
+from backend.copilot.permissions import (
+ CAPABILITY_GATE_NAMES,
+ ROUTINE_SELF_ESCALATION_TOOLS,
+ routine_disabled_tools,
+)
+from backend.copilot.tools import TOOL_REGISTRY
+
+# Every routine the roster ships, as (expert, key). A routine fires unattended
+# once its owner switches it on, and what it says is written by whoever wrote
+# the roster entry — so adding one is a deliberate edit to this set, never a
+# silent roster change.
+EXPECTED_ROSTER_ROUTINES: set[tuple[str, str]] = {
+ ("Maria", "content-pipeline-check"),
+ ("Jules", "repurposing-queue-check"),
+ ("Nadia", "competitor-brief"),
+ ("Remy", "lifecycle-performance-read"),
+ ("Max", "weekday-prospecting-batch"),
+ ("Max", "monday-list-top-up"),
+ ("Max", "friday-pipeline-recap"),
+ ("Frankie", "day-ahead-brief"),
+ ("Frankie", "week-ahead-review"),
+}
+
+VALID_SESSION_MODES = {"FRESH", "PINNED", "THREAD"}
+
+
+def test_roster_routines_are_declared():
+ assert {
+ (entry["name"], routine["key"])
+ for entry in seed.ROSTER
+ for routine in entry["routines"]
+ } == EXPECTED_ROSTER_ROUTINES
+
+
+def test_roster_routine_keys_are_unique_per_expert():
+ """``ExpertRoutine`` is unique on (expertId, key), so a duplicate key would
+ make the second row silently overwrite the first at seed time."""
+ for entry in seed.ROSTER:
+ keys = [routine["key"] for routine in entry["routines"]]
+ assert len(keys) == len(set(keys)), entry["name"]
+
+
+def test_roster_routines_ship_a_cadence_and_a_valid_mode():
+ for entry in seed.ROSTER:
+ for routine in entry["routines"]:
+ assert routine["crons"], (entry["name"], routine["key"])
+ assert routine["session_mode"] in VALID_SESSION_MODES, (
+ entry["name"],
+ routine["key"],
+ )
+
+
+def test_roster_routine_crons_resolve_to_something_apscheduler_accepts():
+ """A malformed cron — or an ``H`` nobody resolved — would only surface when
+ somebody switched the routine on, which is the worst place to find out."""
+ for entry in seed.ROSTER:
+ for routine in entry["routines"]:
+ for index, cron in enumerate(routine["crons"]):
+ assert len(cron.split()) == 5, (entry["name"], routine["key"], cron)
+ resolved = spread_cron(cron, seed=f"u:{routine['key']}:{index}")
+ CronTrigger.from_crontab(resolved, timezone="UTC")
+
+
+def test_roster_routines_spread_their_hour():
+ """Every one of these is "at its scheduled hour" from its source package, so
+ the minute is an artefact of writing it on the hour. Left literal, the five
+ that say 9am would land on one account together."""
+ for entry in seed.ROSTER:
+ for routine in entry["routines"]:
+ for cron in routine["crons"]:
+ assert cron.startswith("H "), (entry["name"], routine["key"], cron)
+
+
+def test_spread_moves_a_fixed_minute_within_its_hour():
+ spread = spread_cron("H 9 * * 1", seed="user-a:morning-sweep:0")
+ minute, hour, dom, month, dow = spread.split()
+ assert (hour, dom, month, dow) == ("9", "*", "*", "1")
+ assert 0 <= int(minute) < 60
+
+
+def test_spread_is_stable_for_the_same_owner_and_routine():
+ """The owner has to be able to rely on it: a routine that lands on a
+ different minute after every deploy is not a cadence."""
+ first = spread_cron("H 9 * * 1", seed="user-a:morning-sweep:0")
+ second = spread_cron("H 9 * * 1", seed="user-a:morning-sweep:0")
+ assert first == second
+
+
+def test_spread_separates_two_owners_on_the_same_cadence():
+ """The whole point: five experts all say Monday 9am, and the turns that
+ lose the race to run do not fail loudly, they simply never happen."""
+ minutes = {
+ spread_cron("H 9 * * 1", seed=f"user-{n}:morning-sweep:0").split()[0]
+ for n in range(20)
+ }
+ assert len(minutes) > 10
+
+
+def test_spread_separates_two_routines_on_one_account():
+ a = spread_cron("H 9 * * 1", seed="user-a:queue-sweep:0")
+ b = spread_cron("H 9 * * 1", seed="user-a:pipeline-read:0")
+ assert a != b
+
+
+def test_spread_separates_the_fire_times_of_one_routine():
+ """A routine with two crons in the same hour must not collapse onto one."""
+ a = spread_cron("H 8 * * *", seed="user-a:callback-sweep:0")
+ b = spread_cron("H 8 * * *", seed="user-a:callback-sweep:1")
+ assert a != b
+
+
+def test_spread_leaves_every_cadence_that_is_not_an_H():
+ """A named minute is a decision — a roster author who wrote 07:40 meant it,
+ and so does an owner who asked for 10am. Only ``H`` defers the choice."""
+ for cron in ["0 9 * * 1", "40 7 * * *", "*/15 * * * *", "* 9 * * 1", "not a cron"]:
+ assert spread_cron(cron, seed="user-a:x:0") == cron
+
+
+def test_the_unattended_denylist_names_things_that_exist():
+ """A name that has been renamed out from under this set denies nothing, and
+ the routine would quietly gain the reach the denylist exists to remove."""
+ for granted in (True, False):
+ for name in routine_disabled_tools(granted=granted):
+ assert name in TOOL_REGISTRY or name in CAPABILITY_GATE_NAMES, name
+
+
+def test_the_unattended_denylist_closes_both_capability_gates():
+ """Blocks and MCP servers are reached through ``run_capability``, so only
+ the gates withhold them — denying a tool name would leave both open."""
+ assert CAPABILITY_GATE_NAMES <= routine_disabled_tools(granted=False)
+
+
+def test_no_routine_may_schedule_another_however_trusted_it_is():
+ """The escalation this whole design has to refuse: an unattended turn reads
+ a page nobody is watching it read, the page asks for a routine, and the
+ account is left with standing work — and credentials — nobody agreed to.
+ Trusting the owner's own words is not trusting what those words go and
+ read."""
+ for granted in (True, False):
+ denied = routine_disabled_tools(granted=granted)
+ assert ROUTINE_SELF_ESCALATION_TOOLS <= denied, granted
+ assert {"schedule_routine", "schedule_followup"} <= ROUTINE_SELF_ESCALATION_TOOLS
+
+
+def test_a_granted_routine_keeps_the_tools_its_owners_chat_has():
+ """The grant is the owner's answer, per routine, and it has to actually do
+ something — a routine they bound to their inbox that still could not reach
+ it would make the question they were asked meaningless."""
+ granted = routine_disabled_tools(granted=True)
+ assert "run_agent" not in granted
+ assert not CAPABILITY_GATE_NAMES & granted
+
+
+def test_an_ungranted_routine_cannot_reach_a_connected_account():
+ """Where seeded routines sit until somebody says otherwise: a roster prompt
+ is read by whoever reviewed the PR, not by the owner whose inbox it would
+ run against."""
+ ungranted = routine_disabled_tools(granted=False)
+ assert "run_agent" in ungranted
+ assert "post_to_chat_platform" in ungranted
+ assert CAPABILITY_GATE_NAMES <= ungranted
+
+
+def test_an_ungranted_routine_does_not_get_a_shell():
+ """The denial that looks like overreach and is not. ``bash_exec`` hands the
+ E2B sandbox the owner's live integration tokens, keyed on the user alone —
+ it never consults this filter or the grant. A shell holding those, with
+ full internet access, is every other denial here undone by one echo."""
+ assert "bash_exec" in routine_disabled_tools(granted=False)
+ # Granted, it is exactly what the owner agreed to, so it comes back.
+ assert "bash_exec" not in routine_disabled_tools(granted=True)
+
+
+def test_roster_routines_ask_before_they_run():
+ """Every seeded routine is a proposal written for everybody, so each one has
+ to name what it needs from this owner. A routine with no asks would schedule
+ straight off the template, against guesses, unattended."""
+ for entry in seed.ROSTER:
+ for routine in entry["routines"]:
+ assert routine["asks"], (entry["name"], routine["key"])
+
+
+def test_roster_routines_ask_for_a_timezone():
+ """Crons resolve in the owner's timezone and the suggested hour is a guess,
+ so every routine has to settle when it actually runs."""
+ for entry in seed.ROSTER:
+ for routine in entry["routines"]:
+ asks = " ".join(routine["asks"]).lower()
+ assert "timezone" in asks, (entry["name"], routine["key"])
+
+
+def test_every_session_mode_is_reachable_by_name():
+ """The three modes are the tool's enum, so a name that stopped parsing here
+ would silently collapse every routine onto THREAD."""
+ for name in ["THREAD", "PINNED", "FRESH"]:
+ assert _session_mode(name).value == name
+
+
+def test_session_mode_is_case_insensitive():
+ assert _session_mode("thread").value == "THREAD"
+
+
+def test_an_unknown_session_mode_falls_back_to_thread():
+ """It arrives as a model argument. A typo should give the routine its own
+ thread — the mode that keeps its memory — not fail a call the owner already
+ agreed to."""
+ assert _session_mode("here").value == "THREAD"
diff --git a/autogpt_platform/backend/backend/api/features/experts/scheduling.py b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
index e7244e88d1..cfd7bf7bf2 100644
--- a/autogpt_platform/backend/backend/api/features/experts/scheduling.py
+++ b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
@@ -15,6 +15,7 @@ from typing import TYPE_CHECKING
import prisma.models
from prisma.enums import ResourceVisibility
+from backend.api.features.experts import routine_jobs
from backend.api.features.experts.errors import ExpertScheduleCleanupError
from backend.api.features.experts.models import ExpertDetachPreview
from backend.copilot import db as chat_db
@@ -297,6 +298,11 @@ async def detach_expert_triggers(user_id: str, expert_id: str) -> None:
},
data={"isActive": False, "deactivatedByExpertArchive": True},
)
+ # Routines are copilot-turn schedules, which `_get_expert_schedules` does
+ # not see (it is graph-only), so they need their own pass. Without it an
+ # archived expert's routines keep their next run time, re-arm on every
+ # tick, and stay listed as scheduled chats for an expert the owner let go.
+ await routine_jobs.pause_routines_for_archive(user_id, expert_id)
scheduler = get_scheduler_client()
for schedule in await _get_expert_schedules(user_id, expert_id):
try:
@@ -408,6 +414,10 @@ async def reattach_expert_triggers(user_id: str, expert_id: str) -> None:
"teamId": team_id,
},
)
+ # Scoped to the routines archiving paused, never one the owner had already
+ # switched off — the same distinction `deactivatedByExpertArchive` draws
+ # for presets just above.
+ await routine_jobs.resume_routines_after_revive(user_id, expert_id)
scheduler = get_scheduler_client()
for schedule in await _get_expert_schedules(
user_id, expert_id, include_paused=True
diff --git a/autogpt_platform/backend/backend/api/features/experts/scheduling_test.py b/autogpt_platform/backend/backend/api/features/experts/scheduling_test.py
index 062ddd9da9..c1ae1f7c58 100644
--- a/autogpt_platform/backend/backend/api/features/experts/scheduling_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/scheduling_test.py
@@ -35,9 +35,16 @@ async def test_reattach_rehomes_presets_to_current_personal_tenancy(mocker) -> N
mocker.patch.object(
scheduling, "get_scheduler_client", return_value=scheduler_client
)
+ # Re-hire also resumes the routines archiving paused, which reads its own
+ # rows. This test is about where presets land, so the routine pass is
+ # stubbed rather than given a database.
+ resume_routines = mocker.patch.object(
+ scheduling.routine_jobs, "resume_routines_after_revive", new=AsyncMock()
+ )
await scheduling.reattach_expert_triggers("owner", "expert-1")
+ resume_routines.assert_awaited_once_with("owner", "expert-1")
resolve_tenancy.assert_awaited_once_with("owner", "expert-1")
preset_client.update_many.assert_awaited_once_with(
where={
diff --git a/autogpt_platform/backend/backend/api/features/experts/seed.py b/autogpt_platform/backend/backend/api/features/experts/seed.py
index 5bbcdd1b65..4e5a403450 100644
--- a/autogpt_platform/backend/backend/api/features/experts/seed.py
+++ b/autogpt_platform/backend/backend/api/features/experts/seed.py
@@ -19,6 +19,7 @@ import logging
from collections.abc import Mapping
from typing import TypedDict
+import prisma.enums
import prisma.models
import prisma.types
@@ -56,6 +57,42 @@ class PreloadSeed(TypedDict):
cron: str | None
+class RoutineSeed(TypedDict):
+ # Stable slug; the key `_sync_routines` matches a template row on, and the
+ # name a hire's row keeps for the life of the expert. Renaming one orphans
+ # the old row on every existing hire, so treat it as permanent.
+ key: str
+ title: str
+ # The proposal, in the expert's own voice: what this routine would do each
+ # time it runs. Not what runs — switching the routine on rewrites this with
+ # the owner's answers before anything is scheduled.
+ prompt: str
+ # Suggested fire times, 5-field and resolved in the owner's timezone.
+ # Several because one routine can legitimately have more than one (a
+ # callback sweep at 08:30 and again at 13:00 is one thing the owner turned
+ # on).
+ #
+ # A minute of `H` means "some minute inside this hour" — plain cron has no
+ # way to say that, so this borrows Jenkins's spelling, and `spread_cron`
+ # picks the real minute per owner and routine at install. Use it whenever
+ # the hour is what matters, which for a standing job it almost always is:
+ # five personas that all literally say `0 9` arrive on one account as a
+ # 09:00 pile-up against the cap on concurrent turns, and the runs that lose
+ # are dropped rather than retried. Write a real minute only when that exact
+ # minute is the point.
+ crons: list[str]
+ # What the expert must ask before this can run — which repo, which inbox,
+ # what hour. Straight from the source package's installer block. A routine
+ # with unanswered asks cannot be switched on, which is what stops a seeded
+ # proposal from firing against guesses.
+ asks: list[str]
+ # Where each turn lands. THREAD (the default) gives the routine one durable
+ # thread of its own, which is also its memory when `graphiti-memory` is
+ # off; FRESH starts a new chat every time and suits work that re-reads its
+ # own source anyway.
+ session_mode: str
+
+
class RosterEntry(TypedDict):
name: str
role: str
@@ -79,6 +116,12 @@ class RosterEntry(TypedDict):
# Up to three rows for the profile's "sets up on day one"; empty hides it.
day_one: list[ExpertDayOneItem]
preloads: list[PreloadSeed]
+ # Standing work this persona offers. Every one arrives switched OFF and
+ # unable to reach a single connected service (see
+ # ``ExpertRoutine.grantsCredentials``) — a roster entry is read by whoever
+ # reviews the PR, not by the owner whose account it will run on, so the
+ # proposal is all a template is allowed to ship.
+ routines: list[RoutineSeed]
ROSTER: list[RosterEntry] = [
@@ -129,6 +172,23 @@ You are direct about trade-offs. If a page is already ranking you look for the s
{"slug": "ai-webpage-copy-improver", "cron": None},
{"slug": "ai-youtube-to-blog-converter", "cron": None},
],
+ "routines": [
+ {
+ "key": "content-pipeline-check",
+ "title": "What ships this week, and what is stuck",
+ "prompt": """Read the editorial calendar and your last check, then report in this order: what ships in the next seven days with the owner on each line, what is late and by how far, what is stuck waiting on one person or one missing proof point, and what has no owner or no ship date.
+
+Never flag the same stuck row two runs running unless it got worse. If nothing ships this week, nothing is late, and nothing has changed since your last run, say so in one line and stop — no filler. Speak up when something newly slips even if nothing else moved.
+
+One line per item, no preamble. Never invent an approval, a draft, or a date.""",
+ "crons": ["H 9 * * 1-5"],
+ "asks": [
+ "Where is your editorial calendar?",
+ "What time should this land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Jules",
@@ -165,6 +225,24 @@ You space posts out and change the angle each time — a result, a mistake, a qu
"cron": None,
},
],
+ "routines": [
+ {
+ "key": "repurposing-queue-check",
+ "title": "What landed this week that is worth cutting up",
+ "prompt": """Look over the work that shipped since your last run — posts, talks, calls, launches, anything the team published — and pick out what is worth repurposing. For each one, name the three to six ideas inside it that could stand on their own, ranked by how much someone would disagree with them, and say which platform each idea belongs on and why.
+
+Leave the source untouched when nothing in it survives on its own, and say so. If nothing new landed and nothing has changed since your last run, say the week was quiet in one line and stop.
+
+Nothing goes out from here: these are drafts waiting for a yes.""",
+ "crons": ["H 9 * * 1-5"],
+ "asks": [
+ "Where should I look for what shipped — a calendar, a folder, a feed?",
+ "Which platforms are actually in play for you?",
+ "What time should this land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Nadia",
@@ -207,6 +285,25 @@ You mark every claim as observed or inferred, and you name what you inferred it
{"slug": "personalized-morning-coffee-newsletter", "cron": "0 8 * * 1"},
{"slug": "youtube-transcription-scraper", "cron": None},
],
+ "routines": [
+ {
+ "key": "competitor-brief",
+ "title": "What competitors shipped, said, or changed",
+ "prompt": """Work the tiered watch list: Tier 1 direct competitors get a deep read, Tier 2 adjacent a skim, Tier 3 aspirational a monthly look. Fetch each one's public pages, blog, and pricing, and log every URL you fetched — including the ones that failed.
+
+Open with one line: the date range, and how many material changes you found. Then one block per competitor, every line ending in its source URL and date. A competitor with nothing material gets no block.
+
+Close each block with two to four lines on what it means here: a launch gets a positioning read, a pricing move a packaging read, a content push a calendar read. Say it is unclear when it is unclear.
+
+Never brief the same change twice. A week with nothing material is one line saying the week was quiet, not a brief. No change without a link, and never pad it to look busy.""",
+ "crons": ["H 8 * * 5"],
+ "asks": [
+ "Who is on the watch list, and which tier is each one?",
+ "What day and hour should the brief land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Remy",
@@ -248,6 +345,26 @@ You treat deliverability as a list problem before a technical one. You will ask
# workflow first, then dropping her from PERSONAS_WITHOUT_WORKFLOWS in
# the roster contract test.
"preloads": [],
+ "routines": [
+ {
+ "key": "lifecycle-performance-read",
+ "title": "How last week's lifecycle email actually did",
+ "prompt": """Fix the period: the last seven full days against the seven before. Pull the numbers from the source the user trusts, plus the send calendar and your previous read.
+
+Report what sent, what it did — opens, clicks, replies, unsubscribes, and whatever conversion the user actually cares about — and what moved against the week before. Every number carries its source. A move you cannot explain from evidence gets written as unclear, not guessed at.
+
+Then the three to five things worth doing about it: a subject line worth retiring, a segment worth splitting, a flow with a step nobody reaches. One line each.
+
+Never report the same week twice. A quiet week gets the headline, the table, and one line saying it was quiet.""",
+ "crons": ["H 8 * * 1"],
+ "asks": [
+ "Where do the email numbers come from?",
+ "Where is the send calendar?",
+ "What day and hour should this land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Mina",
@@ -304,6 +421,10 @@ You support record preparation, not professional accounting or tax advice. Do no
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Theo",
@@ -360,6 +481,10 @@ You provide operational support, not investment, legal, tax, valuation, or secur
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Quinn",
@@ -416,6 +541,10 @@ For cohorts, funnels, and experiments, keep eligibility, exposure, conversion wi
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Max",
@@ -449,6 +578,61 @@ You are rigorous about data quality. You flag when contact information looks sta
{"slug": "business-ownerceo-finder", "cron": None},
{"slug": "email-address-finder", "cron": None},
],
+ "routines": [
+ {
+ "key": "weekday-prospecting-batch",
+ "title": "The next few names, researched with drafts waiting",
+ "prompt": """Take the next batch off the target list at the size the user set, five by default, preferring strong-fit rows that are new or enriched and have never been touched.
+
+Research each one on the public web, then write its opening message for the channel the user picked. Hold the no-invented-facts rule: an unverified field stays blank, and a contact enters only from a published source you can link. Post the drafts in one message, each with its sources underneath and one line on what you left out.
+
+Name any row you could not verify, with the reason, at the end. Never re-draft a row you drafted in the last seven days. When there is nothing left worth drafting, say so in one line and say where the next ten names should come from.
+
+Nothing sends. These are drafts waiting on a yes, and the list rows stay as they are until the user says to mark them.""",
+ "crons": ["H 8 * * 1-5"],
+ "asks": [
+ "Where is the target list?",
+ "How many should I work per run? (five by default)",
+ "Which channel are the first touches for?",
+ "What time should the batch land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ {
+ "key": "monday-list-top-up",
+ "title": "Tops up the target list before it runs dry",
+ "prompt": """Audit the target list: count the untouched strong-fit rows, and check for duplicates, stale ownership, and suppression conflicts. Name what is wrong rather than quietly fixing it.
+
+If ten or more untouched strong-fit rows remain, say the list is healthy with the count and stop. Otherwise research up to ten fresh rows at the same bar as the original build — scored fit, verified titles, no guessed contacts — and never re-add a person-and-company pair that came off the list in the last 30 days.
+
+Put the new rows here with the fit reason on each, and wait. Writing them back to the list is the user's call, not this run's.""",
+ "crons": ["H 9 * * 1"],
+ "asks": [
+ "Where is the target list?",
+ "What does a strong-fit row look like for you?",
+ "What day and hour should this run, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ {
+ "key": "friday-pipeline-recap",
+ "title": "The week's pipeline movement and what is stuck",
+ "prompt": """Pull the week's movement from the numbers source the user trusts, confirming its shape before you read it. Never carry last week forward as news.
+
+A deal already recapped with no change since gets one rollup line, not a repeat block. If nothing moved and nothing is newly stuck, say the week was quiet in one line, add a one-line stalled-age rollup naming the oldest stuck deal and its age, and stop.
+
+Otherwise one block per deal that moved or stalled: the movement with its evidence, your forecast grade, and the one next action with an owner. Label every load-bearing claim FACT, INFERENCE, or UNKNOWN.
+
+Close with the outreach tally — drafted, sent, replies split positive, neutral and negative, meetings booked — graded against a 3-5% reply rate and two to three meetings per hundred sent, then the top three actions for Monday.""",
+ "crons": ["H 16 * * 5"],
+ "asks": [
+ "Where do the pipeline numbers live?",
+ "Where are the deal notes?",
+ "What day and hour should the recap land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Devon",
@@ -498,6 +682,10 @@ For upgrades, you prefer the smallest supported change that removes the risk. Yo
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Riley",
@@ -547,6 +735,10 @@ You prepare renewal and expansion work without forcing a sale. You confirm dates
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Jordan",
@@ -596,6 +788,10 @@ For pipeline and renewals, you measure time in stage against the team's defined
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Frankie",
@@ -632,6 +828,38 @@ You are conservative about commitments. You never promise a delivery date, refun
# are research-only (see PreloadSeed.cron).
{"slug": "personalized-morning-coffee-newsletter", "cron": "40 7 * * *"},
],
+ "routines": [
+ {
+ "key": "day-ahead-brief",
+ "title": "Today's meetings, and what still needs you",
+ "prompt": """Read today's calendar and report in this order: what is on today with who is attending, which of those need prep you have not done, what is waiting on someone else, and anything double-booked or missing a location or an agenda.
+
+For each meeting that needs it, say what a good outcome looks like and the one thing to have ready. Keep it scannable: one line per item, owners in bold, times explicit, and a one-line summary at the top for anyone with thirty seconds.
+
+If the day is clear and nothing has changed since your last run, say so in one line. Never invent an attendee, an agenda, or a commitment.""",
+ "crons": ["H 8 * * 1-5"],
+ "asks": [
+ "Which calendar should I read?",
+ "What time should the brief land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ {
+ "key": "week-ahead-review",
+ "title": "What moved last week, and what is stuck",
+ "prompt": """Fix the period: the last seven full days against the seven before. Compare like with like — a holiday week goes against the prior holiday week, not the one before it.
+
+Report what moved, then what is stuck, in this order: overdue actions, slipped milestones, anything breaching a commitment, and anything with no owner. One line per item with the owner on it. Every number carries its source, and a move you cannot explain from evidence is written as unclear.
+
+Never report the same week twice. A quiet week gets the headline, the summary, and one line saying it was quiet — plus the stuck list, if anything is stuck.""",
+ "crons": ["H 8 * * 1"],
+ "asks": [
+ "Where do I read what moved — a tracker, a board, a sheet?",
+ "What day and hour should the review land, and in which timezone?",
+ ],
+ "session_mode": "THREAD",
+ },
+ ],
},
{
"name": "Harper",
@@ -681,6 +909,10 @@ You draft candidate messages but never send them. Rejection drafts state the dec
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Vera",
@@ -730,6 +962,10 @@ You cannot approve a budget, choose a vendor, accept terms, issue a purchase ord
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
{
"name": "Ellis",
@@ -779,6 +1015,10 @@ You do not give legal advice. You do not say language is legal, enforceable, mar
),
],
"preloads": [],
+ # No standing work yet. Explicit rather than omitted: a roster
+ # entry declaring nothing to do unattended is a decision, and the
+ # required key is what makes somebody make it.
+ "routines": [],
},
]
@@ -1092,6 +1332,93 @@ async def _prune_preloads(
)
+async def _sync_routines(template_id: str, entry: RosterEntry) -> None:
+ """Push the roster's routine proposals onto the template, keyed by slug.
+
+ Template rows only. A hire's rows are handled by ``_sync_hired_routines``,
+ which is far more cautious, because a routine on a hire may already be
+ running on somebody's account.
+ """
+ existing = await prisma.models.ExpertRoutine.prisma().find_many(
+ where={"expertId": template_id}
+ )
+ by_key = {row.key: row for row in existing if row.key is not None}
+ wanted = {routine["key"] for routine in entry["routines"]}
+ for routine in entry["routines"]:
+ fields = _routine_fields(routine)
+ current = by_key.get(routine["key"])
+ if current is None:
+ await prisma.models.ExpertRoutine.prisma().create(
+ data=prisma.types.ExpertRoutineCreateInput(
+ expertId=template_id, key=routine["key"], **fields
+ )
+ )
+ else:
+ await prisma.models.ExpertRoutine.prisma().update(
+ where={"id": current.id}, data=fields
+ )
+ stale = [row.id for row in existing if row.key not in wanted]
+ if not stale:
+ return
+ await prisma.models.ExpertRoutine.prisma().delete_many(
+ where={"id": {"in": stale}, "expertId": template_id}
+ )
+ logger.info(
+ f"Removed {len(stale)} stale template routine(s) from '{entry['name']}'"
+ )
+
+
+def _routine_fields(
+ routine: RoutineSeed,
+) -> prisma.types.ExpertRoutineUpdateManyMutationInput:
+ """The columns a roster entry owns on a template row.
+
+ ``grantsCredentials`` is absent on purpose: it is never roster-declared, so
+ a template row keeps the schema default of False and no roster edit can
+ hand a seeded routine the keys to somebody's inbox.
+
+ ``source`` is written rather than defaulted, because it is what decides
+ that a hired copy of this row reaches nothing until its owner says so.
+ """
+ return {
+ "title": routine["title"],
+ "prompt": routine["prompt"],
+ "crons": routine["crons"],
+ "asks": routine["asks"],
+ "sessionMode": prisma.enums.ExpertRoutineSession(routine["session_mode"]),
+ "source": prisma.enums.ExpertRoutineSource.TEMPLATE,
+ }
+
+
+async def _sync_hired_routines(template_id: str, entry: RosterEntry) -> int:
+ """Refresh routine proposals on hires — but only the untouched ones.
+
+ A routine nobody has switched on and nobody has edited is still just an
+ offer, so re-wording it or fixing its suggested hour is safe and reaches
+ people who hired last month. Everything else is off limits: once a routine
+ is running, or once its owner has changed a single thing about it, what it
+ does is theirs and a roster edit must never silently rewrite it.
+
+ New roster routines are not added to existing hires either. A hire's
+ routine list is what that expert arrived with; growing it behind the
+ owner's back would put unasked-for standing work on their team page.
+ """
+ if not entry["routines"]:
+ return 0
+ refreshed = 0
+ for routine in entry["routines"]:
+ refreshed += await prisma.models.ExpertRoutine.prisma().update_many(
+ where={
+ "key": routine["key"],
+ "enabledAt": None,
+ "customizedAt": None,
+ "Expert": {"is": {"sourceTemplateId": template_id}},
+ },
+ data=_routine_fields(routine),
+ )
+ return refreshed
+
+
async def _resolve_roster_preloads() -> dict[str, str]:
slugs = {preload["slug"] for entry in ROSTER for preload in entry["preloads"]}
resolved = {
@@ -1157,14 +1484,16 @@ async def seed_roster() -> list[str]:
for entry in ROSTER:
template = await _upsert_template(entry)
await _sync_preloads(template.id, entry, resolved_versions)
+ await _sync_routines(template.id, entry)
await _sync_bundled_skills(
template.id, [resolved_skills[slug] for slug in entry["bundled_skills"]]
)
refreshed = await _backfill_hired_copies(template)
+ routines = await _sync_hired_routines(template.id, entry)
template_ids.append(template.id)
logger.info(
f"Seeded expert template '{entry['name']}' (#{template.id}); "
- f"refreshed {refreshed} hired copies"
+ f"refreshed {refreshed} hired copies and {routines} untouched routine(s)"
)
await _clear_removed_cadences()
return template_ids
diff --git a/autogpt_platform/backend/backend/copilot/eval/style/assembly.py b/autogpt_platform/backend/backend/copilot/eval/style/assembly.py
index d8e8e33e23..991f10f3d1 100644
--- a/autogpt_platform/backend/backend/copilot/eval/style/assembly.py
+++ b/autogpt_platform/backend/backend/copilot/eval/style/assembly.py
@@ -21,6 +21,8 @@ from backend.api.features.experts.seed import ROSTER, RosterEntry
from backend.copilot.config import ChatConfig
from backend.copilot.engine import resolve_use_sdk
from backend.copilot.expert_context import (
+ render_account_standing_work_block,
+ render_expert_computer_block,
render_expert_identity_suffix,
render_expert_workflows_block,
render_team_context,
@@ -117,11 +119,25 @@ def user_prefix(expert: Expert | None, roster: list[Expert]) -> str:
(``build_expert_context``): the expert's installed workflows and the rest
of the roster as teammates; plain Otto gets the whole roster."""
if expert is None:
- return render_team_context(roster, delegation_enabled=DELEGATION_ENABLED)
- return render_expert_workflows_block(expert) + render_team_context(
- roster,
- delegation_enabled=DELEGATION_ENABLED,
- exclude_expert_id=expert.id,
+ # ``<routines>`` is omitted: it is a per-account database read, and an
+ # eval fixture has no account. ``<standing_work>`` is static text every
+ # Otto turn carries, so leaving it out here would make this check pass
+ # while production and the harness disagreed.
+ return (
+ render_team_context(roster, delegation_enabled=DELEGATION_ENABLED)
+ + render_account_standing_work_block()
+ )
+ # ``<expert_computer>`` is only rendered when E2B actually backs the
+ # sandbox, so it is empty wherever E2B is unconfigured — which is why its
+ # absence here went unnoticed: CI has no E2B and both sides read "".
+ return (
+ render_expert_workflows_block(expert)
+ + render_expert_computer_block()
+ + render_team_context(
+ roster,
+ delegation_enabled=DELEGATION_ENABLED,
+ exclude_expert_id=expert.id,
+ )
)
diff --git a/autogpt_platform/backend/backend/copilot/expert_context.py b/autogpt_platform/backend/backend/copilot/expert_context.py
index 4ee997bd3e..3553e58b52 100644
--- a/autogpt_platform/backend/backend/copilot/expert_context.py
+++ b/autogpt_platform/backend/backend/copilot/expert_context.py
@@ -25,6 +25,7 @@ import asyncio
import logging
from backend.api.features.experts.models import PROTECTED_SOUL_RULES, Expert
+from backend.api.features.experts.models import ExpertRoutine as ExpertRoutineModel
from backend.blocks.desktop._api import SHARED_PATH, WORKSPACE_PATH
from backend.copilot.config import ChatConfig
from backend.data.db_accessors import experts_db
@@ -114,6 +115,24 @@ def render_expert_identity_suffix(expert: Expert) -> str:
f"<voice_preferences>\n{voice}\n</voice_preferences>\n"
f"<boundaries>\n{boundaries}\n</boundaries>\n"
f"<protected_rules>\n{protected_rules}\n</protected_rules>\n"
+ f"<standing_work>\n"
+ f"Part of your job is the work that repeats. A colleague who only "
+ f"ever acts when asked is half a colleague: when you notice something "
+ f"in your own area that would be worth doing every week, or every "
+ f"weekday morning, say so and offer to take it on. "
+ f"`list_routines` shows any you already came with, and "
+ f"`schedule_routine` both switches one on and sets up a new one you "
+ f"and the user agreed on — you are not limited to the routines you "
+ f"arrived with, and an expert that arrived with none can still build "
+ f"its own. Offer only work inside your role as "
+ f"{escape_prompt_xml_tags(expert.role)}.\n"
+ f"Never describe a routine as running until the tool call that "
+ f"schedules it has actually succeeded. An unkept cadence is silent — "
+ f"the user finds out by noticing that nothing ever arrived — so "
+ f"'I'll check every Monday' is a promise you may only make after the "
+ f"call returns. Every routine you set up is the user's to see and "
+ f"change: `list_schedules` shows what is really scheduled.\n"
+ f"</standing_work>\n"
f"<first_turn>\n"
f"Your first turn after being hired arrives as a hidden instruction "
f"that names `expert_onboarding`. On that turn call "
@@ -122,8 +141,13 @@ def render_expert_identity_suffix(expert: Expert) -> str:
f"question and option on that card must be about your own role as "
f"{escape_prompt_xml_tags(expert.role)} and the workflows installed "
f"on you: never about a teammate's area or work outside your role, "
- f"whatever other context suggests. Once the card's answers come "
- f"back, continue as normal.\n"
+ f"whatever other context suggests. If <routines> lists any "
+ f"standing work, spend one of those questions on which of it to take "
+ f"on — it is the one moment the user is deciding how you will work, "
+ f"and a routine offered later has already missed it. Once the card's "
+ f"answers come back, continue as normal: that reply is an ordinary "
+ f"turn, so settle the details of anything they picked and switch it "
+ f"on there.\n"
f"</first_turn>\n"
f"The base instructions above describe Otto, the platform's default "
f"assistant. All platform capabilities and tools remain "
@@ -210,7 +234,16 @@ async def build_expert_context(
delegation_enabled=delegation_enabled,
include_teammates=include_teammates,
)
- return await _team_context(user_id, delegation_enabled=delegation_enabled)
+ team = await _team_context(user_id, delegation_enabled=delegation_enabled)
+ if not delegation_enabled:
+ # ``expert_resources`` is hidden without the flag, and naming a
+ # tool the turn cannot execute is worse than saying nothing.
+ return team
+ return (
+ team
+ + render_account_standing_work_block()
+ + await _routines_block(user_id, None)
+ )
except Exception as e:
logger.warning(f"Failed to build expert context: {e}")
return ""
@@ -248,7 +281,109 @@ async def _expert_session_context(
# If the expert changes between those reads, omit only this optional block.
if expert is None or expert.is_archived:
return ""
- return render_expert_workflows_block(expert) + _expert_computer_block() + teammates
+ return (
+ render_expert_workflows_block(expert)
+ + await _routines_block(user_id, expert_id)
+ + render_expert_computer_block()
+ + teammates
+ )
+
+
+def render_account_standing_work_block() -> str:
+ """Tell Otto that standing work is a thing it owns, not only experts.
+
+ Without this the model reaches for ``schedule_followup``, because that is
+ the only scheduling primitive its prompt has ever named — and a weekly job
+ pinned to whatever chat the user happened to be in is what that produces.
+ It is right for a deferral and wrong for everything that repeats, and the
+ difference is invisible at the moment of choosing.
+ """
+ return (
+ "<standing_work>\n"
+ "Work that repeats, or that the user will want to find and change "
+ "later, belongs in a routine: `schedule_routine` leaves a named record "
+ "they can switch off, and gives recurring work its own thread so each "
+ "run remembers the last. `list_routines` shows what you hold. Offer "
+ "one when you notice work repeating, rather than waiting to be asked "
+ "twice, and never say a routine is running before the call that "
+ "schedules it has returned — an unkept cadence is silent.\n"
+ "</standing_work>\n\n"
+ )
+
+
+async def _routines_block(user_id: str, expert_id: str | None) -> str:
+ """The standing work this expert offers, and what is actually running.
+
+ Without this the model has no idea its own routines exist, so it never
+ offers them and the expert silently does less than it came able to do. A
+ failed lookup drops the block rather than the turn: an expert that forgets
+ to mention a routine is worse than one that cannot answer at all.
+ """
+ try:
+ routines = await experts_db().list_routines(user_id, expert_id)
+ except Exception as e:
+ logger.warning(f"Failed to load routines for expert context: {e}")
+ return ""
+ if not routines:
+ return ""
+ lines = "\n".join(_routine_line(routine) for routine in routines)
+ # Only a proposal somebody else wrote needs resolving before it runs. Said
+ # about the user's own words it would be nonsense — and worse, it would
+ # send the model back to re-ask questions they have already answered.
+ proposal_rule = (
+ (
+ "The routines marked (proposal) are offers, not plans: their "
+ "wording is a draft written for everybody, so before switching one "
+ "on, answer its open questions with the user, rewrite it in their "
+ "terms, and show them the result. Routines without that mark are "
+ "already the user's own words — do not re-ask them. A routine "
+ "reaches none of their connected accounts unless they say it "
+ "should, so if the work needs one, ask for that specifically "
+ "rather than assuming it.\n"
+ )
+ if any(r.source == "TEMPLATE" for r in routines)
+ else ""
+ )
+ return (
+ f"<routines>\n"
+ f"Standing work you can do unattended. Each runs as a turn of yours at "
+ f"its own time, in the user's timezone. Switch one on with "
+ f"`schedule_routine` — never silently, always after the user has "
+ f"chosen it:\n"
+ f"{lines}\n"
+ f"{proposal_rule}"
+ f"</routines>\n\n"
+ )
+
+
+def _routine_line(routine: ExpertRoutineModel) -> str:
+ title = escape_prompt_xml_tags(routine.title)
+ when = (
+ ", ".join(routine.crons)
+ if routine.crons
+ else (
+ f"once at {routine.run_at:%Y-%m-%d %H:%M} UTC"
+ if routine.run_at
+ else "no time set"
+ )
+ )
+ if not routine.enabled:
+ asks = (
+ " — still needs answered: "
+ + "; ".join(escape_prompt_xml_tags(ask) for ask in routine.asks)
+ if routine.asks
+ else ""
+ )
+ # Marked per row rather than described once for the list: an expert can
+ # hold a template's proposals and the owner's own routines at the same
+ # time, and one blanket rule about drafts sends the model back to
+ # re-ask questions the user already answered.
+ proposal = " (proposal)" if routine.source == "TEMPLATE" else ""
+ return f"- {title} (id: {routine.id}) — OFF{proposal}, suggested {when}{asks}"
+ reach = (
+ "may use connected accounts" if routine.grants_credentials else "platform-only"
+ )
+ return f"- {title} (id: {routine.id}) — ON, {when}, {reach}"
def render_expert_workflows_block(expert: Expert) -> str:
@@ -282,7 +417,7 @@ def render_expert_workflows_block(expert: Expert) -> str:
)
-def _expert_computer_block() -> str:
+def render_expert_computer_block() -> str:
"""Tell an expert about its own machine — only when E2B actually backs it.
Lives in the first user message with the other expert blocks so the
diff --git a/autogpt_platform/backend/backend/copilot/expert_context_test.py b/autogpt_platform/backend/backend/copilot/expert_context_test.py
index dc61f38b4b..408c915612 100644
--- a/autogpt_platform/backend/backend/copilot/expert_context_test.py
+++ b/autogpt_platform/backend/backend/copilot/expert_context_test.py
@@ -20,6 +20,7 @@ import pytest
from backend.api.features.experts.models import (
PROTECTED_SOUL_RULES,
Expert,
+ ExpertRoutine,
ExpertWorkflowRef,
)
from backend.copilot.expert_context import (
@@ -663,15 +664,21 @@ class TestBuildExpertContextPlainSession:
assert results[0] == results[1]
@pytest.mark.asyncio
- async def test_no_experts_returns_empty(self):
+ async def test_no_experts_renders_no_roster(self):
+ """A teamless account still gets the standing-work instruction — it is
+ the account most likely to be in a plain Otto chat asking for something
+ weekly — but nothing that would describe a team it does not have."""
from backend.copilot.expert_context import build_expert_context
mock_db = MagicMock()
mock_db.list_experts = AsyncMock(return_value=[])
+ mock_db.list_routines = AsyncMock(return_value=[])
with patch(f"{_EC}.experts_db", MagicMock(return_value=mock_db)):
result = await build_expert_context("user-1", None)
- assert result == ""
+ assert "<team_context>" not in result
+ assert "<routines>" not in result
+ assert result.strip().startswith("<standing_work>")
@pytest.mark.asyncio
async def test_no_experts_with_team_flag_renders_head_of_ai_block(self):
@@ -916,19 +923,22 @@ class TestInjectUserContextExpertWiring:
assert "Finding leads" in result
@pytest.mark.asyncio
- async def test_no_expert_block_without_expert_or_team(self):
+ async def test_no_team_or_expert_block_without_either(self):
from backend.copilot.model import ChatMessage
from backend.copilot.service import inject_user_context
msg = ChatMessage(role="user", content="hello", sequence=None)
mock_db = MagicMock()
mock_db.list_experts = AsyncMock(return_value=[])
+ mock_db.list_routines = AsyncMock(return_value=[])
with patch(f"{_EC}.experts_db", MagicMock(return_value=mock_db)):
result = await inject_user_context(
None, "hello", "sess-1", [msg], user_id="user-1"
)
- assert result == "hello"
+ assert result.endswith("hello")
+ assert "<team_context>" not in result
+ assert "<expert_identity>" not in result
class TestStripInjectedContextForDisplay:
@@ -1085,3 +1095,141 @@ class TestExpertComputerBlock:
assert "<expert_computer>" not in result
assert "<expert_workflows>" in result
+
+
+class TestRoutinesBlock:
+ """Standing work, as the model is told about it.
+
+ Nothing here asserts the wording; what each test pins is a decision — that
+ Otto is told routines exist at all, that a proposal is described as a
+ proposal and the owner's own words are not, and that a one-shot says when
+ it runs instead of saying nothing.
+ """
+
+ @staticmethod
+ def _routine(**overrides) -> ExpertRoutine:
+ return ExpertRoutine(
+ **{
+ "id": "routine-1",
+ "expert_id": None,
+ "title": "Weekly calendar read",
+ "prompt": "Read the week ahead.",
+ "crons": ["0 8 * * 1"],
+ "source": "OWNER",
+ "enabled": True,
+ **overrides,
+ }
+ )
+
+ @staticmethod
+ def _db(routines: list[ExpertRoutine]) -> MagicMock:
+ db = MagicMock()
+ db.list_experts = AsyncMock(return_value=[])
+ db.list_templates = AsyncMock(return_value=[])
+ db.list_routines = AsyncMock(return_value=routines)
+ return db
+
+ async def _otto_context(self, routines: list[ExpertRoutine]) -> str:
+ from backend.copilot.expert_context import build_expert_context
+
+ with patch(f"{_EC}.experts_db", MagicMock(return_value=self._db(routines))):
+ return await build_expert_context("user-1", None)
+
+ @pytest.mark.asyncio
+ async def test_otto_is_told_it_can_hold_standing_work(self):
+ """The bug this closes: with nothing in its prompt naming a routine,
+ the model reached for ``schedule_followup`` — the only scheduling tool
+ it had ever been told about — and pinned a weekly job to whatever chat
+ the user happened to be in."""
+ result = await self._otto_context([])
+
+ assert "<standing_work>" in result
+ assert "schedule_routine" in result
+ assert "list_routines" in result
+
+ @pytest.mark.asyncio
+ async def test_the_flag_that_hides_the_tools_hides_the_instruction(self):
+ """Routines ride the ``expert_resources`` group. With the flag off the
+ tools are not declared, and naming a tool the turn cannot call is worse
+ than saying nothing."""
+ from backend.copilot.expert_context import build_expert_context
+
+ with (
+ patch(f"{_EC}.experts_db", MagicMock(return_value=self._db([]))),
+ patch(f"{_EC}.is_feature_enabled", _flag_mock(HIRE_EXPERTS=False)),
+ ):
+ result = await build_expert_context("user-1", None)
+
+ assert "<standing_work>" not in result
+ assert "schedule_routine" not in result
+
+ @pytest.mark.asyncio
+ async def test_the_accounts_own_routines_are_listed_to_it(self):
+ result = await self._otto_context([self._routine()])
+
+ assert "<routines>" in result
+ assert "Weekly calendar read" in result
+ assert "routine-1" in result
+ assert "0 8 * * 1" in result
+
+ @pytest.mark.asyncio
+ async def test_a_proposal_is_described_as_one(self):
+ """A seeded routine's wording was written for everybody, so it has to
+ be resolved with this owner before it runs."""
+ result = await self._otto_context(
+ [self._routine(source="TEMPLATE", enabled=False, asks=["Which calendar?"])]
+ )
+
+ assert "(proposal)" in result
+ assert "are offers, not plans" in result
+ assert "Which calendar?" in result
+
+ @pytest.mark.asyncio
+ async def test_the_owners_own_words_are_not(self):
+ """Said about a routine the user dictated, "answer its open questions"
+ is nonsense — and worse, it sends the model back to re-ask things they
+ already answered."""
+ result = await self._otto_context([self._routine(source="OWNER")])
+
+ assert "<routines>" in result
+ assert "(proposal)" not in result
+ assert "are offers, not plans" not in result
+
+ @pytest.mark.asyncio
+ async def test_a_one_shot_says_when_it_runs(self):
+ """It has no cron, so the cadence-shaped rendering left it describing
+ itself with an empty string where its time should be."""
+ result = await self._otto_context(
+ [
+ self._routine(
+ title="Check the deploy",
+ crons=[],
+ run_at=datetime(2026, 9, 20, 14, 30, tzinfo=timezone.utc),
+ )
+ ]
+ )
+
+ assert "2026-09-20 14:30" in result
+
+ @pytest.mark.asyncio
+ async def test_a_mixed_list_marks_only_the_proposals(self):
+ """An expert holds a template's offers and the owner's own routines at
+ once. One blanket rule about drafts would send the model back to re-ask
+ questions the user already answered."""
+ result = await self._otto_context(
+ [
+ self._routine(
+ id="r-template",
+ title="Shipped with me",
+ source="TEMPLATE",
+ enabled=False,
+ ),
+ self._routine(
+ id="r-owner", title="Mine", source="OWNER", enabled=False
+ ),
+ ]
+ )
+
+ lines = [ln for ln in result.splitlines() if ln.startswith("- ")]
+ marked = {ln.split(" (id: ")[0][2:]: "(proposal)" in ln for ln in lines}
+ assert marked == {"Shipped with me": True, "Mine": False}
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index f756a3995a..074ca64948 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -130,6 +130,7 @@ ToolName = Literal[
"list_expert_workflows",
"list_folders",
"list_presets",
+ "list_routines",
"list_schedules",
"list_skills",
"list_team",
@@ -156,6 +157,7 @@ ToolName = Literal[
"run_capability",
"run_sub_session",
"schedule_followup",
+ "schedule_routine",
"search_docs",
"search_feature_requests",
"setup_agent_webhook_trigger",
@@ -203,6 +205,82 @@ LEGACY_TOOL_ALIASES: dict[str, str] = {
}
DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset(LEGACY_TOOL_ALIASES)
+
+
+# What a routine reaches when nobody has bound it to anything. A roster
+# template is read by whoever reviews the PR, not by the owner whose account it
+# will run on, so a seeded routine ships able to research, think, read its own
+# workspace and write to its own thread — and nothing else. Denying the names
+# that carry a credential outward is what makes "a cadence may only carry work
+# that acts on nothing outside the platform" (``PreloadSeed.cron``) a boundary
+# rather than a comment. An owner who wants their queue swept says so when they
+# switch the routine on, and that answer is what lifts this.
+#
+# The grant is the whole rule at fire time. Where the prompt came from decides
+# what that grant STARTS as — a template arrives ungranted, and a routine the
+# owner dictated in their own chat arrives granted, because the same words typed
+# into the same chat already run with every tool here and taking ``run_agent``
+# off somebody's own morning briefing protects nobody. Both remain the owner's
+# to change, and neither reads as permission on its own.
+UNGRANTED_ROUTINE_DENIED_TOOLS: frozenset[str] = frozenset(
+ {
+ # The two capability gates, so denying them withholds every block and
+ # every MCP server rather than one tool's worth of them.
+ BLOCK_GATE,
+ MCP_GATE,
+ "run_agent",
+ "post_to_chat_platform",
+ # ``bash_exec`` is the one that looks harmless and is not. On E2B the
+ # sandbox is handed ``get_integration_env_vars(user_id)`` — the
+ # owner's live GH_TOKEN and friends — keyed on the user alone, with no
+ # reference to this filter or to the grant. A shell plus internet
+ # access plus the owner's tokens in ``env`` is the whole mute undone by
+ # one ``echo $GH_TOKEN``, so an ungranted routine does not get a shell.
+ "bash_exec",
+ }
+)
+
+
+# Refused on EVERY routine turn, however the routine was written and whatever
+# its owner granted it. An unattended turn reads things nobody is watching it
+# read — an issue tracker, an inbox, a web page — and text in any of them can
+# ask it to schedule more work. Without this, one injected page buys standing
+# access to the account forever: a routine that can write a routine can grant
+# itself the credentials its own prompt was denied, and the owner sees a
+# schedule they never agreed to. Standing work is created where somebody is
+# present to refuse it.
+ROUTINE_SELF_ESCALATION_TOOLS: frozenset[str] = frozenset(
+ {
+ "schedule_routine",
+ "schedule_followup",
+ "setup_agent_webhook_trigger",
+ }
+)
+
+
+def routine_disabled_tools(*, granted: bool) -> frozenset[str]:
+ """Tools to refuse on a routine's unattended turn.
+
+ *granted* is the owner's answer to "may this routine use my connected
+ services", which they give per routine when they switch it on. It only ever
+ removes the outward-reaching denials; nothing makes a routine able to
+ schedule more of itself.
+
+ Deliberately a denylist of what reaches *outward*, not a narrow allowlist:
+ reading, searching, and drafting into the thread are the whole point of an
+ unattended routine, and a routine that can do none of those is not worth
+ shipping off.
+
+ Kept here rather than beside the other tool gates in ``tools/__init__``:
+ the scheduler needs it at import time, and ``executor.scheduler`` importing
+ ``copilot.tools`` closes a cycle (tools -> helpers -> executor -> scheduler).
+ ``routines_test`` asserts every name here is a live tool or gate.
+ """
+ if granted:
+ return ROUTINE_SELF_ESCALATION_TOOLS
+ return UNGRANTED_ROUTINE_DENIED_TOOLS | ROUTINE_SELF_ESCALATION_TOOLS
+
+
"""Tool names accepted only for backwards compatibility with saved graphs.
These names are intentionally absent from ``ToolName`` and
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 9e33e72868..2b20017272 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -79,6 +79,7 @@ from .models import ErrorResponse
from .platform_info import PlatformInfoTool
from .raise_expert import RaiseExpertTool
from .resume_capability import ResumeCapabilityTool
+from .routines import ListRoutinesTool, ScheduleRoutineTool
from .run_agent import RunAgentTool
from .run_capability import RunCapabilityTool
from .run_sub_session import RunSubSessionTool
@@ -218,6 +219,10 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"install_expert_workflow": InstallExpertWorkflowTool(),
"remove_expert_workflow": RemoveExpertWorkflowTool(),
"list_expert_workflows": ListExpertWorkflowsTool(),
+ # Standing work: what the expert offers to do unattended, and the round
+ # trip that turns one of those offers into a real cadence.
+ "list_routines": ListRoutinesTool(),
+ "schedule_routine": ScheduleRoutineTool(),
"list_expert_credentials": ListExpertCredentialsTool(),
"grant_expert_credential": GrantExpertCredentialTool(),
"revoke_expert_credential": RevokeExpertCredentialTool(),
@@ -284,6 +289,11 @@ TOOL_GROUPS: dict[str, ToolGroup] = {
"install_expert_workflow": "expert_resources",
"remove_expert_workflow": "expert_resources",
"list_expert_workflows": "expert_resources",
+ # Routines ride the same gate as workflow installs: an expert manages its
+ # own standing work, and personal AutoPilot manages any expert's — and,
+ # with no expert named, the account's own.
+ "list_routines": "expert_resources",
+ "schedule_routine": "expert_resources",
"list_expert_credentials": "expert_resources",
"grant_expert_credential": "expert_admin",
"revoke_expert_credential": "expert_admin",
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
index 0c6c7f720d..f11204ecac 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
@@ -138,6 +138,50 @@ async def resolve_target_expert(
return expert.id
+class RoutineOwner(BaseModel):
+ """Whose standing work a routine call acts on.
+
+ ``expert_id is None`` is not "unknown" — it is the account itself. Otto is
+ the platform's default assistant rather than a row in ``Expert``, so its
+ routines hang off the owner, and a personal AutoPilot session that names no
+ expert is asking about its own.
+ """
+
+ expert_id: str | None = None
+
+
+async def resolve_routine_owner(
+ user_id: str, session: ChatSession, requested_expert_id: str | None
+) -> RoutineOwner | ErrorResponse:
+ """``resolve_target_expert``'s rule, minus the requirement to name someone.
+
+ An expert session still acts on itself and may not name another. Personal
+ AutoPilot may name one of the owner's experts to manage its standing work,
+ and naming nobody means the account's own — the one case where
+ ``resolve_target_expert`` has to refuse and this does not.
+ """
+ if session.expert_id is not None:
+ if requested_expert_id and requested_expert_id != session.expert_id:
+ return ErrorResponse(
+ message=EXPERT_OWNER_DENIED,
+ error="access_denied",
+ session_id=session.session_id,
+ )
+ return RoutineOwner(expert_id=session.expert_id)
+ if not requested_expert_id:
+ return RoutineOwner()
+ expert = await experts_db().get_expert(
+ user_id, requested_expert_id, include_workflows=False
+ )
+ if expert is None:
+ return ErrorResponse(
+ message=f"Expert '{requested_expert_id}' was not found on this account.",
+ error="expert_not_found",
+ session_id=session.session_id,
+ )
+ return RoutineOwner(expert_id=expert.id)
+
+
async def settle_expert_grants(user_id: str, session: ChatSession) -> None:
"""An expert installing a workflow on itself must not widen its own grants.
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 02753a92c5..7ffbbcff61 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -58,6 +58,9 @@ class ResponseType(str, Enum):
EXPERT_WORKFLOW = "expert_workflow"
EXPERT_WORKFLOWS = "expert_workflows"
EXPERT_CREDENTIALS = "expert_credentials"
+ # Standing work: the routines an expert offers, and one switched on or off.
+ ROUTINES = "routines"
+ ROUTINE = "routine"
CREDENTIAL_GRANT_REQUESTED = "credential_grant_requested"
SCHEDULE_CREATED = "schedule_created"
diff --git a/autogpt_platform/backend/backend/copilot/tools/routines.py b/autogpt_platform/backend/backend/copilot/tools/routines.py
new file mode 100644
index 0000000000..aec57286fb
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/routines.py
@@ -0,0 +1,443 @@
+"""Offer, switch on, and switch off standing work.
+
+An expert arrives with its routines already listed and every one of them off.
+Switching one on is a conversation, not a toggle: the template ships a proposal
+and the questions it needs answered, and the owner's answers become the prompt
+and the cadence that actually run. That is the whole point of the round trip —
+what a roster wrote for everybody is never what any one account should run
+unattended.
+
+The account has standing work too. Otto is not a row in ``Expert``, so its
+routines hang off the owner directly; everything else about them is the same,
+including that nothing a routine's own turn does can create another one.
+"""
+
+import logging
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+from backend.api.features.experts.models import ExpertRoutine
+from backend.api.features.experts.routines import (
+ RoutineNotFoundError,
+ RoutineUnansweredAsksError,
+)
+from backend.copilot.model import ChatSession, get_chat_session
+from backend.data.activity_event import ActivityEventDraft
+from backend.data.db_accessors import experts_db
+
+from .base import BaseTool
+from .expert_scope import RoutineOwner, resolve_routine_owner
+from .models import ErrorResponse, ResponseType, ToolResponseBase
+
+logger = logging.getLogger(__name__)
+
+# The shortest deferral ``schedule_followup`` accepts, kept identical so the
+# two tools cannot disagree about what "soon" means.
+_MIN_DELAY_SECONDS = 60
+
+_EXPERT_ID_PARAM = {
+ "type": "string",
+ "description": (
+ "Whose standing work. Experts act on themselves and omit it. From "
+ "personal AutoPilot, name an expert, or omit for the account's own."
+ ),
+}
+
+
+class RoutinesResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.ROUTINES
+ expert_id: str | None = None
+ routines: list[ExpertRoutine]
+
+
+class RoutineResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.ROUTINE
+ expert_id: str | None = None
+ routine: ExpertRoutine
+
+
+class ListRoutinesTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "list_routines"
+
+ @property
+ def description(self) -> str:
+ return (
+ "List standing work: routines and pending one-offs, which are "
+ "switched on, and what each still needs answered. Read before "
+ "offering one."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {"expert_id": _EXPERT_ID_PARAM},
+ "required": [],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+ owner = await resolve_routine_owner(user_id, session, expert_id)
+ if isinstance(owner, ErrorResponse):
+ return owner
+ routines = await experts_db().list_routines(user_id, owner.expert_id)
+ return RoutinesResponse(
+ message=(
+ f"{len(routines)} routine(s); "
+ f"{sum(1 for r in routines if r.enabled)} switched on."
+ ),
+ expert_id=owner.expert_id,
+ routines=routines,
+ session_id=session_id,
+ )
+
+
+class ScheduleRoutineTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "schedule_routine"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Create standing work, or switch a routine on or off. Omit "
+ "'routine_id' and pass 'title'/'prompt' plus 'crons' or "
+ "'delay_seconds' to set up something new you agreed with the "
+ "user. ON commits to what it will do: answer any 'asks' first "
+ "(never guess), use the time THEY chose, and show them the "
+ "wording before calling."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "routine_id": {
+ "type": "string",
+ "description": (
+ "Routine id from list_routines. Omit to create a new "
+ "one from 'title' and 'prompt'."
+ ),
+ },
+ "title": {
+ "type": "string",
+ "description": (
+ "Short name, for a new routine. Required when there "
+ "is no routine_id."
+ ),
+ },
+ "enabled": {
+ "type": "boolean",
+ "description": "True switches it on, false switches it off.",
+ },
+ "prompt": {
+ "type": "string",
+ "description": (
+ "The routine as it will run, rewritten from the "
+ "proposal with the user's answers. Required when it "
+ "has unanswered 'asks'."
+ ),
+ },
+ "crons": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Repeating work: 5-field crons in the user's timezone, "
+ "one per fire time. Minute 'H' means any minute in "
+ "that hour, picked once and kept — use it when they "
+ "gave an hour rather than a time, so routines do not "
+ "pile up. Not with 'delay_seconds'."
+ ),
+ },
+ "delay_seconds": {
+ "type": "integer",
+ "minimum": _MIN_DELAY_SECONDS,
+ "description": (
+ "One-off work: seconds from now. Convert an absolute "
+ "time ('at six') to a delay. Not with 'crons'."
+ ),
+ },
+ "session_mode": {
+ "type": "string",
+ "enum": ["THREAD", "PINNED", "FRESH"],
+ "description": (
+ "Where each run lands. THREAD (default): its own "
+ "thread, reused, which is how it remembers what it "
+ "already reported. PINNED: an existing chat — this "
+ "one unless 'session_id' names another. FRESH: a new "
+ "chat each time, remembering nothing."
+ ),
+ },
+ "session_id": {
+ "type": "string",
+ "description": (
+ "With PINNED, the chat each run lands in. Defaults to "
+ "this one; its id is in <session_context>. Same user "
+ "and same expert only."
+ ),
+ },
+ "grants_credentials": {
+ "type": "boolean",
+ "description": (
+ "Let it use the owner's connected services. Omit to "
+ "leave as-is. False: it researches and drafts but "
+ "touches nothing outside the platform. True only when "
+ "the user agreed to THIS routine using their accounts."
+ ),
+ },
+ "expert_id": _EXPERT_ID_PARAM,
+ },
+ "required": ["enabled"],
+ }
+
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, RoutineResponse):
+ return None
+ on = result.routine.enabled
+ return ActivityEventDraft(
+ category="SCHEDULE",
+ event_type="routine.enabled" if on else "routine.disabled",
+ title=(
+ f"Switched on '{result.routine.title}'"
+ if on
+ else f"Switched off '{result.routine.title}'"
+ ),
+ )
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ routine_id: str = "",
+ enabled: bool = False,
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+ if not routine_id and not kwargs.get("title"):
+ return ErrorResponse(
+ message=(
+ "Give a `routine_id` to change an existing routine, or a "
+ "`title`, a `prompt` and either `crons` or "
+ "`delay_seconds` to create one."
+ ),
+ error="missing_routine",
+ session_id=session_id,
+ )
+ owner = await resolve_routine_owner(user_id, session, expert_id)
+ if isinstance(owner, ErrorResponse):
+ return owner
+ pinned = await self._pinned_session(user_id, session, owner, kwargs)
+ if isinstance(pinned, ErrorResponse):
+ return pinned
+ try:
+ routine = await self._apply(
+ user_id, owner, routine_id, enabled, pinned, kwargs
+ )
+ except RoutineUnansweredAsksError as e:
+ return ErrorResponse(
+ message=str(e),
+ error="unanswered_asks",
+ session_id=session_id,
+ )
+ except RoutineNotFoundError:
+ return ErrorResponse(
+ message=f"Routine '{routine_id}' was not found.",
+ error="routine_not_found",
+ session_id=session_id,
+ )
+ except ValueError as e:
+ return ErrorResponse(
+ message=f"That schedule is not valid: {e}",
+ error="invalid_schedule",
+ session_id=session_id,
+ )
+ return RoutineResponse(
+ message=_confirmation(routine),
+ expert_id=owner.expert_id,
+ routine=routine,
+ session_id=session_id,
+ )
+
+ async def _pinned_session(
+ self,
+ user_id: str,
+ session: ChatSession,
+ owner: RoutineOwner,
+ kwargs: dict[str, Any],
+ ) -> str | None | ErrorResponse:
+ """The chat a PINNED routine fires into, validated before it is stored.
+
+ Same rule ``schedule_followup`` applies to its ``session_id``: the
+ target must be the caller's and in the routine owner's scope, so a
+ routine cannot be aimed at another persona's memory. The fire path
+ re-checks both on every run, because a chat can be deleted or a scope
+ can change long after this.
+
+ Scoped to ``owner``, not to the calling session: personal AutoPilot
+ managing an expert's routine is in no expert scope itself, so
+ defaulting to "this chat" would pin the owner's Otto chat onto an
+ expert's routine — which the fire path then refuses on every run.
+
+ Returns ``None`` when the call did not ask to pin anything. THREAD and
+ FRESH have no chat to name, and an omitted ``session_mode`` on an
+ existing routine means "leave it as it is" — answering with the
+ caller's chat there would silently re-pin a routine that was already
+ pinned somewhere else.
+ """
+ requested: str | None = kwargs.get("session_id")
+ current = session.session_id if session else None
+ in_owner_scope = session.expert_id == owner.expert_id
+
+ if requested:
+ if requested == current and in_owner_scope:
+ return requested
+ target = await get_chat_session(requested, user_id)
+ if target is None or target.expert_id != owner.expert_id:
+ return ErrorResponse(
+ message=(
+ f"Session {requested} not found, not owned by the "
+ "calling user, or outside the routine owner's memory "
+ "scope."
+ ),
+ error="session_not_found",
+ session_id=current,
+ )
+ return requested
+
+ # Nothing named. Only a call that explicitly asks to pin needs a chat;
+ # everything else has none to give and must not be refused for it.
+ if str(kwargs.get("session_mode") or "").upper() != "PINNED":
+ return None
+ if in_owner_scope:
+ return current
+ return ErrorResponse(
+ message=(
+ "PINNED needs `session_id`: this chat belongs to a different "
+ "scope than the routine's owner, so a routine pinned to it "
+ "would never run. Name one of that owner's chats, or use "
+ "THREAD."
+ ),
+ error="session_required",
+ session_id=current,
+ )
+
+ async def _apply(
+ self,
+ user_id: str,
+ owner: RoutineOwner,
+ routine_id: str,
+ enabled: bool,
+ pinned_session_id: str | None,
+ kwargs: dict[str, Any],
+ ) -> ExpertRoutine:
+ run_at = _run_at(kwargs.get("delay_seconds"))
+ crons = kwargs.get("crons")
+ grant = kwargs.get("grants_credentials")
+ if not routine_id:
+ created = await experts_db().create_routine(
+ user_id,
+ owner.expert_id,
+ title=kwargs.get("title") or "",
+ prompt=kwargs.get("prompt") or "",
+ crons=crons,
+ run_at=run_at,
+ session_mode=kwargs.get("session_mode"),
+ session_id=pinned_session_id,
+ # A routine dictated in conversation is the owner's own words,
+ # so it reaches what they reach unless they said otherwise.
+ # ``None`` is "they did not say", which on a new row is the
+ # default rather than a change to leave alone.
+ grants_credentials=True if grant is None else bool(grant),
+ )
+ if not enabled:
+ return created
+ routine_id = created.id
+ # Already resolved onto the new row; passing them again would
+ # re-validate the same values and, for a one-shot, recompute a
+ # delay against a later now.
+ crons, run_at = None, None
+ if not enabled:
+ return await experts_db().disable_routine(
+ user_id, owner.expert_id, routine_id
+ )
+ return await experts_db().enable_routine(
+ user_id,
+ owner.expert_id,
+ routine_id,
+ prompt=kwargs.get("prompt"),
+ crons=crons,
+ run_at=run_at,
+ session_mode=kwargs.get("session_mode"),
+ # Only read when the mode is PINNED; passed always so the tool
+ # never has to know which modes want it.
+ pinned_session_id=pinned_session_id,
+ # Absent means "leave the grant alone", so rewording a routine
+ # never quietly widens what it can touch.
+ grants_credentials=grant,
+ )
+
+
+def _run_at(delay_seconds: int | None) -> datetime | None:
+ if delay_seconds is None:
+ return None
+ if delay_seconds < _MIN_DELAY_SECONDS:
+ raise ValueError(f"`delay_seconds` must be at least {_MIN_DELAY_SECONDS}.")
+ return datetime.now(timezone.utc) + timedelta(seconds=delay_seconds)
+
+
+def _confirmation(routine: ExpertRoutine) -> str:
+ """What the model should be able to repeat back without checking again."""
+ if not routine.enabled:
+ return f"'{routine.title}' is switched off. Nothing is scheduled for it."
+ reach = (
+ "It can use the owner's connected services."
+ if routine.grants_credentials
+ else "It reaches nothing outside the platform."
+ )
+ where = {
+ "THREAD": "in its own thread",
+ "PINNED": "in the chat it was pinned to",
+ "FRESH": "in a new chat each time",
+ }.get(routine.session_mode, "in its own thread")
+ if routine.crons:
+ when = f"{', '.join(routine.crons)} in the user's timezone"
+ elif routine.run_at is not None:
+ when = f"once at {routine.run_at:%Y-%m-%d %H:%M} UTC"
+ else:
+ when = "at no time it can name"
+ return f"'{routine.title}' is on: {when}, {where}. {reach}"
diff --git a/autogpt_platform/backend/backend/copilot/tools/routines_test.py b/autogpt_platform/backend/backend/copilot/tools/routines_test.py
new file mode 100644
index 0000000000..89f00502e0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/routines_test.py
@@ -0,0 +1,517 @@
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.api.features.experts.models import ExpertRoutine
+from backend.api.features.experts.routines import (
+ RoutineNotFoundError,
+ RoutineUnansweredAsksError,
+)
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse
+from backend.copilot.tools.routines import (
+ ListRoutinesTool,
+ RoutineResponse,
+ RoutinesResponse,
+ ScheduleRoutineTool,
+)
+
+_PATH = "backend.copilot.tools.routines"
+_SCOPE = "backend.copilot.tools.expert_scope"
+
+
+def _routine(**overrides) -> ExpertRoutine:
+ return ExpertRoutine(
+ **{
+ "id": "routine-1",
+ "expert_id": "expert-a",
+ "key": "queue-sweep",
+ "title": "Sweep the queue",
+ "prompt": "Read the queue and stage a draft per item.",
+ "crons": ["H 9 * * 1-5"],
+ "asks": ["Where is the queue?"],
+ "session_mode": "THREAD",
+ "source": "TEMPLATE",
+ "enabled": False,
+ **overrides,
+ }
+ )
+
+
+def experts():
+ db = MagicMock()
+ db.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: (
+ MagicMock(id=expert_id) if expert_id in {"expert-a", "expert-b"} else None
+ )
+ )
+ db.list_routines = AsyncMock(return_value=[_routine()])
+ db.enable_routine = AsyncMock(
+ return_value=_routine(enabled=True, customized=True, crons=["17 9 * * 1-5"])
+ )
+ db.disable_routine = AsyncMock(return_value=_routine())
+ db.create_routine = AsyncMock(
+ return_value=_routine(id="routine-2", key=None, source="OWNER", customized=True)
+ )
+ with (
+ patch(f"{_PATH}.experts_db", return_value=db),
+ patch(f"{_SCOPE}.experts_db", return_value=db),
+ ):
+ yield db
+
+
+def _session(expert_id: str | None) -> ChatSession:
+ return ChatSession.new("user-1", dry_run=False, expert_id=expert_id)
+
+
+async def test_an_expert_lists_its_own_standing_work(experts):
+ result = await ListRoutinesTool()._execute("user-1", _session("expert-a"))
+ assert isinstance(result, RoutinesResponse)
+ assert [r.key for r in result.routines] == ["queue-sweep"]
+ experts.list_routines.assert_awaited_once_with("user-1", "expert-a")
+
+
+async def test_autopilot_naming_nobody_lists_the_accounts_own_routines(experts):
+ """Otto is the default assistant, not a row in Expert, so its standing work
+ hangs off the owner. Refusing here — as the expert-only version did — is
+ what sent the model to ``schedule_followup`` instead."""
+ result = await ListRoutinesTool()._execute("user-1", _session(None))
+ assert isinstance(result, RoutinesResponse)
+ assert result.expert_id is None
+ experts.list_routines.assert_awaited_once_with("user-1", None)
+
+
+async def test_autopilot_may_still_name_one_of_its_experts(experts):
+ await ListRoutinesTool()._execute("user-1", _session(None), expert_id="expert-b")
+ experts.list_routines.assert_awaited_once_with("user-1", "expert-b")
+
+
+async def test_switching_one_on_passes_the_owners_answers_through(experts):
+ """The whole point of the round trip: what reaches the database is the
+ prompt and cadence the owner agreed, not the template's proposal."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the support queue.",
+ crons=["0 10 * * 1-5"],
+ grants_credentials=True,
+ )
+ assert isinstance(result, RoutineResponse)
+ assert result.routine.enabled is True
+ kwargs = experts.enable_routine.await_args.kwargs
+ assert kwargs["prompt"] == "Read the support queue."
+ assert kwargs["crons"] == ["0 10 * * 1-5"]
+ assert kwargs["grants_credentials"] is True
+
+
+async def test_an_omitted_grant_leaves_the_routine_where_it_was(experts):
+ """Omitting the flag must not read as permission, and must not read as
+ revocation either: rewording a routine the owner already bound to their
+ inbox should not quietly unbind it. ``None`` is "leave it alone"."""
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ )
+ assert experts.enable_routine.await_args.kwargs["grants_credentials"] is None
+
+
+async def test_pinning_defaults_to_the_chat_the_routine_was_set_up_in(experts):
+ """THREAD is the default because a daily routine firing into the chat the
+ user is having now buries it; PINNED is for when they asked for that."""
+ session = _session("expert-a")
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ session,
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ session_mode="PINNED",
+ )
+ kwargs = experts.enable_routine.await_args.kwargs
+ assert kwargs["session_mode"] == "PINNED"
+ assert kwargs["pinned_session_id"] == session.session_id
+
+
+async def test_pinning_can_name_another_chat_the_owner_holds(experts):
+ """The one thing ``schedule_followup`` could do that a routine could not:
+ land in a conversation other than the one being had now."""
+ target = MagicMock(expert_id="expert-a")
+ with patch(f"{_PATH}.get_chat_session", AsyncMock(return_value=target)):
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ session_mode="PINNED",
+ session_id="other-session",
+ )
+ assert experts.enable_routine.await_args.kwargs["pinned_session_id"] == (
+ "other-session"
+ )
+
+
+async def test_a_chat_in_another_experts_scope_cannot_be_pinned(experts):
+ """A routine aimed at another persona's thread would write that expert's
+ memory under this one's prompt, every run, unattended."""
+ with patch(
+ f"{_PATH}.get_chat_session",
+ AsyncMock(return_value=MagicMock(expert_id="expert-b")),
+ ):
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ session_mode="PINNED",
+ session_id="someone-elses",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "session_not_found"
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_a_chat_that_is_not_the_callers_cannot_be_pinned(experts):
+ with patch(f"{_PATH}.get_chat_session", AsyncMock(return_value=None)):
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ session_mode="PINNED",
+ session_id="not-mine",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "session_not_found"
+
+
+async def test_unanswered_asks_come_back_as_the_questions_to_ask(experts):
+ """The model has to be told what is missing, or it cannot close the gap
+ with the user — a bare refusal would just stall."""
+ experts.enable_routine.side_effect = RoutineUnansweredAsksError(
+ "'Sweep the queue' needs answers before it can run: Where is the queue?"
+ )
+ result = await ScheduleRoutineTool()._execute(
+ "user-1", _session("expert-a"), routine_id="routine-1", enabled=True
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "unanswered_asks"
+ assert "Where is the queue?" in result.message
+
+
+async def test_switching_one_off_keeps_the_row(experts):
+ result = await ScheduleRoutineTool()._execute(
+ "user-1", _session("expert-a"), routine_id="routine-1", enabled=False
+ )
+ assert isinstance(result, RoutineResponse)
+ assert result.routine.enabled is False
+ experts.disable_routine.assert_awaited_once_with("user-1", "expert-a", "routine-1")
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_an_expert_records_standing_work_it_agreed_in_conversation(experts):
+ """No routine_id means there was no proposal — a raised expert has no
+ template, so this is the only way it gets any standing work at all."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ enabled=False,
+ title="Morning triage",
+ prompt="Read overnight tickets and rank them.",
+ crons=["H 8 * * 1-5"],
+ session_mode="FRESH",
+ )
+ assert isinstance(result, RoutineResponse)
+ kwargs = experts.create_routine.await_args.kwargs
+ assert kwargs["title"] == "Morning triage"
+ assert kwargs["crons"] == ["H 8 * * 1-5"]
+ assert kwargs["session_mode"] == "FRESH"
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_work_the_owner_dictated_reaches_what_they_reach(experts):
+ """The provenance rule, at the point it is decided: a prompt the owner
+ spoke is not a template, so it is not muted like one."""
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ enabled=False,
+ title="Morning triage",
+ prompt="Read overnight tickets.",
+ crons=["H 8 * * 1-5"],
+ )
+ kwargs = experts.create_routine.await_args.kwargs
+ assert kwargs["grants_credentials"] is True
+
+
+async def test_the_owner_can_still_ask_for_one_that_touches_nothing(experts):
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ enabled=False,
+ title="Morning triage",
+ prompt="Read overnight tickets.",
+ crons=["H 8 * * 1-5"],
+ grants_credentials=False,
+ )
+ assert experts.create_routine.await_args.kwargs["grants_credentials"] is False
+
+
+async def test_a_one_shot_is_recorded_as_a_time_not_a_cadence(experts):
+ """ "Check the deploy in an hour" gets a row like anything else, so it can
+ be listed, reworded and cancelled rather than living only as a job."""
+ before = datetime.now(timezone.utc)
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ enabled=True,
+ title="Check the deploy",
+ prompt="Check whether the deploy finished.",
+ delay_seconds=3600,
+ )
+ kwargs = experts.create_routine.await_args.kwargs
+ assert kwargs["crons"] is None
+ assert kwargs["run_at"] is not None
+ assert (kwargs["run_at"] - before).total_seconds() == pytest.approx(3600, abs=30)
+
+
+async def test_a_delay_shorter_than_the_followup_minimum_is_refused(experts):
+ """Kept identical to ``schedule_followup`` so the two cannot disagree about
+ what the soonest deferral is."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ enabled=True,
+ title="Too soon",
+ prompt="Now-ish.",
+ delay_seconds=5,
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "invalid_schedule"
+ experts.create_routine.assert_not_awaited()
+
+
+async def test_creating_and_switching_on_together_enables_the_new_row(experts):
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ enabled=True,
+ title="Morning triage",
+ prompt="Read overnight tickets.",
+ crons=["H 8 * * 1-5"],
+ )
+ experts.create_routine.assert_awaited_once()
+ # The id enabled is the one just created, never the caller's.
+ assert experts.enable_routine.await_args.args[2] == "routine-2"
+ # The cadence was resolved onto the new row a moment ago; re-sending it
+ # would re-validate the same values and, for a one-shot, recompute the
+ # delay against a later now.
+ assert experts.enable_routine.await_args.kwargs["crons"] is None
+ assert experts.enable_routine.await_args.kwargs["run_at"] is None
+
+
+async def test_a_call_naming_neither_a_routine_nor_a_title_is_refused(experts):
+ result = await ScheduleRoutineTool()._execute(
+ "user-1", _session("expert-a"), enabled=True
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_routine"
+ experts.create_routine.assert_not_awaited()
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_an_expert_cannot_reach_a_teammates_routines(experts):
+ """``resolve_routine_owner``'s rule, which these tools inherit: an expert
+ acts on itself and may not name another."""
+ result = await ListRoutinesTool()._execute(
+ "user-1", _session("expert-a"), expert_id="expert-b"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+ experts.list_routines.assert_not_awaited()
+
+
+async def test_an_expert_that_is_not_on_the_account_is_not_found(experts):
+ result = await ListRoutinesTool()._execute(
+ "user-1", _session(None), expert_id="expert-z"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "expert_not_found"
+
+
+async def test_a_routine_id_from_another_account_is_not_found(experts):
+ experts.enable_routine.side_effect = RoutineNotFoundError("routine-1")
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Mine now.",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "routine_not_found"
+
+
+async def test_an_invalid_cadence_is_reported_rather_than_raised(experts):
+ experts.enable_routine.side_effect = ValueError("bad cron")
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ crons=["not a cron"],
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "invalid_schedule"
+
+
+async def test_an_unauthenticated_call_is_refused_before_any_lookup(experts):
+ result = await ScheduleRoutineTool()._execute(
+ None, _session("expert-a"), routine_id="routine-1", enabled=True
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_the_confirmation_states_what_the_routine_may_reach(experts):
+ """The model repeats this back, so it has to carry the two things an owner
+ would want to check: when it runs, and whether it can touch their accounts."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ )
+ assert isinstance(result, RoutineResponse)
+ assert "17 9 * * 1-5" in result.message
+ assert "reaches nothing outside the platform" in result.message
+
+
+async def test_the_confirmation_of_a_one_shot_names_its_time(experts):
+ experts.enable_routine.return_value = _routine(
+ enabled=True,
+ crons=[],
+ run_at=datetime(2026, 9, 20, 14, 30, tzinfo=timezone.utc),
+ )
+ result = await ScheduleRoutineTool()._execute(
+ "user-1", _session("expert-a"), routine_id="routine-1", enabled=True
+ )
+ assert isinstance(result, RoutineResponse)
+ assert "2026-09-20 14:30" in result.message
+
+
+async def test_autopilot_pinning_an_experts_routine_must_name_that_experts_chat(
+ experts,
+):
+ """Personal AutoPilot is in no expert scope, so "this chat" is the wrong
+ default when it manages an expert's routine: the chat it would pin belongs
+ to Otto, and the fire path refuses it on every run — deleting the schedule
+ and leaving a routine that says it is on with nothing behind it."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ expert_id="expert-a",
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ session_mode="PINNED",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "session_required"
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_autopilot_may_pin_an_experts_routine_to_that_experts_chat(experts):
+ with patch(
+ f"{_PATH}.get_chat_session",
+ AsyncMock(return_value=MagicMock(expert_id="expert-a")),
+ ):
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ expert_id="expert-a",
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ session_mode="PINNED",
+ session_id="an-expert-a-chat",
+ )
+ assert experts.enable_routine.await_args.kwargs["pinned_session_id"] == (
+ "an-expert-a-chat"
+ )
+
+
+async def test_autopilot_pinning_its_own_routine_still_defaults_to_this_chat(experts):
+ """The account's own standing work is in the account's own scope, so the
+ default is right there and only there."""
+ session = _session(None)
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ session,
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ session_mode="PINNED",
+ )
+ assert experts.enable_routine.await_args.kwargs["pinned_session_id"] == (
+ session.session_id
+ )
+
+
+async def test_autopilot_can_manage_an_experts_thread_routine_without_a_session(
+ experts,
+):
+ """The regression the PINNED scope check introduced. THREAD has no chat to
+ name, so requiring one refused the ordinary case outright: personal
+ AutoPilot switching on an expert's routine, which is most of the flow."""
+ result = await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ expert_id="expert-a",
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Read the queue.",
+ )
+ assert isinstance(result, RoutineResponse)
+ experts.enable_routine.assert_awaited_once()
+ assert experts.enable_routine.await_args.kwargs["pinned_session_id"] is None
+
+
+async def test_autopilot_can_create_an_experts_fresh_routine_without_a_session(
+ experts,
+):
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session(None),
+ expert_id="expert-a",
+ enabled=False,
+ title="Morning triage",
+ prompt="Read overnight tickets.",
+ crons=["H 8 * * 1-5"],
+ session_mode="FRESH",
+ )
+ experts.create_routine.assert_awaited_once()
+ assert experts.create_routine.await_args.kwargs["session_id"] is None
+
+
+async def test_omitting_the_mode_does_not_re_pin_a_routine_to_this_chat(experts):
+ """An omitted `session_mode` means "leave it as it is". Answering with the
+ caller's chat would move an already-pinned routine into whatever
+ conversation happened to reword it."""
+ await ScheduleRoutineTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Reworded, nothing else.",
+ )
+ assert experts.enable_routine.await_args.kwargs["pinned_session_id"] is None
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
index df717d16c6..f3bff0067f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
@@ -10,12 +10,16 @@ The ``session_id`` argument decides WHERE the follow-up lands:
At fire time the scheduler creates a new copilot session in the same
Otto or expert scope and routes the turn into it (no prior
conversation context).
- Use this for recurring "morning brief" / "daily digest" patterns
- where a clean slate is preferred over polluting the current chat.
+ Use this only where a clean slate is genuinely wanted: the turn
+ starts with no idea what the last one found or said, which for a
+ recurring job means no dedupe and no "third time this week".
* A specific session UUID — the follow-up resumes that session with
- full history. This is the right value for "remind me here in 20
- minutes": the model reads the current ``session_id`` from the
+ full history. Right for "remind me here in 20 minutes", and right
+ for a recurring routine that has to remember its own last run:
+ the two axes are independent and pinning a repeating follow-up to
+ one thread is a supported, common shape. The model reads the
+ current ``session_id`` from the
trusted ``<session_context>`` block injected on every turn and
passes it back verbatim. Ownership and persona scope are validated —
UUIDs belonging to other users or another expert are rejected as
@@ -71,21 +75,19 @@ class ScheduleFollowupTool(BaseTool):
def description(self) -> str:
return (
"Schedule a copilot follow-up turn. The 'message' is sent "
- "at the scheduled time. The 'session_id' arg picks the "
- "destination: OMIT IT (or pass null) to fire into a brand-"
- "new chat created at fire-time in this chat's same Otto "
- "or expert memory scope — best for daily briefs / recurring "
- "digests / anything that should start fresh. "
- "Pass an existing 'session_id' (you can read the current "
- "one from the trusted <session_context> block) to resume "
- "that conversation with its full history (the target must use "
- "the same Otto or expert scope) — best for "
- "'remind me here in 20 minutes'. Use 'delay_seconds' for "
- "one-shot followups ('in 20 minutes', 'at 7am tomorrow' — "
- "convert absolute times to a delay) or 'cron' for "
- "recurring schedules ('every Monday at 9am'). After "
- "calling this tool your turn ends — send your final user-"
- "facing message before calling."
+ "at the scheduled time. Two independent choices: WHEN, and "
+ "WHERE. WHEN: 'delay_seconds' fires once ('in 20 minutes', "
+ "'at 7am tomorrow' — convert an absolute time to a delay); "
+ "'cron' repeats ('every Monday at 9am'). WHERE: omit "
+ "'session_id' to fire into a brand-new chat each time, or "
+ "pass one (the current chat's id is in the trusted "
+ "<session_context> block) to land in that conversation with "
+ "its full history. Every combination is valid — a recurring "
+ "follow-up pinned to one thread is how a daily routine "
+ "remembers what it said yesterday, and is usually what "
+ "somebody means by a standing digest. After calling this "
+ "tool your turn ends — send your final user-facing message "
+ "before calling."
)
@property
@@ -125,13 +127,17 @@ class ScheduleFollowupTool(BaseTool):
"session_id": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"description": (
- "Target session UUID. OMIT or null = create a "
- "brand-new chat at fire-time in the current "
- "Otto or expert memory scope (no prior context). "
- "Pass the current session's id from <session_"
- "context> to fire into THIS chat with full "
- "history. Sessions owned by other users or in a "
- "different expert scope are rejected as "
+ "Where the follow-up lands; independent of "
+ "whether it repeats. OMIT or null = a brand-new "
+ "chat at every fire, in the current Otto or "
+ "expert memory scope, with no prior context — "
+ "choose this only when each run should start "
+ "clean. Pass a session id (the current one is in "
+ "<session_context>) to fire into that chat with "
+ "its full history, which is what lets a repeating "
+ "follow-up build on its own past runs instead of "
+ "repeating itself. Sessions owned by other users "
+ "or in a different expert scope are rejected as "
"'session_not_found'."
),
},
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 42a31f92bd..e643f7e3c4 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -217,7 +217,24 @@ from ._test_data import make_session
# + #14207 multi-expert-teams +981 71,751 (86 tools)
# consult_teammate has measured +981 at every dev tip since 2026-09-09; what
# moves this line is dev, not this branch.
-_CHAR_BUDGET = 73_030
+# Bumped 73_030 -> 75_260 for the two tools this PR adds: set_expert_routine
+# measures 1,823 (nine parameters, because it both creates standing work and
+# switches it on, and because the modes and the credential grant are each a
+# decision the owner makes out loud) and list_expert_routines 403. Measured on
+# the branch merged with dev, plus one — this line carries no margin by design.
+# Bumped 75_261 -> 75_693 in the same PR, for two arguments those tools grew:
+# `delay_seconds` (a routine can now be a one-shot, so the durable record
+# covers "check the deploy at six" and not only work that repeats) and
+# `session_id` (PINNED can name any chat the owner holds, which is the one
+# thing schedule_followup could do that a routine could not). Every other
+# description in both tools was cut first — that paid back 377 of the 808 —
+# so what is left here is the two new arguments, not wording. Measured on the
+# branch merged with dev at 75,692, plus one.
+# Bumped 75_693 -> 75_839 after merging dev, which reworded `raise_expert`,
+# `setup_agent_webhook_trigger` and `run_agent` — no tool was added and this
+# branch's own delta did not move. Re-measured on the merged tree at 75,838,
+# plus one, per the rule above about measuring on the merge ref.
+_CHAR_BUDGET = 75_839
@pytest.fixture(scope="module")
@@ -372,7 +389,17 @@ def test_total_schema_char_budget() -> None:
# ON CONFLICT, KEEP THE HIGHER VALUE — same rule, same reason: each branch's
# CI measures only its own delta while the ceiling has to cover every in-flight
# PR together. MEASURE ON THE PR'S MERGE REF, never the branch tip.
-_SESSION_WIRE_BUDGET = 65_630
+# Raised 65_630 -> 67_767 for the same two tools. They ride the
+# ``expert_resources`` group, so they are declared in every session that can
+# manage an expert's resources — which is the largest one. Measured 67,767,
+# plus one.
+# Raised 67_768 -> 68_188 for the same two arguments as ``_CHAR_BUDGET`` above;
+# both tools are in that largest session, so the whole delta lands here too.
+# Measured 68,187, plus one.
+# Raised 68_188 -> 68_329 for the same dev rewordings; all three tools are in
+# the largest session, so the whole delta lands here too. Measured 68,328,
+# plus one.
+_SESSION_WIRE_BUDGET = 68_329
def test_largest_declared_session_wire_budget() -> None:
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index c05b40969e..e15758605e 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, TypeVar, cas
from backend.api.features.experts import credentials as expert_credentials
from backend.api.features.experts import experts_db
+from backend.api.features.experts import routine_jobs as experts_routine_jobs
from backend.api.features.experts import scheduling as experts_scheduling
from backend.api.features.experts import spend_approval as experts_spend_approval
from backend.api.features.library.db import (
@@ -531,6 +532,16 @@ class DatabaseManager(AppService):
resolve_attributable_expert = _(experts_db.resolve_attributable_expert)
list_experts = _(experts_db.list_experts)
resolve_private_expert_tenancy = _(experts_db.resolve_private_expert_tenancy)
+ # The scheduler's fire path reads the routine behind a copilot-turn job to
+ # find its durable thread and whether the owner granted it anything.
+ create_routine = _(experts_db.create_routine)
+ list_routines = _(experts_db.list_routines)
+ enable_routine = _(experts_db.enable_routine)
+ disable_routine = _(experts_db.disable_routine)
+ get_routine = _(experts_db.get_routine)
+ record_routine_thread = _(experts_routine_jobs.record_routine_thread)
+ record_routine_fired = _(experts_routine_jobs.record_routine_fired)
+ mark_routine_unscheduled = _(experts_routine_jobs.mark_routine_unscheduled)
enforce_expert_run_budget = _(experts_scheduling.enforce_expert_run_budget)
spend_approval_required = _(experts_spend_approval.spend_approval_required)
park_execution_for_spend_approval = _(
@@ -930,6 +941,14 @@ class DatabaseManagerAsyncClient(AppServiceClient):
resolve_attributable_expert = d.resolve_attributable_expert
list_experts = d.list_experts
resolve_private_expert_tenancy = d.resolve_private_expert_tenancy
+ get_routine = d.get_routine
+ record_routine_thread = d.record_routine_thread
+ record_routine_fired = d.record_routine_fired
+ mark_routine_unscheduled = d.mark_routine_unscheduled
+ create_routine = d.create_routine
+ list_routines = d.list_routines
+ enable_routine = d.enable_routine
+ disable_routine = d.disable_routine
enforce_expert_run_budget = d.enforce_expert_run_budget
spend_approval_required = d.spend_approval_required
park_execution_for_spend_approval = d.park_execution_for_spend_approval
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 337c73c3a6..d6115e1b19 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -27,6 +27,7 @@ from dotenv import load_dotenv
from pydantic import BaseModel, Field, ValidationError
from sqlalchemy import MetaData, create_engine
+from backend.api.features.experts.models import ExpertRoutine
from backend.copilot.active_turns import ConcurrentTurnLimitError
from backend.copilot.dream.scheduling import (
COMMUNITY_REBUILD_REGISTRATION_PREFIX,
@@ -37,6 +38,7 @@ from backend.copilot.executor.utils import schedule_turn
from backend.copilot.graphiti.communities import rebuild_communities_for_user
from backend.copilot.model import create_chat_session, get_chat_session
from backend.copilot.optimize_blocks import optimize_block_descriptions
+from backend.copilot.permissions import CopilotPermissions, routine_disabled_tools
from backend.copilot.transports import resolve_default_chat_route
from backend.data.db_accessors import experts_db
from backend.data.execution import ExecutionTrigger, GraphExecutionWithNodes
@@ -349,9 +351,70 @@ async def _skip_inactive_expert_scope(
await _reschedule_one_shot_after_expert_unavailable(args)
+async def _routine_for_turn(args: "CopilotTurnJobArgs") -> ExpertRoutine | None:
+ """Load the routine behind this job, if it is one.
+
+ A failed lookup returns ``None``, which is the cautious side of both
+ decisions it feeds: the turn lands in a fresh chat rather than one it
+ cannot confirm belongs to this routine, and it runs muted rather than
+ assuming an owner granted it anything.
+ """
+ if args.routine_id is None:
+ return None
+ try:
+ routine = await experts_db().get_routine(args.routine_id)
+ except Exception:
+ logger.warning(
+ "Could not load routine %s for scheduled turn %s; "
+ "firing into a fresh chat with nothing granted",
+ args.routine_id[:12],
+ args.schedule_id,
+ exc_info=True,
+ )
+ return None
+ return routine
+
+
+def _routine_turn_permissions(routine: ExpertRoutine | None) -> CopilotPermissions:
+ """The capability filter a routine's turn runs under.
+
+ Every routine turn gets one, even a fully granted one: no routine may
+ schedule more of itself, because nobody is watching this turn read the page
+ that might ask it to. Passing ``None`` would mean "whatever the session
+ allows", and the point of this object is that the decision is made here, at
+ the boundary, and is visible in the job.
+
+ A routine loaded as ``None`` — the row is gone, or the lookup failed — is
+ treated as ungranted, which is the right way to be wrong.
+ """
+ granted = routine is not None and routine.grants_credentials
+ return CopilotPermissions(tools=sorted(routine_disabled_tools(granted=granted)))
+
+
async def _execute_copilot_turn(**kwargs):
expert_scope_was_persisted = "expert_id" in kwargs
args = CopilotTurnJobArgs(**kwargs)
+ routine = await _routine_for_turn(args)
+ if routine is not None and not routine.enabled:
+ # Deleting a routine's jobs is best effort — the scheduler can refuse,
+ # and a spent one-shot's row outlives its job either way. So "off" has
+ # to mean something at fire time too, or a job that survived being
+ # switched off keeps running work its owner stopped. This is the
+ # fire-time lookup ``delete_routine_schedules`` defers to.
+ logger.info(
+ "Copilot turn schedule %s skipped — routine %s is switched off; "
+ "removing the schedule that outlived it",
+ args.schedule_id,
+ routine.id[:12],
+ )
+ await _self_delete_copilot_turn_schedule(args)
+ return
+ # A THREAD routine keeps one durable conversation: null until its first
+ # fire mints it, reused by every fire after. Resolving it here means the
+ # second fire takes the existing-session branch below and inherits that
+ # branch's ownership and scope re-validation for free.
+ if routine is not None and routine.session_id is not None:
+ args = args.model_copy(update={"session_id": routine.session_id})
start_time = asyncio.get_event_loop().time()
try:
# Resolve the target session. ``session_id=None`` means "fire into
@@ -410,6 +473,22 @@ async def _execute_copilot_turn(**kwargs):
return
target_session_id = new_session.session_id
target_session = new_session
+ if routine is not None and routine.session_mode == "THREAD":
+ # First fire of a THREAD routine: remember the conversation so
+ # every later fire continues it instead of leaving a trail of
+ # one-message chats. Best effort — losing this costs a thread,
+ # not a run, and the next fire mints a fresh one.
+ try:
+ await experts_db().record_routine_thread(
+ routine.id, target_session_id
+ )
+ except Exception:
+ logger.warning(
+ "Could not record thread %s on routine %s",
+ target_session_id[:12],
+ routine.id[:12],
+ exc_info=True,
+ )
# Nothing can be forged in a chat that has never existed before:
# its ``origin="automation"`` refuses the staffing tools outright,
# so no proposal can be parked here to approve. Persist the opener
@@ -476,7 +555,29 @@ async def _execute_copilot_turn(**kwargs):
team_id=args.team_id,
llm_auth_provider=target_session.metadata.llm_auth_provider,
llm_credential_id=target_session.metadata.llm_credential_id,
+ # Per turn, not per session: a PINNED routine fires into a chat the
+ # user also drives themselves, and muting the conversation would
+ # take capabilities away from the person sitting in it. What is
+ # unattended is this turn.
+ permissions=(
+ _routine_turn_permissions(routine)
+ if args.routine_id is not None
+ else None
+ ),
)
+ if routine is not None and routine.run_at is not None:
+ # APScheduler drops a one-shot job once it fires, so without this
+ # the row would go on describing itself as scheduled for a time
+ # that has passed. After dispatch, not before: a turn that never
+ # reached the queue has not run.
+ try:
+ await experts_db().record_routine_fired(routine.id)
+ except Exception:
+ logger.warning(
+ "Could not mark one-shot routine %s fired",
+ routine.id[:12],
+ exc_info=True,
+ )
product_analytics.track_schedule_fired(
user_id=args.user_id,
schedule_id=args.schedule_id,
@@ -611,6 +712,12 @@ async def _reschedule_one_shot(
# turn into a plain session, escaping the expert's thread/budget
# and its isolated memory scope.
expert_id=args.expert_id,
+ # And for the routine behind it. Dropping this was the worst of
+ # the three: the retried turn resolves no routine, so it runs
+ # with the session's own permissions instead of the routine's —
+ # an ungranted routine that merely lost a race to the concurrency
+ # cap would come back with everything the mute exists to withhold.
+ routine_id=args.routine_id,
)
logger.info(
f"Rescheduled one-shot copilot turn for session "
@@ -673,6 +780,23 @@ async def _self_delete_copilot_turn_schedule(args: "CopilotTurnJobArgs") -> None
args.user_id,
reason="session unavailable or scope mismatch",
)
+ # A job with no schedule_id predates the field and cannot be matched
+ # against the ids a routine row holds, so there is nothing to drop.
+ if args.routine_id is None or args.schedule_id is None:
+ return
+ # The row outlives the job it lost, and a routine still listed as switched
+ # on with nothing scheduled behind it is the one state the owner cannot act
+ # on: the UI offers to switch off something that is already not running.
+ # Most often this is a PINNED routine whose chat the owner deleted.
+ try:
+ await experts_db().mark_routine_unscheduled(args.routine_id, args.schedule_id)
+ except Exception:
+ logger.warning(
+ "Could not switch off routine %s after removing its schedule %s",
+ args.routine_id[:12],
+ args.schedule_id,
+ exc_info=True,
+ )
async def _handle_graph_validation_error(args: "GraphExecutionJobArgs") -> None:
@@ -1536,6 +1660,12 @@ class CopilotTurnJobArgs(BaseModel):
# and Otto follow-ups in the user's account scope. Optional for
# backward compat with rows persisted before this field was added.
expert_id: str | None = None
+ # Set when this job is one fire time of an ``ExpertRoutine``. The row is
+ # what makes a routine more than a followup: it owns the durable thread a
+ # THREAD routine reuses (minted here on the first fire) and the flag that
+ # decides whether the turn may touch a connected service at all. None keeps
+ # ordinary ``schedule_followup`` jobs on their existing path.
+ routine_id: str | None = None
def _timezone_from_job(job_obj: JobObj) -> str:
@@ -2158,6 +2288,7 @@ class Scheduler(AppService):
organization_id: str | None = None,
team_id: str | None = None,
expert_id: str | None = None,
+ routine_id: str | None = None,
) -> CopilotTurnJobInfo:
"""Schedule a copilot turn at a future time.
@@ -2194,6 +2325,7 @@ class Scheduler(AppService):
organization_id=organization_id,
team_id=team_id,
expert_id=expert_id,
+ routine_id=routine_id,
)
default_name = (
f"copilot turn (session {session_id[:8]})"
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 99b1b5a7e9..1350b30791 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -15,6 +15,11 @@ import pytest
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
+from backend.api.features.experts.models import ExpertRoutine
+from backend.copilot.permissions import (
+ CAPABILITY_GATE_NAMES,
+ ROUTINE_SELF_ESCALATION_TOOLS,
+)
from backend.executor.scheduler import (
_MAX_CAP_RETRIES,
_MAX_EXPERT_LOOKUP_RETRIES,
@@ -33,6 +38,7 @@ from backend.executor.scheduler import (
_next_run_time_iso,
_reschedule_one_shot_after_cap,
_reschedule_one_shot_after_expert_unavailable,
+ _routine_turn_permissions,
_self_delete_copilot_turn_schedule,
_self_delete_morning_briefing_schedule,
reconcile_stripe_tiers,
@@ -1993,3 +1999,178 @@ def test_graph_schedule_listing_can_include_paused_jobs():
sched.get_graph_execution_schedules(user_id="other", include_paused=True)
== []
)
+
+
+class TestRoutineTurnPermissions:
+ """What a routine's unattended turn is allowed to do.
+
+ This is the single decision the whole safety story rests on, and it is
+ made here rather than in the session, so it is worth pinning directly
+ instead of only through the set that feeds it.
+ """
+
+ @staticmethod
+ def _routine(**overrides) -> ExpertRoutine:
+ return ExpertRoutine(
+ **{
+ "id": "routine-1",
+ "title": "Sweep the queue",
+ "prompt": "Read the queue.",
+ "crons": ["0 9 * * 1-5"],
+ "source": "TEMPLATE",
+ "grants_credentials": False,
+ **overrides,
+ }
+ )
+
+ def _denied(self, routine: ExpertRoutine | None) -> set[str]:
+ return set(_routine_turn_permissions(routine).tools)
+
+ def test_a_template_routine_reaches_nothing_outside_the_platform(self):
+ denied = self._denied(self._routine())
+
+ assert "run_agent" in denied
+ assert "post_to_chat_platform" in denied
+ assert CAPABILITY_GATE_NAMES <= denied
+
+ def test_granting_a_template_routine_is_the_owners_call_and_it_counts(self):
+ """The grant is the whole rule at fire time. A template the owner
+ looked at and bound to their queue must actually reach it, or the
+ question they were asked meant nothing."""
+ denied = self._denied(self._routine(grants_credentials=True))
+
+ assert "run_agent" not in denied
+ assert not CAPABILITY_GATE_NAMES & denied
+
+ def test_a_routine_the_owner_dictated_is_not_muted_like_a_template(self):
+ """``create_routine`` grants an OWNER row by default, which is what
+ settles the complaint this came from: the same words typed into the
+ same chat already run with these, so muting somebody's own morning
+ briefing protected nobody. Fire time reads only the grant — provenance
+ is what decided the grant's starting value."""
+ denied = self._denied(self._routine(source="OWNER", grants_credentials=True))
+
+ assert "run_agent" not in denied
+ assert not CAPABILITY_GATE_NAMES & denied
+
+ def test_an_owner_who_asked_for_hands_off_still_gets_hands_off(self):
+ denied = self._denied(self._routine(source="OWNER", grants_credentials=False))
+
+ assert "run_agent" in denied
+
+ @pytest.mark.parametrize(
+ "routine",
+ [
+ None,
+ _routine.__func__(),
+ _routine.__func__(source="OWNER", grants_credentials=True),
+ ],
+ )
+ def test_no_routine_turn_may_schedule_another(self, routine):
+ """An unattended turn reads pages nobody is watching it read. Without
+ this, one injected page buys standing access to the account forever —
+ a routine that can write a routine can grant itself the credentials
+ its own prompt was denied."""
+ denied = set(_routine_turn_permissions(routine).tools)
+
+ assert ROUTINE_SELF_ESCALATION_TOOLS <= denied
+
+ def test_a_routine_that_could_not_be_loaded_is_trusted_least(self):
+ """The row is gone or the lookup failed; the turn still fires, and
+ guessing that it was granted something is the wrong way to be wrong."""
+ denied = self._denied(None)
+
+ assert "run_agent" in denied
+ assert CAPABILITY_GATE_NAMES <= denied
+
+ def test_the_filter_is_always_a_denylist_never_an_empty_one(self):
+ """``effective_allowed_tools`` reads an empty ``tools`` as "everything
+ allowed", so a filter that narrowed to nothing would silently widen."""
+ for routine in (None, self._routine(), self._routine(source="OWNER")):
+ permissions = _routine_turn_permissions(routine)
+ assert permissions.tools
+ assert permissions.tools_exclude is True
+
+
+async def test_reschedule_after_cap_keeps_the_routine_behind_the_turn():
+ """The retried job has to still be a routine's.
+
+ Without ``routine_id`` the replacement resolves no routine, so
+ ``_execute_copilot_turn`` passes ``permissions=None`` and the turn runs
+ with whatever the session allows. An ungranted routine that merely lost a
+ race to the concurrency cap would come back holding everything the mute
+ exists to withhold — and it would never be marked as having fired.
+ """
+ args = _args(cap_retry_count=0, routine_id="routine-1")
+ mock_client = AsyncMock()
+ with patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=mock_client):
+ await _reschedule_one_shot_after_cap(args)
+
+ assert (
+ mock_client.add_copilot_turn_schedule.call_args.kwargs["routine_id"]
+ == "routine-1"
+ )
+
+
+async def test_a_switched_off_routine_does_not_fire_and_its_job_is_removed():
+ """Deleting a routine's jobs is best effort, so "off" has to mean
+ something at fire time too. Otherwise a job the scheduler refused to
+ delete keeps running work its owner stopped, forever."""
+ args = _args(routine_id="routine-1")
+ off = ExpertRoutine(
+ id="routine-1",
+ title="Stopped",
+ prompt="Read it.",
+ crons=["0 9 * * 1"],
+ enabled=False,
+ )
+ schedule_turn = AsyncMock()
+ self_delete = AsyncMock()
+ db = MagicMock()
+ db.get_routine = AsyncMock(return_value=off)
+
+ with (
+ patch(f"{_SCHEDULER_PATH}.experts_db", return_value=db),
+ patch(f"{_SCHEDULER_PATH}.schedule_turn", schedule_turn),
+ patch(f"{_SCHEDULER_PATH}._self_delete_copilot_turn_schedule", self_delete),
+ ):
+ await _execute_copilot_turn(**args.model_dump())
+
+ schedule_turn.assert_not_awaited()
+ self_delete.assert_awaited_once()
+
+
+async def test_a_switched_on_routine_still_fires():
+ """The guard above must not be the thing that stops every routine."""
+ args = _args(routine_id="routine-1")
+ on = ExpertRoutine(
+ id="routine-1",
+ title="Running",
+ prompt="Read it.",
+ crons=["0 9 * * 1"],
+ enabled=True,
+ )
+ schedule_turn = AsyncMock()
+ self_delete = AsyncMock()
+ db = MagicMock()
+ db.get_routine = AsyncMock(return_value=on)
+ db.record_routine_fired = AsyncMock()
+ session = MagicMock(
+ session_id="session-1",
+ expert_id=None,
+ metadata=MagicMock(llm_auth_provider=None, llm_credential_id=None),
+ )
+
+ with (
+ patch(f"{_SCHEDULER_PATH}.experts_db", return_value=db),
+ patch(f"{_SCHEDULER_PATH}.schedule_turn", schedule_turn),
+ patch(f"{_SCHEDULER_PATH}._self_delete_copilot_turn_schedule", self_delete),
+ patch(f"{_SCHEDULER_PATH}.get_chat_session", AsyncMock(return_value=session)),
+ ):
+ await _execute_copilot_turn(**args.model_dump())
+
+ schedule_turn.assert_awaited_once()
+ self_delete.assert_not_awaited()
diff --git a/autogpt_platform/backend/migrations/20260917120000_add_expert_routine/migration.sql b/autogpt_platform/backend/migrations/20260917120000_add_expert_routine/migration.sql
new file mode 100644
index 0000000000..56ca8db891
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260917120000_add_expert_routine/migration.sql
@@ -0,0 +1,51 @@
+-- CreateEnum
+CREATE TYPE "ExpertRoutineSession" AS ENUM ('FRESH', 'PINNED', 'THREAD');
+
+-- CreateEnum
+CREATE TYPE "ExpertRoutineSource" AS ENUM ('TEMPLATE', 'OWNER');
+
+-- CreateTable
+CREATE TABLE "ExpertRoutine" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "expertId" TEXT,
+ "userId" TEXT,
+ "key" TEXT,
+ "title" TEXT NOT NULL,
+ "prompt" TEXT NOT NULL,
+ "crons" TEXT[],
+ "asks" TEXT[],
+ "sessionMode" "ExpertRoutineSession" NOT NULL DEFAULT 'THREAD',
+ "sessionId" TEXT,
+ "source" "ExpertRoutineSource" NOT NULL DEFAULT 'TEMPLATE',
+ "runAt" TIMESTAMP(3),
+ "firedAt" TIMESTAMP(3),
+ "scheduleIds" TEXT[],
+ "enabledAt" TIMESTAMP(3),
+ "customizedAt" TIMESTAMP(3),
+ "grantsCredentials" BOOLEAN NOT NULL DEFAULT false,
+ "pausedByExpertArchive" BOOLEAN NOT NULL DEFAULT false,
+
+ CONSTRAINT "ExpertRoutine_pkey" PRIMARY KEY ("id"),
+ -- Exactly one owner. Prisma cannot express this, so both columns are
+ -- nullable in the schema and every reader has to trust the invariant;
+ -- stated here it is the database's job. A row with both owners would be
+ -- reachable from two scopes at once, and a row with neither would be
+ -- reachable from none while still firing.
+ CONSTRAINT "ExpertRoutine_one_owner" CHECK (("expertId" IS NULL) <> ("userId" IS NULL))
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "ExpertRoutine_expertId_key_key" ON "ExpertRoutine"("expertId", "key");
+
+-- CreateIndex
+CREATE INDEX "ExpertRoutine_expertId_createdAt_id_idx" ON "ExpertRoutine"("expertId", "createdAt", "id");
+
+-- CreateIndex
+CREATE INDEX "ExpertRoutine_userId_createdAt_id_idx" ON "ExpertRoutine"("userId", "createdAt", "id");
+
+-- AddForeignKey
+ALTER TABLE "ExpertRoutine" ADD CONSTRAINT "ExpertRoutine_expertId_fkey" FOREIGN KEY ("expertId") REFERENCES "Expert"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ExpertRoutine" ADD CONSTRAINT "ExpertRoutine_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 3c89f90e30..2e193b5526 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -156,6 +156,7 @@ model User {
LibraryFolders LibraryFolder[]
OwnedExperts Expert[]
ExpertPods ExpertPod[]
+ ExpertRoutines ExpertRoutine[]
Profile Profile[]
UserOnboarding UserOnboarding?
@@ -166,7 +167,7 @@ model User {
StoreListingReviews StoreListingReview[]
StoreVersionsReviewed StoreListingVersion[]
SkillListings SkillListing[]
- SkillVersionsReviewed SkillListingVersion[] @relation("SkillVersionsReviewed")
+ SkillVersionsReviewed SkillListingVersion[] @relation("SkillVersionsReviewed")
APIKeys APIKey[]
IntegrationWebhooks IntegrationWebhook[]
NotificationBatches UserNotificationBatch[]
@@ -191,7 +192,7 @@ model User {
PlatformUserLinks PlatformUserLink[]
ExperimentAssignments ExperimentAssignment[]
- Attribution UserAttribution?
+ Attribution UserAttribution?
}
// One row per (user, experiment): the arm a user was bucketed into the first
@@ -234,11 +235,11 @@ model UserAttribution {
datafastSessionId String?
// First landing on the site, as seen by the browser that later signed up.
- landingPath String?
- referrer String?
- utmSource String?
- utmMedium String?
- utmCampaign String?
+ landingPath String?
+ referrer String?
+ utmSource String?
+ utmMedium String?
+ utmCampaign String?
// "email" | "google" when the account was created in this browser session.
signupMethod String?
@@ -263,30 +264,30 @@ enum SubscriptionTier {
}
model SubscriptionTrial {
- id String @id @default(uuid())
- userId String @unique
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ id String @id @default(uuid())
+ userId String @unique
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
offer Json
stripeCustomerId String
- stripeCheckoutSessionId String? @unique
- stripeSubscriptionId String? @unique
- stripeConversionInvoiceId String? @unique
- notificationRevision Int @default(0)
- checkoutAttempt Int @default(0)
+ stripeCheckoutSessionId String? @unique
+ stripeSubscriptionId String? @unique
+ stripeConversionInvoiceId String? @unique
+ notificationRevision Int @default(0)
+ checkoutAttempt Int @default(0)
checkoutSuccessUrl String
checkoutCancelUrl String
- checkoutMetadata Json @default("{}")
- status String @default("checkout_pending")
+ checkoutMetadata Json @default("{}")
+ status String @default("checkout_pending")
rejectionReason String?
cardVerifiedAt DateTime?
startedAt DateTime?
endsAt DateTime?
consumedAt DateTime?
convertedAt DateTime?
- cancelAtPeriodEnd Boolean @default(false)
- costMicrodollars BigInt @default(0)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ cancelAtPeriodEnd Boolean @default(false)
+ costMicrodollars BigInt @default(0)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([status, endsAt])
@@index([stripeCustomerId, id])
@@ -1151,6 +1152,7 @@ model Expert {
AgentPresets AgentPreset[]
PauseEvents ExpertPauseEvent[]
BundledSkills ExpertSkillListing[]
+ Routines ExpertRoutine[]
// Owner-scoped grouping into named "pods" (distinct from org-tenancy Team).
podId String?
@@ -1202,6 +1204,114 @@ model ExpertWorkflow {
@@index([expertId, createdAt, id])
}
+// Where a routine's turn lands each time it fires.
+enum ExpertRoutineSource {
+ // Shipped by a roster or a shared package. Its prompt was written by someone
+ // who will never see the account it runs on, so it arrives reaching nothing
+ // and stays that way until the owner grants it.
+ TEMPLATE
+ // Dictated by the owner in their own chat. There is no third party in the
+ // prompt, so it runs with the same reach a `schedule_followup` has always had.
+ OWNER
+}
+
+enum ExpertRoutineSession {
+ // A brand-new chat every fire. No memory of the last run.
+ FRESH
+ // One named chat, pinned when the routine was switched on: the one it was
+ // set up in unless the owner named another. Any session the owner holds in
+ // the same expert scope is allowed, which is the one thing `schedule_followup`
+ // could do that a routine could not.
+ PINNED
+ // One durable thread of its own, minted at the first fire and reused after.
+ // Per routine, not per expert, so two routines on the same cadence never
+ // interleave into one conversation. With `graphiti-memory` off this thread
+ // IS the routine's memory, which is why it is the default.
+ THREAD
+}
+
+// Standing work an expert does unattended: a prompt on a cadence, firing as a
+// copilot turn. `schedule_followup` is the primitive underneath; this is the
+// durable record that owns the cadence, the thread, and the on/off state.
+//
+// Template rows are proposals — a draft prompt, a suggested cadence, and the
+// questions an owner has to answer before it can run. Hiring copies them OFF,
+// because a cadence that fires unattended from the day of hire is a much
+// bigger promise than a skill. Switching one on resolves the proposal into the
+// routine that actually runs.
+model ExpertRoutine {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+
+ // Null when the routine is the account's own standing work rather than an
+ // expert's — Otto is the platform's default assistant, not a row in Expert,
+ // so its routines have no expert to hang off. Exactly one of expertId and
+ // userId is set: a template or hire row names the expert and takes its owner
+ // from it; an account row names the owner directly.
+ expertId String?
+ Expert Expert? @relation(fields: [expertId], references: [id], onDelete: Cascade)
+
+ userId String?
+ User User? @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ // Roster/shared slug, and the key `_sync_routines` matches on. Null when the
+ // expert authored this one in conversation; Postgres treats NULLs as
+ // distinct, so the unique below still allows many authored rows.
+ key String?
+
+ title String
+ // The proposal on a template row; what actually runs once resolved.
+ prompt String
+ // One routine, several fire times — a callback sweep that runs at 08:30 and
+ // again at 13:00 is one thing the owner switched on, not two. Template rows
+ // hold the suggested cadence; hire rows hold the resolved one.
+ crons String[]
+ // What the owner has to tell the expert before this can run: which repo,
+ // which inbox, what time. Carried from the source package's installer block.
+ // A routine with unanswered asks cannot be switched on.
+ asks String[]
+
+ sessionMode ExpertRoutineSession @default(THREAD)
+ // THREAD: null until the first fire mints it, then reused. PINNED: the chat
+ // the owner named. FRESH: stays null.
+ sessionId String?
+
+ // Where the prompt came from, which is what decides how far a fire-time turn
+ // can reach. Nothing else in the row answers that: a proposal and an
+ // owner's own words are both just text by the time they are scheduled.
+ source ExpertRoutineSource @default(TEMPLATE)
+
+ // Exactly one of `crons` and `runAt` is set. `runAt` is the one-shot — "check
+ // the deploy at six" — which gets a row like any other so it can be listed,
+ // renamed, cancelled and counted rather than living only as a scheduler job.
+ runAt DateTime?
+ // Stamped when a one-shot has run. The row outlives its job on purpose; this
+ // is what stops a spent routine still reading as switched on.
+ firedAt DateTime?
+
+ // One scheduler job per cron. Empty means off — off is the absence of a job,
+ // not a paused one, so a routine nobody switched on costs the scheduler
+ // nothing.
+ scheduleIds String[]
+ enabledAt DateTime?
+ // Set when the owner resolved the proposal (a time, a source, a rewrite).
+ // From then on the row is theirs and roster edits never touch it again.
+ customizedAt DateTime?
+ // False means the fire-time turn resolves an EMPTY credential allow-list, so
+ // the routine provably reaches nothing outside the platform — the rule
+ // `PreloadSeed.cron` states for preloads, enforced rather than asserted.
+ // Seeded and shared rows always arrive false; only an owner binding this
+ // routine to their connections sets it.
+ grantsCredentials Boolean @default(false)
+ // Mirrors AgentPreset.deactivatedByExpertArchive: re-hire resumes exactly
+ // what archiving paused, never one the owner had switched off themselves.
+ pausedByExpertArchive Boolean @default(false)
+
+ @@unique([expertId, key])
+ @@index([expertId, createdAt, id])
+ @@index([userId, createdAt, id])
+}
+
// A Skills Hub listing a roster template comes with; hiring installs its
// active version into the new expert's own skills folder.
model ExpertSkillListing {
@@ -1404,8 +1514,8 @@ model AgentGraphExecution {
// What started this run, when it was not a person: the scheduler job or
// the webhook that fired. Soft references, since jobs live in
// APScheduler's own store and webhooks are cleaned up independently.
- scheduleId String?
- webhookId String?
+ scheduleId String?
+ webhookId String?
inputs Json?
credentialInputs Json?
@@ -2200,7 +2310,7 @@ model SkillListingVersion {
// Tenancy
organizationId String?
- Files SkillListingFile[]
+ Files SkillListingFile[]
@@unique([skillListingId, version])
@@index([skillListingId, submissionStatus, isAvailable])
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 824572962a..a163879e16 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -19527,6 +19527,10 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Expert Id"
},
+ "routine_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Routine Id"
+ },
"id": { "type": "string", "title": "Id" },
"name": { "type": "string", "title": "Name" },
"next_run_time": { "type": "string", "title": "Next Run Time" },
@@ -28021,6 +28025,8 @@
"expert_workflow",
"expert_workflows",
"expert_credentials",
+ "routines",
+ "routine",
"credential_grant_requested",
"schedule_created",
"agent_trigger_list",
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 50af54d1ba..f1170994a6 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -96,7 +96,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| transport | Run on platform credits, or on your connected ChatGPT subscription if supported by your plan. | "platform" \| "codex_app_server" | No |
| session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No |
| max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |
-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "consult_teammate" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "describe_capability" \| "edit_agent" \| "edit_chat_platform_message" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_capability" \| "find_library_agent" \| "find_session" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "message_session" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_capability" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_capability" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "start_desktop" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "run_block" \| "run_mcp_tool" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "consult_teammate" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "describe_capability" \| "edit_agent" \| "edit_chat_platform_message" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_capability" \| "find_library_agent" \| "find_session" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_routines" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "message_session" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_capability" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_capability" \| "run_sub_session" \| "schedule_followup" \| "schedule_routine" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "start_desktop" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "run_block" \| "run_mcp_tool" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
| blocks | Block identifiers to filter when the copilot runs blocks via run_capability. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |