Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(routines): run users' own agents and drop the agent rollout flag (#9334)
Wolf Mermelstein1e4dc035f897
diff --git a/.agents/skills/feature-flags/SKILL.md b/.agents/skills/feature-flags/SKILL.mdindex 5e72aa22f5..83e52345b1 100644--- a/.agents/skills/feature-flags/SKILL.md+++ b/.agents/skills/feature-flags/SKILL.md@@ -1,6 +1,6 @@---name: feature-flags-description: Add, read, or remove a feature flag in the web app (`defineFlag`, PostHog, `ENABLE_*` env flags, `useFeatureFlag`, `isFeatureEnabled`, `ShowFeatureFlag`) or the Rust backend (`crates/feature_flags`, config switches). Use when gating, rolling out, or killing a feature, or when asked to "flag it".+description: Add, read, or remove a feature flag in the web app (`defineFlag`, PostHog, `ENABLE_*` env flags, `useFeatureFlag`, `isFeatureEnabled`, `ShowFeatureFlag`) or the Rust backend (`crates/feature_flags`). Use when gating, rolling out, or killing a feature, or when asked to "flag it".---# Feature flags@@ -103,9 +103,11 @@ These are the mistakes past flagged launches had to fix:construct `PostHogFeatureFlags` once at the composition root, load one`FlagSnapshot` per authenticated user id, and read it synchronously. A failedload returns `Err`; the caller decides the fallback, explicitly. Wire the adapter and its config at the consuming service composition root.-- **Deployment switches** (on for an environment, not per user) are- `MacroConfig` bools with a default, configured in Doppler (see the config- rule), not PostHog.+- **Every backend rollout or feature gate**, per user or for everyone, is a+ `crates/feature_flags` flag, never a `MacroConfig`/Doppler boolean.+ `MacroConfig` holds real environment configuration (endpoints, credentials,+ capacities), not switches that turn features on. Remove the gate once its+ rollout is done.- Keep the backend and web flag keys identical when both gate one feature.## 6. Remove itdiff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex a1833560dc..e77d4e3e69 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -12053,6 +12053,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/model-error-response","crates/model_user",diff --git a/CLAUDE.md b/CLAUDE.mdindex f15076b89d..e89d571a34 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -53,6 +53,7 @@ Real files live in `.agents/`; tool-specific directories only symlink to it.| Adding collaborative markdown to a feature | [Collab surface core skill](.agents/skills/collab-surface-core/SKILL.md) || Editing frontend or backend code that adds a flow, view, or hot path, or tracing one | `instrumentation` skill || Finding slow web or desktop app flows in Datadog | `perf-investigation` skill |+| Adding, reading or removing a feature flag (web or backend) | `feature-flags` skill || Rust code, builds, or tests | [Rust development](docs/development/rust.md) || SQLx queries, migrations, DB tests, or cache errors | [Database development](docs/development/database.md) || Web frontend | [Web agent guide](apps/web/AGENTS.md) |diff --git a/Cargo.lock b/Cargo.lockindex 7fc4ee0c87..f9537ba582 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -17111,6 +17111,7 @@ dependencies = ["chrono-tz","cron","macro_authorization",+ "macro_tower_layers","macro_user_id","reqwest 0.13.4","schemars 1.2.1",diff --git a/apps/docs/AI/mcp/tools/create-routine.mdx b/apps/docs/AI/mcp/tools/create-routine.mdxindex 62457dc889..343cab8e2b 100644--- a/apps/docs/AI/mcp/tools/create-routine.mdx+++ b/apps/docs/AI/mcp/tools/create-routine.mdx@@ -6,7 +6,7 @@ description: >-# CreateRoutine-Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.+Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId: a built-in agent, or one the user owns or can use, including one on a self-hosted runtime. That runtime need not be online to save the routine; a run it cannot serve fails and shows in ReadRoutine history. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.## Parametersdiff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 8d55cbe499..5966e40859 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -8359,7 +8359,7 @@ export interface CreateProjectResponse {projectName: string;}/**- * Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.+ * Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId: a built-in agent, or one the user owns or can use, including one on a self-hosted runtime. That runtime need not be online to save the routine; a run it cannot serve fails and shows in ReadRoutine history. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.*/export interface CreateRoutine {configuration: RoutineConfiguration;diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex ffcfd121d7..e0918d6722 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -1798,7 +1798,7 @@"RoutineTemplate.activate": "### activate()\n\n> **activate**(`options`): `Promise`\\<`Routine`\\>\n\nCreate the caller's own routine from this template, with its references\nalready filled in for them.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`Routine`\\>","RoutineTemplate.toJSON": "### toJSON()\n\n> **toJSON**(): `scheduled-action.RoutineTemplate`\n\nSerialize without the authenticated client.\n\n#### Returns\n\n`scheduled-action.RoutineTemplate`","routineBody": "# Function: routineBody()\n\n> **routineBody**(`options`): \\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: `RunVisibility` \\| `undefined`; `task`: \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: `ActionTrigger`; \\}\n\nTranslate typed routine options into the generated wire contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n## Returns\n\n\\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: `RunVisibility` \\| `undefined`; `task`: \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: `ActionTrigger`; \\}\n\n| Name | Type | Default value | Description |\n| ------ | ------ | ------ | ------ |\n| `enabled` | `boolean` \\| `undefined` | `options.enabled` | - |\n| `kind` | `\"Agent\"` | - | - |\n| `name` | `string` | `options.name` | - |\n| `run_visibility` | `RunVisibility` \\| `undefined` | `options.runVisibility` | - |\n| `task` | \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\} | - | - |\n| `task.agent?` | `AgentTaskAgent` \\| `null` | - | - |\n| `task.mcp_servers?` | `scheduled-action.AgentMcpServer`[] | - | Apps the routine requires on top of the agent's own. The owner must have each one connected to save the routine and for it to run. |\n| `task.model?` | `string` \\| `null` | - | - |\n| `task.prompt` | `string` | - | - |\n| `task.user_prompt` | `string` | - | - |\n| `trigger` | `ActionTrigger` | - | - |",- "RoutineOptions": "# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | `Agent` | Agent to run the task. Set `model`, `agent`, or both. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model to run the task, e.g. `anthropic/claude-sonnet-5-5`, or the model override for `agent`. Set `model`, `agent`, or both. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | `RunVisibility` | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | `RoutineTriggerOptions` | Schedules or Macro events that start the routine. A cron `schedule` has 6 or 7 fields: `sec min hour day-of-month month day-of-week [year]`. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |",+ "RoutineOptions": "# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | `Agent` | Agent to run the task: a built-in agent, or one the caller owns or can use, including one on a self-hosted runtime. Access is checked on save and again on every run. Set `model`, `agent`, or both. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model to run the task, e.g. `anthropic/claude-sonnet-5-5`, or the model override for `agent`. Set `model`, `agent`, or both. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | `RunVisibility` | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | `RoutineTriggerOptions` | Schedules or Macro events that start the routine. A cron `schedule` has 6 or 7 fields: `sec min hour day-of-month month day-of-week [year]`. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |","RoutineEventFilter": "# Type Alias: RoutineEventFilter\n\n> **RoutineEventFilter** = `Omit`\\<`EventFilter`, `\"ids\"` \\| `\"condition\"`\\> & \\{ `condition?`: `string`; `entities?`: `EntityReference`[]; \\}\n\nAn event selector references resources by typed handles.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `condition?` | `string` | Optional yes/no condition on the triggering content. |\n| `entities?` | `EntityReference`[] | Resource selectors for these events. Omit to match all resources. |","RoutineTriggerOptions": "# Type Alias: RoutineTriggerOptions\n\n> **RoutineTriggerOptions** = `SingleRoutineTrigger` \\| \\{ `triggers`: `SingleRoutineTrigger`[]; `type`: `\"multiple\"`; \\}\n\nOne or multiple routine triggers.","SingleRoutineTrigger": "# Type Alias: SingleRoutineTrigger\n\n> **SingleRoutineTrigger** = `Extract`\\<`RoutineTrigger`, \\{ `type`: `\"cron\"`; \\}\\> \\| \\{ `filters`: `RoutineEventFilter`[]; `type`: `\"events\"`; \\}\n\nOne schedule or set of event selectors.",diff --git a/crates/routines/Cargo.toml b/crates/routines/Cargo.tomlindex 1de338324d..f523892dcf 100644--- a/crates/routines/Cargo.toml+++ b/crates/routines/Cargo.toml@@ -12,6 +12,7 @@ chrono.workspace = truechrono-tz.workspace = truecron.workspace = truemacro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }+macro_tower_layers = { path = "../macro_tower_layers" }macro_user_id = { path = "../macro_user_id" }reqwest.workspace = trueschemars.workspace = truediff --git a/crates/routines/src/inbound.rs b/crates/routines/src/inbound.rsindex 1bb07cac59..77551ab4a1 100644--- a/crates/routines/src/inbound.rs+++ b/crates/routines/src/inbound.rs@@ -48,7 +48,7 @@ pub fn routine_toolset() -> AsyncToolCollection<RoutineToolContext> {#[derive(Deserialize, JsonSchema)]#[schemars(title = "CreateRoutine",- description = r#"Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine."#+ description = r#"Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId: a built-in agent, or one the user owns or can use, including one on a self-hosted runtime. That runtime need not be online to save the routine; a run it cannot serve fails and shows in ReadRoutine history. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine."#)]pub struct CreateRoutine {/// Name, instructions, target, and schedule.diff --git a/crates/routines/src/outbound.rs b/crates/routines/src/outbound.rsindex 87c06ce30c..63ea0fb0f7 100644--- a/crates/routines/src/outbound.rs+++ b/crates/routines/src/outbound.rs@@ -14,6 +14,26 @@ use serde_json::Value;use std::{sync::Arc, time::Duration};use uuid::Uuid;+/// The scheduler's rejection text, which names a safe cause such as a deleted+/// agent. Bounded so a proxy's error page cannot flood the tool result.+async fn rejection_reason(mut response: reqwest::Response) -> String {+ const MAX_REASON_BYTES: usize = 300;+ let mut body = Vec::new();+ while body.len() < MAX_REASON_BYTES {+ match response.chunk().await {+ Ok(Some(chunk)) => body.extend_from_slice(&chunk),+ _ => break,+ }+ }+ let reason = String::from_utf8_lossy(&body[..body.len().min(MAX_REASON_BYTES)]);+ let reason = reason.trim();+ if reason.is_empty() {+ "no reason given".to_owned()+ } else {+ reason.to_owned()+ }+}+/// Reusable client; internal credentials never come from model arguments.pub struct RoutineClient {client: Client,@@ -64,9 +84,12 @@ impl RoutineClient {path: &str,body: Option<Value>,) -> Result<Vec<u8>> {+ let mut trace_headers = reqwest::header::HeaderMap::new();+ macro_tower_layers::inject_trace_headers(&mut trace_headers);let mut request = self.client.request(method, self.base.join(path)?)+ .headers(trace_headers).header(INTERNAL_API_KEY_HEADER, self.key.clone()).header(INTERNAL_MACRO_USER_ID_HEADER, user.as_ref());if let Some(body) = body {@@ -93,12 +116,17 @@ impl RoutineClient {Ok(body)}400 => bail!(- "Invalid routine configuration or unavailable model/agent. Check the schedule and select an accessible agent from ListAgents using its bot.botId."+ "Invalid routine configuration or unavailable model/agent ({}). Check the schedule and select an accessible agent from ListAgents using its bot.botId.",+ rejection_reason(response).await),422 => bail!(- "Invalid routine configuration, or a required app is not connected or unusable by the selected agent. Ask the user to connect each app in requiredApps (DiscoverConnectors gives a link) or remove it."+ "Invalid routine configuration, or a required app is not connected or unusable by the selected agent ({}). Ask the user to connect each app in requiredApps (DiscoverConnectors gives a link) or remove it.",+ rejection_reason(response).await+ ),+ 401 | 403 | 404 => bail!(+ "Routine or target is unavailable to this user ({}).",+ rejection_reason(response).await),- 401 | 403 | 404 => bail!("Routine or target is unavailable to this user."),402 => bail!("The user's AI allowance is exhausted, so the routine cannot run now."),409 => bail!("Routine is running or changed. Read it again before editing."),_ => bail!(diff --git a/crates/routines/src/outbound/test.rs b/crates/routines/src/outbound/test.rsindex b3c0087cf4..31c54dc77e 100644--- a/crates/routines/src/outbound/test.rs+++ b/crates/routines/src/outbound/test.rs@@ -212,3 +212,50 @@ async fn run_now_explains_an_exhausted_ai_allowance() {assert!(error.to_string().contains("allowance"), "{error}");server.await.unwrap();}++/// The scheduler's rejection names the cause, so the agent can tell a deleted+/// agent from one the user may not run or a configuration it must fix.+#[tokio::test]+async fn create_rejections_carry_the_scheduler_reason() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/scheduled-action", listener.local_addr().unwrap());+ let rejections = [+ ("404 Not Found", "selected agent is unavailable"),+ ("403 Forbidden", "routine owner is not authorized"),+ (+ "400 Bad Request",+ "invalid routine task; select a model or agent and provide instructions",+ ),+ (+ "422 Unprocessable Entity",+ "connect every app this routine requires",+ ),+ ];+ let server = serve_responses(+ listener,+ rejections+ .iter()+ .map(|(status, reason)| (*status, (*reason).to_owned()))+ .collect(),+ );+ let client = RoutineClient::new(&url, "test-internal-key").unwrap();+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let config = RoutineConfiguration {+ name: "Stuck tickets".into(),+ instructions: "Sweep stuck tickets".into(),+ target: RoutineTarget::Agent {+ agent_id: Uuid::from_u128(1),+ },+ schedule: RoutineSchedule::Cron {+ expression: "0 0 9,17 * * *".into(),+ timezone: "UTC".into(),+ },+ required_apps: vec![],+ };++ for (_, reason) in rejections {+ let error = client.create(&user, &config).await.unwrap_err();+ assert!(error.to_string().contains(reason), "{error}");+ }+ server.await.unwrap();+}diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.mdindex a9725671ca..598bac2f10 100644--- a/crates/scheduled_action/AGENTS.md+++ b/crates/scheduled_action/AGENTS.md@@ -77,6 +77,10 @@ that listener is ready. Cancellation can stop the gate before startup finishes.`RoutineSessions::prepare` checks again on every run, then adds them to anagent limited to selected apps. An update that omits the key is rejectedwhen the stored task has apps (`require_explicit_selection`).+- An agent target is any agent the owner may run: built in, their own, or+ one on a self-hosted runtime. `TargetValidation` authorizes it on save+ without contacting the runtime; `RoutineSessions::prepare` reauthorizes on+ every run, and an offline runtime fails that run in its history.- Macro events store only ids, plus the GitHub pull request and account behinda task status change (`change_source`), and are read again, as the owner, atdispatch.diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rsindex 095aede620..28034bc721 100644--- a/crates/scheduled_action/src/domain/service/test.rs+++ b/crates/scheduled_action/src/domain/service/test.rs@@ -329,7 +329,7 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {base.dispatcher_tx.clone(),grants(&base.repo),)- .with_target_validation(TargetValidation::new(sessions.clone(), true));+ .with_target_validation(TargetValidation::new(sessions.clone()));let mut config = configuration(false);config.task = agent_task();let foreign = MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap();@@ -373,7 +373,7 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {}#[tokio::test]-async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clients() {+async fn without_sessions_agents_are_refused_but_models_and_explicit_switches_are_kept() {let base = service(false);let svc = TestService::new(base.repo.clone(),@@ -381,7 +381,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_cliebase.dispatcher_tx.clone(),grants(&base.repo),)- .with_target_validation(TargetValidation::new(Arc::new(Sessions::default()), true));+ .with_target_validation(TargetValidation::new(Arc::new(Sessions::default())));let mut config = configuration(false);config.task = agent_task();let error = base@@ -390,7 +390,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie.unwrap_err();assert_eq!(error.downcast_ref(),- Some(&TargetValidationError::AgentsDisabled)+ Some(&TargetValidationError::SessionsUnavailable));let created = svc.create_action(&user_principal(), config.clone())@@ -403,7 +403,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie.unwrap_err();assert_eq!(error.downcast_ref(),- Some(&TargetValidationError::AgentsDisabled)+ Some(&TargetValidationError::SessionsUnavailable));// An old client cannot erase the agent even when trying to pause it.@@ -440,7 +440,7 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_base.dispatcher_tx.clone(),grants(&base.repo),)- .with_target_validation(TargetValidation::new(sessions.clone(), true));+ .with_target_validation(TargetValidation::new(sessions.clone()));let mut config = configuration(false);config.task = agent_task();let created = svc@@ -496,7 +496,7 @@ async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_rbase.dispatcher_tx.clone(),grants(&base.repo),)- .with_target_validation(TargetValidation::new(sessions.clone(), true));+ .with_target_validation(TargetValidation::new(sessions.clone()));let mut config = configuration(false);config.task = agent_task();let created = svc.create_action(&user_principal(), config).await.unwrap();@@ -1146,7 +1146,7 @@ async fn resuming_revalidates_the_stored_agent_but_pausing_does_not() {base.dispatcher_tx.clone(),grants(&base.repo),)- .with_target_validation(TargetValidation::new(sessions.clone(), true));+ .with_target_validation(TargetValidation::new(sessions.clone()));let mut config = configuration(false);config.task = agent_task();let created = svc.create_action(&user_principal(), config).await.unwrap();diff --git a/crates/scheduled_action/src/domain/target_validation.rs b/crates/scheduled_action/src/domain/target_validation.rsindex 4c96a6ddaa..e5f6f9a7db 100644--- a/crates/scheduled_action/src/domain/target_validation.rs+++ b/crates/scheduled_action/src/domain/target_validation.rs@@ -17,45 +17,46 @@ use super::{pub enum TargetValidationError {#[error("invalid routine task; select a model or agent and provide instructions")]InvalidTask,- #[error("agent routines are not enabled")]- AgentsDisabled,+ /// The scheduler has no session domain to authorize agents or apps with.+ #[error("this scheduler cannot check agents or required apps")]+ SessionsUnavailable,#[error("this routine selects an agent; reload or upgrade your client before updating")]ExplicitAgentRequired,#[error("this routine requires apps; reload or upgrade your client before updating")]ExplicitAppsRequired,}-/// Default acceptance policy for composition roots that have not enabled agents.+/// Default acceptance policy for composition roots without a session domain.pub struct ModelOnlyTargets;impl TaskTargetValidator for ModelOnlyTargets {async fn validate_task(&self, task: &Value, _owner: &MacroUserIdStr<'static>) -> Result<()> {- // Required apps need the session domain to check the owner's connections.- if !parse_task(task, false)?.mcp_servers.is_empty() {- return Err(TargetValidationError::AgentsDisabled.into());+ let task = parse_task(task)?;+ // Agents and required apps need the session domain to authorize them.+ if matches!(task.resolve_target()?, ResolvedTaskTarget::Agent { .. })+ || !task.mcp_servers.is_empty()+ {+ return Err(TargetValidationError::SessionsUnavailable.into());}Ok(())}}-/// Authorizes the selection without opening a session or checking runtime connectivity.+/// Authorizes the selection without opening a session or checking runtime+/// connectivity, so a self-hosted agent can be saved while its runtime is offline.pub struct TargetValidation<Sessions> {sessions: Arc<Sessions>,- agents_enabled: bool,}impl<Sessions> TargetValidation<Sessions> {- pub fn new(sessions: Arc<Sessions>, agents_enabled: bool) -> Self {- Self {- sessions,- agents_enabled,- }+ pub fn new(sessions: Arc<Sessions>) -> Self {+ Self { sessions }}}impl<Sessions: RoutineSessions> TaskTargetValidator for TargetValidation<Sessions> {async fn validate_task(&self, task: &Value, owner: &MacroUserIdStr<'static>) -> Result<()> {- let task = parse_task(task, self.agents_enabled)?;+ let task = parse_task(task)?;let (bot_id, model) = task.resolve_target()?.session_target();self.sessions.validate(ValidateRoutineSession {@@ -69,15 +70,11 @@ impl<Sessions: RoutineSessions> TaskTargetValidator for TargetValidation<Session}}-fn parse_task(task: &Value, agents_enabled: bool) -> Result<AgentTask, TargetValidationError> {+fn parse_task(task: &Value) -> Result<AgentTask, TargetValidationError> {let task: AgentTask =serde_json::from_value(task.clone()).map_err(|_| TargetValidationError::InvalidTask)?;- let target = task- .resolve_target()+ task.resolve_target().map_err(|_| TargetValidationError::InvalidTask)?;- if matches!(target, ResolvedTaskTarget::Agent { .. }) && !agents_enabled {- return Err(TargetValidationError::AgentsDisabled);- }Ok(task)}diff --git a/crates/scheduled_action/src/domain/target_validation/test.rs b/crates/scheduled_action/src/domain/target_validation/test.rsindex 156bef7903..a13b3738d8 100644--- a/crates/scheduled_action/src/domain/target_validation/test.rs+++ b/crates/scheduled_action/src/domain/target_validation/test.rs@@ -68,78 +68,94 @@ pub(crate) fn agent_task() -> Value {}#[tokio::test]-async fn local_validation_precedes_gate_and_remote_authorization() {+async fn local_validation_precedes_remote_authorization() {let sessions = Arc::new(Sessions::default());let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();- for enabled in [false, true] {- let validator = TargetValidation::new(sessions.clone(), enabled);- for task in [- json!({}),- json!({"prompt":"instructions", "user_prompt":"task"}),- json!({"model":" ", "prompt":"instructions", "user_prompt":"task"}),- json!({"agent":{"bot_id":"bad-id"}, "prompt":"instructions", "user_prompt":"task"}),- json!({"agent":{"bot_id":BOT}, "model":"", "prompt":"instructions", "user_prompt":"task"}),- ] {- let error = validator.validate_task(&task, &owner).await.unwrap_err();- assert_eq!(- error.downcast_ref(),- Some(&TargetValidationError::InvalidTask)- );- }+ let validator = TargetValidation::new(sessions.clone());+ for task in [+ json!({}),+ json!({"prompt":"instructions", "user_prompt":"task"}),+ json!({"model":" ", "prompt":"instructions", "user_prompt":"task"}),+ json!({"agent":{"bot_id":"bad-id"}, "prompt":"instructions", "user_prompt":"task"}),+ json!({"agent":{"bot_id":BOT}, "model":"", "prompt":"instructions", "user_prompt":"task"}),+ ] {+ let error = validator.validate_task(&task, &owner).await.unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&TargetValidationError::InvalidTask)+ );}assert!(sessions.validations.lock().unwrap().is_empty());}#[tokio::test]-async fn model_selection_validates_macro_session_without_the_named_agent_gate() {+async fn model_selection_validates_a_macro_session() {let sessions = Arc::new(Sessions::default());let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();- for enabled in [false, true] {- TargetValidation::new(sessions.clone(), enabled)- .validate_task(- &json!({"model":"runtime/model", "prompt":"instructions", "user_prompt":"task"}),- &owner,- )- .await- .unwrap();- }+ TargetValidation::new(sessions.clone())+ .validate_task(+ &json!({"model":"runtime/model", "prompt":"instructions", "user_prompt":"task"}),+ &owner,+ )+ .await+ .unwrap();let validations = sessions.validations.lock().unwrap();- assert_eq!(validations.len(), 2);- for selection in validations.iter() {- assert_eq!(selection.bot_id, bot_id::MACRO_NEW_BOT_ID);- assert_eq!(selection.model.as_deref(), Some("runtime/model"));- assert_eq!(selection.owner, owner);- }+ assert_eq!(validations.len(), 1);+ assert_eq!(validations[0].bot_id, bot_id::MACRO_NEW_BOT_ID);+ assert_eq!(validations[0].model.as_deref(), Some("runtime/model"));+ assert_eq!(validations[0].owner, owner);assert!(sessions.preparations.lock().unwrap().is_empty());}#[tokio::test]-async fn default_and_disabled_gates_reject_agents_without_contacting_sessions() {+async fn a_validator_without_sessions_rejects_agents() {let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();- let sessions = Arc::new(Sessions::default());let error = ModelOnlyTargets.validate_task(&agent_task(), &owner).await.unwrap_err();assert_eq!(error.downcast_ref(),- Some(&TargetValidationError::AgentsDisabled)+ Some(&TargetValidationError::SessionsUnavailable));- let error = TargetValidation::new(sessions.clone(), false)+}++/// A user's own agent, built in or on a self-hosted runtime, is checked by+/// the session domain rather than refused by the scheduler.+#[tokio::test]+async fn hands_an_owned_agent_to_the_session_check() {+ let sessions = Arc::new(Sessions::default());+ let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();+ TargetValidation::new(sessions.clone()).validate_task(&agent_task(), &owner).await+ .unwrap();+ let validations = sessions.validations.lock().unwrap();+ assert_eq!(validations.len(), 1);+ assert_eq!(validations[0].bot_id.to_string(), BOT);+ assert_eq!(validations[0].owner, owner);+}++#[tokio::test]+async fn rejects_a_deleted_agent() {+ let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();+ let error = TargetValidation::new(Arc::new(Sessions::default()))+ .validate_task(+ &json!({"agent":{"bot_id":"01960000-0000-7000-8000-0000000000ff"}, "prompt":"instructions", "user_prompt":"task"}),+ &owner,+ )+ .await.unwrap_err();assert_eq!(error.downcast_ref(),- Some(&TargetValidationError::AgentsDisabled)+ Some(&RoutineSessionError::PersonaUnavailable));- assert!(sessions.validations.lock().unwrap().is_empty());}#[tokio::test]async fn authorizes_owner_and_override_without_starting_external_runtime() {let sessions = Arc::new(Sessions::default());- let validator = TargetValidation::new(sessions.clone(), true);+ let validator = TargetValidation::new(sessions.clone());let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();for model in [None, Some("external/model")] {let mut task = agent_task();@@ -183,7 +199,7 @@ fn requires_explicit_null_to_remove_even_an_unparseable_historical_selection() {async fn hands_the_routine_apps_to_the_session_check() {let sessions = Arc::new(Sessions::default());let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();- TargetValidation::new(sessions.clone(), true)+ TargetValidation::new(sessions.clone()).validate_task(&json!({"agent": {"bot_id": BOT},@@ -204,7 +220,7 @@ async fn hands_the_routine_apps_to_the_session_check() {);*sessions.error.lock().unwrap() = Some(RoutineSessionError::AppNotConnected);- let error = TargetValidation::new(sessions.clone(), true)+ let error = TargetValidation::new(sessions.clone()).validate_task(&json!({"model": "runtime/model",@@ -239,7 +255,7 @@ async fn a_validator_that_cannot_check_connections_rejects_routine_apps() {.unwrap_err();assert_eq!(error.downcast_ref(),- Some(&TargetValidationError::AgentsDisabled)+ Some(&TargetValidationError::SessionsUnavailable));}diff --git a/crates/scheduled_action/src/inbound/axum_router.rs b/crates/scheduled_action/src/inbound/axum_router.rsindex 7e067c2d6f..3445094952 100644--- a/crates/scheduled_action/src/inbound/axum_router.rs+++ b/crates/scheduled_action/src/inbound/axum_router.rs@@ -530,7 +530,7 @@ impl IntoResponse for ScheduledActionApiError {}if let Some(validation) = error.downcast_ref::<TargetValidationError>() {let status = match validation {- TargetValidationError::InvalidTask | TargetValidationError::AgentsDisabled => {+ TargetValidationError::InvalidTask | TargetValidationError::SessionsUnavailable => {StatusCode::BAD_REQUEST}TargetValidationError::ExplicitAgentRequireddiff --git a/crates/scheduled_action/src/inbound/axum_router/test.rs b/crates/scheduled_action/src/inbound/axum_router/test.rsindex 11c4820c84..274374de34 100644--- a/crates/scheduled_action/src/inbound/axum_router/test.rs+++ b/crates/scheduled_action/src/inbound/axum_router/test.rs@@ -698,7 +698,7 @@ async fn target_errors_have_deliberate_sanitized_status_codes() {StatusCode::BAD_REQUEST,),(- TargetValidationError::AgentsDisabled.into(),+ TargetValidationError::SessionsUnavailable.into(),StatusCode::BAD_REQUEST,),(@@ -786,7 +786,7 @@ async fn agent_replacement_requires_explicit_null_and_unavailable_agent_remains_tx,Arc::new(FakeGrants::all(repo)),)- .with_target_validation(TargetValidation::new(sessions.clone(), true));+ .with_target_validation(TargetValidation::new(sessions.clone()));let app = router_with(Arc::new(svc), FakeEntityAccessService::owner_only());let mut input = cron_action();input["task"] = agent_task();diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/interfaces/RoutineOptions.md b/packages/sdk-docs/reference/src/entities/routines/routine/interfaces/RoutineOptions.mdindex 7e46fe54a1..2eadf0bdc4 100644--- a/packages/sdk-docs/reference/src/entities/routines/routine/interfaces/RoutineOptions.md+++ b/packages/sdk-docs/reference/src/entities/routines/routine/interfaces/RoutineOptions.md@@ -6,7 +6,7 @@ Configuration of an agent routine.| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-agent"></a> `agent?` | [`Agent`](../../../agents/agent/classes/Agent.md) | Agent to run the task. Set `model`, `agent`, or both. |+| <a id="property-agent"></a> `agent?` | [`Agent`](../../../agents/agent/classes/Agent.md) | Agent to run the task: a built-in agent, or one the caller owns or can use, including one on a self-hosted runtime. Access is checked on save and again on every run. Set `model`, `agent`, or both. || <a id="property-enabled"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. || <a id="property-model"></a> `model?` | `string` | Model to run the task, e.g. `anthropic/claude-sonnet-5-5`, or the model override for `agent`. Set `model`, `agent`, or both. || <a id="property-name"></a> `name` | `string` | Display name. |diff --git a/packages/sdk/src/entities/routines/routine.ts b/packages/sdk/src/entities/routines/routine.tsindex 84eeffebd0..324c5a2ead 100644--- a/packages/sdk/src/entities/routines/routine.ts+++ b/packages/sdk/src/entities/routines/routine.ts@@ -79,7 +79,11 @@ export interface RoutineOptions {* override for `agent`. Set `model`, `agent`, or both.*/model?: RoutineModelId;- /** Agent to run the task. Set `model`, `agent`, or both. */+ /**+ * Agent to run the task: a built-in agent, or one the caller owns or can+ * use, including one on a self-hosted runtime. Access is checked on save and+ * again on every run. Set `model`, `agent`, or both.+ */agent?: Agent;/** Whether triggers can start executions. Defaults to true on creation. */enabled?: boolean;diff --git a/services/agent_harness_service/src/scheduling.rs b/services/agent_harness_service/src/scheduling.rsindex 8f3568be16..6bd16895e8 100644--- a/services/agent_harness_service/src/scheduling.rs+++ b/services/agent_harness_service/src/scheduling.rs@@ -264,10 +264,7 @@ pub async fn build().with_event_management_enabled(config.event_routines_enabled).with_conditions_enabled(conditions_enabled)- .with_target_validation(TargetValidation::new(- sessions,- config.routine_agents_enabled,- ))+ .with_target_validation(TargetValidation::new(sessions)).with_github_links(PgGithubInstallationClaims::new(db.clone())),);let template_flags = configdiff --git a/services/agent_harness_service/src/scheduling/config.rs b/services/agent_harness_service/src/scheduling/config.rsindex 1f95b3fa5f..a8f1124f07 100644--- a/services/agent_harness_service/src/scheduling/config.rs+++ b/services/agent_harness_service/src/scheduling/config.rs@@ -60,10 +60,6 @@ pub struct Config {/// Register EVENT_ROUTINES_ENABLED as a raw boolean in Doppler before rollout.#[macro_config_default(false)]pub event_routines_enabled: bool,- /// Accept agent-target configuration only after all scheduler workers are upgraded.- /// Register ROUTINE_AGENTS_ENABLED as a raw boolean in Doppler before rollout.- #[macro_config_default(false)]- pub routine_agents_enabled: bool,/// The internal api keypub internal_api_key: InternalApiKey,/// TypeSafe credential for the Jev classifier behind trigger conditions.diff --git a/services/agent_harness_service/src/scheduling/config/test.rs b/services/agent_harness_service/src/scheduling/config/test.rsindex 898d766ba2..83c3873924 100644--- a/services/agent_harness_service/src/scheduling/config/test.rs+++ b/services/agent_harness_service/src/scheduling/config/test.rs@@ -116,23 +116,9 @@ fn settlement_requests_need_billing_on_and_the_authentication_key() {fn event_routines_default_off_and_reuse_existing_brokers() {let config: Config = serde_json::from_value(config_values()).unwrap();assert!(!config.event_routines_enabled);- assert!(!config.routine_agents_enabled);assert_eq!(config.kafka_brokers.to_string(), "existing-broker:9092");}-#[test]-fn routine_agents_require_an_explicit_boolean() {- for enabled in [false, true] {- let mut values = config_values();- values["ROUTINE_AGENTS_ENABLED"] = json!(enabled);- let config: Config = serde_json::from_value(values).unwrap();- assert_eq!(config.routine_agents_enabled, enabled);- }- let mut values = config_values();- values["ROUTINE_AGENTS_ENABLED"] = json!("enabled");- assert!(serde_json::from_value::<Config>(values).is_err());-}-#[test]fn event_routines_require_an_explicit_boolean() {for enabled in [false, true] {