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
refactor(bots): define first-party bots in code instead of the bots table (#5954)
Eric Hayes6e778ed7bbb2
diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rsindex 8153967374..a2cb109ffa 100644--- a/crates/bot_id/src/lib.rs+++ b/crates/bot_id/src/lib.rs@@ -98,6 +98,76 @@ pub const CURSOR_HANDLE: &str = "cursor";/// Display name for the "Cursor" system bot.pub const CURSOR_NAME: &str = "Cursor";+/// Stable handle for the autonomous Macro platform principal.+pub const MACRO_SYSTEM_HANDLE: &str = "macro-system";++/// A first-party bot.+///+/// System bots live here rather than in the `bots` table. Their ids are+/// compile-time constants, so a row would only be a second copy of this one+/// that an environment could be missing - which is exactly how a deployment+/// ends up serving a bot it cannot look up. Only user- and team-owned bots+/// are rows.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SystemBot {+ /// Stable id.+ pub id: BotId,+ /// Display name.+ pub name: &'static str,+ /// Handle used for `@` mentions.+ pub handle: &'static str,+ /// Whether mentioning this bot opens an agent session.+ pub has_agent: bool,+}++/// Every first-party bot.+pub const SYSTEM_BOTS: &[SystemBot] = &[+ SystemBot {+ id: MACRO_AI_BOT_ID,+ name: MACRO_AI_NAME,+ handle: MACRO_AI_HANDLE,+ has_agent: true,+ },+ SystemBot {+ id: MACRO_CODER_BOT_ID,+ name: MACRO_CODER_NAME,+ handle: MACRO_CODER_HANDLE,+ has_agent: true,+ },+ SystemBot {+ id: CURSOR_BOT_ID,+ name: CURSOR_NAME,+ handle: CURSOR_HANDLE,+ has_agent: true,+ },+ // Posts as itself for autonomous platform operations, but nothing mentions+ // it and it opens no sessions.+ SystemBot {+ id: MACRO_SYSTEM_BOT_ID,+ name: MACRO_SYSTEM_NAME,+ handle: MACRO_SYSTEM_HANDLE,+ has_agent: false,+ },+];++/// The first-party bot with this id, when it is one.+#[must_use]+pub fn system_bot(id: BotId) -> Option<&'static SystemBot> {+ SYSTEM_BOTS.iter().find(|bot| bot.id == id)+}++/// The first-party bot with this handle, when it is one.+#[must_use]+pub fn system_bot_by_handle(handle: &str) -> Option<&'static SystemBot> {+ SYSTEM_BOTS.iter().find(|bot| bot.handle == handle)+}++/// Whether `id` is a first-party bot, and so has no `bots` row.+#[must_use]+pub fn is_system_bot(id: BotId) -> bool {+ system_bot(id).is_some()+}+/// A bot id UUID.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(transparent)]diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex 39004dddfd..8069eb4d7c 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -131,6 +131,31 @@ pub struct Bot {pub has_agent: bool,}+impl Bot {+ /// The [`Bot`] view of a first-party bot.+ ///+ /// First-party bots have no row (see [`bot_id::SystemBot`]), so the+ /// row-shaped fields are the honest answers for something that was never+ /// created and cannot be owned, edited, or deleted.+ #[must_use]+ pub fn system(bot: &bot_id::SystemBot) -> Self {+ Self {+ id: bot.id,+ kind: BotKind::System,+ owner: None,+ name: bot.name.to_owned(),+ handle: bot.handle.to_owned(),+ description: None,+ avatar_url: None,+ created_by: None,+ created_at: DateTime::UNIX_EPOCH,+ updated_at: DateTime::UNIX_EPOCH,+ deleted_at: None,+ has_agent: bot.has_agent,+ }+ }+}+/// Channel containing a bot.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rsindex e148db436a..358a017aa5 100644--- a/crates/bots/src/outbound/pg_bots_repo.rs+++ b/crates/bots/src/outbound/pg_bots_repo.rs@@ -380,6 +380,11 @@ impl BotRepo for PgBotsRepo {}async fn get_bot(&self, bot_id: BotId) -> Result<Option<Bot>, Self::Err> {+ // First-party bots are compile-time constants with no row, so they are+ // answered from the registry rather than looked up and missed.+ if let Some(system) = bot_id::system_bot(bot_id) {+ return Ok(Some(Bot::system(system)));+ }let row = sqlx::query_as!(BotRow,r#"diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rsindex 3b2bc1e87b..90b71c8b39 100644--- a/crates/channels/src/outbound/pg_channels_repo.rs+++ b/crates/channels/src/outbound/pg_channels_repo.rs@@ -647,7 +647,19 @@ async fn load_bot_display_names(if bot_ids.is_empty() {return Ok(HashMap::new());}- let uuids: Vec<Uuid> = bot_ids.iter().map(|bot_id| bot_id.as_uuid()).collect();+ // First-party bots have no row; their names come from the registry.+ let mut names: HashMap<BotId, String> = bot_ids+ .iter()+ .filter_map(|bot_id| bot_id::system_bot(*bot_id).map(|bot| (*bot_id, bot.name.to_owned())))+ .collect();+ let uuids: Vec<Uuid> = bot_ids+ .iter()+ .filter(|bot_id| !bot_id::is_system_bot(**bot_id))+ .map(|bot_id| bot_id.as_uuid())+ .collect();+ if uuids.is_empty() {+ return Ok(names);+ }let rows = sqlx::query!(r#"SELECT id, name@@ -658,10 +670,11 @@ async fn load_bot_display_names().fetch_all(pool).await?;- Ok(rows- .into_iter()- .map(|row| (BotId::new_from_uuid(row.id), row.name))- .collect())+ names.extend(+ rows.into_iter()+ .map(|row| (BotId::new_from_uuid(row.id), row.name)),+ );+ Ok(names)}async fn load_user_display_names(@@ -3885,7 +3898,29 @@ impl ChannelRepo for PgChannelsRepo {return Ok(HashMap::new());}- let ids: Vec<Uuid> = bot_ids.iter().map(|id| id.as_uuid()).collect();+ // First-party bots have no row; their profiles come from the registry.+ let mut profiles: HashMap<BotId, BotSenderProfile> = bot_ids+ .iter()+ .filter_map(|id| {+ bot_id::system_bot(*id).map(|bot| {+ (+ *id,+ BotSenderProfile {+ name: bot.name.to_owned(),+ avatar_url: None,+ },+ )+ })+ })+ .collect();+ let ids: Vec<Uuid> = bot_ids+ .iter()+ .filter(|id| !bot_id::is_system_bot(**id))+ .map(|id| id.as_uuid())+ .collect();+ if ids.is_empty() {+ return Ok(profiles);+ }// Soft-deleted bots are included on purpose so historical messages// keep their sender identity.let rows = sqlx::query!(@@ -3900,17 +3935,15 @@ impl ChannelRepo for PgChannelsRepo {.await.context("unable to fetch bot profiles")?;- Ok(rows- .into_iter()- .map(|row| {- (- BotId::new_from_uuid(row.id),- BotSenderProfile {- name: row.name,- avatar_url: row.avatar_url,- },- )- })- .collect())+ profiles.extend(rows.into_iter().map(|row| {+ (+ BotId::new_from_uuid(row.id),+ BotSenderProfile {+ name: row.name,+ avatar_url: row.avatar_url,+ },+ )+ }));+ Ok(profiles)}}diff --git a/crates/channels/src/outbound/pg_side_effect_context.rs b/crates/channels/src/outbound/pg_side_effect_context.rsindex 1e3f2ab957..d2a28011f9 100644--- a/crates/channels/src/outbound/pg_side_effect_context.rs+++ b/crates/channels/src/outbound/pg_side_effect_context.rs@@ -144,6 +144,13 @@ impl ChannelSideEffectContext for PgChannelSideEffectContext {}async fn get_bot_sender_profile(db: &PgPool, bot_id: BotId) -> Option<BotSenderProfile> {+ // First-party bots have no row; their profile comes from the registry.+ if let Some(system) = bot_id::system_bot(bot_id) {+ return Some(BotSenderProfile {+ name: system.name.to_owned(),+ avatar_url: None,+ });+ }sqlx::query!(r#"SELECT name, avatar_urldiff --git a/crates/macro_db_client/migrations/20260826152838_system_bots_leave_the_bots_table.sql b/crates/macro_db_client/migrations/20260826152838_system_bots_leave_the_bots_table.sqlnew file mode 100644index 0000000000..68ad0bc8f7--- /dev/null+++ b/crates/macro_db_client/migrations/20260826152838_system_bots_leave_the_bots_table.sql@@ -0,0 +1,23 @@+-- First-party bots stop being rows.+--+-- Their ids are compile-time constants (`bot_id::SYSTEM_BOTS`), so a row was+-- only ever a second copy of that: seeded by migration, looked up at runtime,+-- and able to be missing in an environment whose code was already ready.+-- Identity now comes from the registry; `bots` holds user- and team-owned+-- bots only.++-- Dropped before the delete below, and not re-added. The constraint is+-- ON DELETE CASCADE, so removing the system rows while it exists would take+-- every agent_session referencing them along with it. `agent_session.bot_id`+-- is now resolved by the registry-or-row lookup in `BotRepo::get_bot`.+--+-- Nothing relied on the cascade: `BotRepo::delete_bot` soft-deletes (sets+-- deleted_at), so no bot row is ever hard-deleted and the cascade never fired.+ALTER TABLE agent_session DROP CONSTRAINT IF EXISTS agent_session_bot_id_fkey;++DELETE FROM bots WHERE kind = 'system';++-- Enforces the invariant rather than leaving it to convention: no future seed+-- can reintroduce a system row that would shadow the registry.+ALTER TABLE bots+ ADD CONSTRAINT bots_are_owned_only CHECK (kind = 'owned');diff --git a/infra/stacks/agent-harness-service/index.ts b/infra/stacks/agent-harness-service/index.tsindex faa9c49e27..631053e0e3 100644--- a/infra/stacks/agent-harness-service/index.ts+++ b/infra/stacks/agent-harness-service/index.ts@@ -90,15 +90,6 @@ const service = new AgentHarnessService(`agent-harness-service-${stack}`, {name: 'ENVIRONMENT',value: stack,},- ...(stack === 'dev'- ? [- {- // bot_id::MACRO_AI_BOT_ID: @macro runs on the in-process runtime.- name: 'INMEM_BOT_ID',- value: '00000000-0000-0000-0000-00000000a1a1',- },- ]- : []),// Datadog{name: 'DD_SERVICE',diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 826375fc73..11b8114e31 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -67,3 +67,6 @@ tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }tokio-util = { workspace = true, features = ["rt"] }tracing = { workspace = true }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }++[dev-dependencies]+agent_session = { path = "../../crates/agent_session", features = ["test-utils"] }diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 6fd689798f..b1be2c1c6c 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -71,10 +71,16 @@ pub struct Config {pub local_container_network: String,/// The bot this deployment answers for.///- /// Configuration rather than a constant: `@claude` and `@codex` are separate- /// deployments of this same binary, distinguished only by which bot id they- /// watch for. It must be a real `bots` row - `agent_session.bot_id`- /// references it.+ /// Still configuration, because `@claude` and `@codex` are separate+ /// deployments of this same binary distinguished only by the bot they+ /// watch for, and those are user-owned bots with rows.+ ///+ /// Deliberately required, with no default. A default here would be the+ /// same silent-misconfiguration trap this binary already fell into once:+ /// a per-bot deployment that failed to set it would not fail, it would+ /// quietly become a second deployment of whatever the default was, split+ /// the shared consumer group with the real one, and answer half its+ /// mentions.pub harness_bot_id: Uuid,/// Model slug stamped onto sessions this deployment opens.#[macro_config_default(String::from("claude"))]@@ -91,11 +97,6 @@ pub struct Config {/// only works if *their* GitHub App installation can see this repo.#[macro_config_default(String::from("https://github.com/macro-inc/macro"))]pub cursor_repo_url: String,- /// The bot whose sessions run in-process (the in-memory agent). Dev sets- /// this to `bot_id::MACRO_AI_BOT_ID`; unset deployments serve only the- /// sandboxed bot. It must be a real `bots` row because- /// `agent_session.bot_id` references it.- pub inmem_bot_id: Option<Uuid>,/// Model id stamped onto sessions the in-memory bot opens. Unknown ids/// fall back to the agent loop's default model.#[macro_config_default(String::from("claude-sonnet-5"))]diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rsindex 8186bcd8b4..b67e09003a 100644--- a/services/agent_harness_service/src/containers.rs+++ b/services/agent_harness_service/src/containers.rs@@ -8,7 +8,7 @@//! from.use agent_harness::domain::error::{HarnessError, Result};-use agent_harness::domain::model::SpawnContainer;+use agent_harness::domain::model::{AgentKind, SpawnContainer};use agent_harness::domain::ports::ContainerManager;use agent_harness::domain::sandbox::SandboxResizeEffect;use agent_harness::outbound::containers::{HarnessContainer, HarnessContainers};@@ -21,6 +21,9 @@ use agent_session::domain::model::{AgentSessionId, SandboxSize};use agent_session::domain::service::AgentSessionService;use bot_id::BotId;+#[cfg(test)]+mod test;+/// A session transport from whichever runtime the session's bot uses.pub enum RoutedTransport {/// A sandboxed session's sidecar-backed transport.@@ -80,6 +83,7 @@ pub struct RoutedContainers<Sessions> {sessions: Sessions,}+#[derive(Debug)]enum Route {Sandbox,InMem(SessionFacts),@@ -104,25 +108,34 @@ where/// Which runtime serves `session`. The row exists before any container/// operation - `open` creates it first - so the lookup is authoritative.+ ///+ /// Deliberately has no "when in doubt, use the sandbox" branch. The+ /// in-process bot must never be handed a sandbox: it has no repository to+ /// clone and no reason to cost a Daytona container, so a deployment that+ /// cannot serve it refuses the session instead of silently provisioning+ /// the wrong runtime for it.async fn route(&self, session: AgentSessionId) -> Result<Route> {- let Some(inmem) = &self.inmem else {- return Ok(Route::Sandbox);- };let row = self.sessions.get_session(session).await.map_err(HarnessError::Session)?;- if row.bot_id == inmem.bot {- Ok(Route::InMem(SessionFacts {+ if let Some(inmem) = &self.inmem+ && row.bot_id == inmem.bot+ {+ return Ok(Route::InMem(SessionFacts {id: session,owner: row.owner_id,model: row.model,acp_session_id: row.acp_session_id,- }))- } else {- Ok(Route::Sandbox)+ }));+ }+ if AgentKind::of(row.bot_id) == AgentKind::InMemory {+ return Err(HarnessError::Container(format!(+ "session {session} belongs to the in-process bot, which this deployment does not serve"+ )));}+ Ok(Route::Sandbox)}fn inmem(&self) -> &InMemRuntime {diff --git a/services/agent_harness_service/src/containers/test.rs b/services/agent_harness_service/src/containers/test.rsnew file mode 100644index 0000000000..27980aa0c5--- /dev/null+++ b/services/agent_harness_service/src/containers/test.rs@@ -0,0 +1,74 @@+use super::*;+use agent_fold::domain::service::FoldedMessageService;+use agent_harness::outbound::daytona::{AnthropicApiKey, GithubToken};+use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};+use agent_session::domain::ports::NoOpRealtime;+use agent_session::domain::service::AgentSessionServiceImpl;+use agent_session::testing::{InMemoryAgentSessionRepo, test_agent_session};++/// A sandbox provider the tests never reach: every case here is decided by+/// `route` before the provider is asked for anything.+fn unreachable_sandbox() -> HarnessContainers {+ HarnessContainers::Local(LocalContainerManager::new(LocalSettings {+ docker_binary: "false".to_owned(),+ image: "unused".to_owned(),+ network: "unused".to_owned(),+ github_token: GithubToken::new(String::new()),+ anthropic_api_key: AnthropicApiKey::new(String::new()),+ }))+}++fn sessions_with(bot: BotId) -> (AgentSessionId, impl AgentSessionService + use<>) {+ let repo = InMemoryAgentSessionRepo::new();+ let id = AgentSessionId::new();+ let mut session = test_agent_session(id);+ session.bot_id = bot;+ repo.insert_session(session);+ let service =+ AgentSessionServiceImpl::new(repo.clone(), FoldedMessageService::new(repo), NoOpRealtime);+ (id, service)+}++/// The whole point of the refusal: `@macro`'s sessions have no repository to+/// clone, so a deployment that cannot run them in-process must not quietly+/// bill a sandbox for one.+#[tokio::test]+async fn refuses_the_in_process_bot_when_no_in_memory_runtime_is_configured() {+ let (id, sessions) = sessions_with(bot_id::MACRO_AI_BOT_ID);+ let containers = RoutedContainers::new(unreachable_sandbox(), None, sessions);++ let error = containers+ .route(id)+ .await+ .expect_err("a deployment without the in-process runtime must refuse its bot");++ assert!(+ matches!(error, HarnessError::Container(message) if message.contains("in-process bot")),+ "expected a refusal naming the in-process bot"+ );+}++/// The sandboxed bot is unaffected by the refusal above.+#[tokio::test]+async fn routes_the_sandboxed_bot_to_the_sandbox() {+ let (id, sessions) = sessions_with(bot_id::MACRO_CODER_BOT_ID);+ let containers = RoutedContainers::new(unreachable_sandbox(), None, sessions);++ assert!(matches!(+ containers.route(id).await.expect("coder routes"),+ Route::Sandbox+ ));+}++/// So is a user-owned bot, which is what an `@claude` deployment serves.+#[tokio::test]+async fn routes_an_owned_bot_to_the_sandbox() {+ let owned = BotId::new_from_uuid(macro_uuid::Uuid::from_u128(0x0000_1234));+ let (id, sessions) = sessions_with(owned);+ let containers = RoutedContainers::new(unreachable_sandbox(), None, sessions);++ assert!(matches!(+ containers.route(id).await.expect("owned bot routes"),+ Route::Sandbox+ ));+}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex b874fbc8c6..20ec86adab 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -122,7 +122,15 @@ async fn run() -> anyhow::Result<()> {agent_harness::install_tls_provider();let config = Config::from_env()?;let bot_id = BotId::new_from_uuid(config.harness_bot_id);- let inmem_bot = config.inmem_bot_id.map(BotId::new_from_uuid);+ // The in-process Macro bot is a compile-time identity, not configuration:+ // it is always `bot_id::MACRO_AI_BOT_ID`, so the only real question is+ // whether this environment serves it. Production stays off until its AI+ // tool config lands - `build_tool_service_context_from_env` below is+ // fatal, so turning it on without that config would refuse to boot.+ let inmem_bot = match config.environment {+ Environment::Local | Environment::Develop => Some(bot_id::MACRO_AI_BOT_ID),+ Environment::Production => None,+ };let pool = PgPoolOptions::new().min_connections(1)@@ -269,6 +277,15 @@ async fn run() -> anyhow::Result<()> {.chain(inmem_bot).chain(std::iter::once(bot_id::CURSOR_BOT_ID)).collect();+ // Logged because the failure mode this replaced was silent: a harness that+ // resolved no in-process bot booted healthy, passed its health check, and+ // dropped every `@macro` mention as ForeignBot with nothing to show for it.+ tracing::info!(+ bots = ?our_bots.iter().map(|bot| bot.as_uuid()).collect::<Vec<_>>(),+ in_process_bot = ?inmem_bot.map(BotId::as_uuid),+ environment = %config.environment,+ "agent harness serving bots"+ );let containers =RoutedContainerManager::new(sandbox_and_inmem, cursor_manager, session_repo.clone());let notifications = Arc::new(notification::domain::service::SqsNotificationIngress {diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex 5cdea5c726..b0187abb0e 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -274,8 +274,9 @@ impl MailEnv {/// still clone.////// Two managed bots: `@coder` (`HARNESS_BOT_ID`) gets a sandbox from the-/// local Docker provider, and `@macro` (`INMEM_BOT_ID`) runs in-process on-/// the in-memory ACP runtime.+/// local Docker provider, and `@macro` runs in-process on the in-memory ACP+/// runtime. Only the first is configured - `@macro` is `bot_id::MACRO_AI_BOT_ID`+/// in code, served wherever `ENVIRONMENT` is not production.struct AgentHarnessEnv {bot_id: &'static str,snapshot: &'static str,@@ -290,7 +291,7 @@ struct AgentHarnessEnv {impl AgentHarnessEnv {fn local(project_name: &str) -> Self {AgentHarnessEnv {- // bot_id::MACRO_CODER_BOT_ID, seeded by the bots_has_agent migration.+ // bot_id::MACRO_CODER_BOT_ID, a first-party bot with no row.bot_id: "00000000-0000-0000-0000-00000000a9e7",snapshot: "macro-agent-harness",image: super::sandbox_image::DEFAULT_LOCAL_TAG,@@ -301,12 +302,6 @@ impl AgentHarnessEnv {fn write(&self, env: &mut BTreeMap<String, String>) {env.insert("HARNESS_BOT_ID".into(), self.bot_id.into());- // bot_id::MACRO_AI_BOT_ID: @macro's sessions run on the in-process- // ACP runtime, while @coder's get sandboxes from the local provider.- env.insert(- "INMEM_BOT_ID".into(),- "00000000-0000-0000-0000-00000000a1a1".into(),- );env.insert("DAYTONA_SNAPSHOT".into(), self.snapshot.into());env.insert("DAYTONA_API_KEY".into(), String::new());env.insert("DEV_DANGEROUS_LOCAL_CONTAINERS".into(), "true".into());