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(agent_session): typed owner in session model and API (#6693)
Will Hutchinsonae501c0dba90
diff --git a/Cargo.lock b/Cargo.lockindex 12d500eb3f..6c1515ac08 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -232,6 +232,7 @@ dependencies = ["macro_auth","macro_db_client","macro_user_id",+ "model_owner","pipedream_mcp","rand 0.9.4","reqwest 0.13.4",@@ -319,6 +320,7 @@ dependencies = ["mockall","model-entity","model_notifications",+ "model_owner","model_user","notification","opentelemetry",@@ -453,6 +455,7 @@ dependencies = ["mcp_toolset","memory","model-entity",+ "model_owner","non_empty","opentelemetry","opentelemetry_sdk",@@ -573,6 +576,7 @@ dependencies = ["macro_uuid","messages","mockall",+ "model_owner","serde","serde_json","sqlx",diff --git a/crates/agent_changes/src/domain/pull_request.rs b/crates/agent_changes/src/domain/pull_request.rsindex a1082aef77..e334e021c5 100644--- a/crates/agent_changes/src/domain/pull_request.rs+++ b/crates/agent_changes/src/domain/pull_request.rs@@ -31,7 +31,12 @@ impl<Reader: PullRequestDiffReader> ChangesetExtractor for PullRequestChanges<Relet pull_request = PullRequestRef::parse(url).ok_or_else(|| {ExtractError::NotReady("The linked URL is not a GitHub pull request.".to_owned())})?;- let diff = self.reader.read(&session.owner_id, &pull_request).await.map_err(|error| match error {+ // The diff is read through the GitHub App on the owner's behalf, so+ // the owner has to be a person.+ let owner = session+ .owner_user()+ .map_err(|error| ExtractError::Failed(rootcause::report!(error).into()))?;+ let diff = self.reader.read(owner, &pull_request).await.map_err(|error| match error {CompareError::NotFound => ExtractError::NotReady("The linked pull request is not available on GitHub.".to_owned()),CompareError::TooLarge => ExtractError::NotReady("This pull request is too large to load here. Review it on GitHub.".to_owned()),CompareError::Unavailable => ExtractError::NotReady("Macro's GitHub App cannot read this pull request. Check its repository access.".to_owned()),diff --git a/crates/agent_egress/Cargo.toml b/crates/agent_egress/Cargo.tomlindex 1db3eb7ce7..ae9d860484 100644--- a/crates/agent_egress/Cargo.toml+++ b/crates/agent_egress/Cargo.toml@@ -33,6 +33,7 @@ macro_auth = { path = "../macro_auth" }# The owner's `User` row, which carries the FusionAuth id the exchange needs.macro_db_client = { path = "../macro_db_client" }macro_user_id = { path = "../macro_user_id" }+model_owner = { path = "../model_owner" }# The rows saying which apps an owner connected, and the client that turns one# into Pipedream's MCP endpoint plus the headers scoping a call to it.pipedream_mcp = { path = "../pipedream_mcp" }diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rsindex 8b9d904cba..c612a07a4a 100644--- a/crates/agent_egress/src/outbound/session_authority.rs+++ b/crates/agent_egress/src/outbound/session_authority.rs@@ -17,6 +17,7 @@use agent_session::domain::ports::AgentSessionRepo;use agent_session::domain::{credentials::authenticate_session, error::AgentSessionError};+use model_owner::Owner;use crate::domain::error::EgressError;use crate::domain::model::{McpServerListing, McpServerSlug, RepoSlug, SessionGrant, SessionToken};@@ -56,6 +57,20 @@ where)),})?;+ // The grant is a person's: everything egress does, it does with the+ // owner's credentials, and a bot or team has none to spend. Refused+ // as an admission the token fails, in our own fixed words like every+ // other gate here, rather than resolved as though the owner were a+ // user.+ let owner = match &session.owner_id {+ Owner::User(owner) => owner.clone(),+ Owner::Bot(_) | Owner::Team(_) => {+ return Err(EgressError::Unauthenticated(+ "the session is not owned by a user",+ ));+ }+ };+// A repository is optional for MCP-only sessions. The domain service// requires one only for git requests; a malformed stored URL still// indicates a configuration error.@@ -92,7 +107,7 @@ whereOk(SessionGrant {session: session.id,- owner: session.owner_id,+ owner,repo,mcp_servers,})diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex b4b77d2713..43db767190 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -50,6 +50,7 @@ macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }+model_owner = { path = "../model_owner" }notification = { path = "../notification" }messages = { path = "../messages", features = ["broker", "ports"] }opentelemetry = { workspace = true, features = ["trace"] }diff --git a/crates/agent_harness/src/domain/claude.rs b/crates/agent_harness/src/domain/claude.rsindex e0d0086493..453df5a2e5 100644--- a/crates/agent_harness/src/domain/claude.rs+++ b/crates/agent_harness/src/domain/claude.rs@@ -51,7 +51,7 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>) -> Result<String> {let row = self.repo.get(id).await?;let egress = provisioner- .provision(id, &row.owner_id, &row.mcp_servers)+ .provision(id, row.owner_user()?, &row.mcp_servers).await?;self.repo.set_egress_token_hash(id, &egress.session_token_hash)@@ -81,7 +81,7 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>}let row = AgentSessionRepo::get(&self.repo, id).await?;self.provider- .connect(row.owner_id.as_ref())+ .connect(row.owner_user()?.as_ref()).await.map_err(cloud_error)?.archive(&SessionId::parse(&external.external_id).map_err(cloud_error)?)@@ -98,7 +98,7 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>claude_cloud_agents::domain::models::Model::parse(&row.model).map_err(cloud_error)?;let client = self.provider- .connect(row.owner_id.as_ref())+ .connect(row.owner_user()?.as_ref()).await.map_err(cloud_error)?;let external = ExternalSessionRepo::get(&self.external, id).await?;diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rsindex ccbdb35538..42e370eb52 100644--- a/crates/agent_harness/src/domain/claude/test.rs+++ b/crates/agent_harness/src/domain/claude/test.rs@@ -153,7 +153,9 @@ async fn seed(repo_branch: None,id,bot_id: bot,- owner_id: macro_user_id::user_id::MacroUserIdStr::try_from(owner.to_owned()).unwrap(),+ owner_id: model_owner::Owner::User(+ macro_user_id::user_id::MacroUserIdStr::try_from(owner.to_owned()).unwrap(),+ ),thread_id: None,originating_message_id: None,model: "claude-default".into(),diff --git a/crates/agent_harness/src/domain/codex/test/selection.rs b/crates/agent_harness/src/domain/codex/test/selection.rsindex 40dc205107..129ef7c4dc 100644--- a/crates/agent_harness/src/domain/codex/test/selection.rs+++ b/crates/agent_harness/src/domain/codex/test/selection.rs@@ -79,7 +79,7 @@ fn configured_runtime() -> (provider.clone(),);let mut current = agent_session::testing::test_agent_session(runtime.session);- current.owner_id = runtime.owner.clone();+ current.owner_id = model_owner::Owner::User(runtime.owner.clone());runtime.session_repository.insert_session(current);(Arc::new(runtime), connections, provider)}diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rsindex 1a69ea9160..167c47a2aa 100644--- a/crates/agent_harness/src/domain/ports/test.rs+++ b/crates/agent_harness/src/domain/ports/test.rs@@ -32,7 +32,7 @@ fn params(id: AgentSessionId) -> CreateAgentSessionParams {CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: model_owner::Owner::User(owner()),bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),thread_id: None,originating_message_id: None,diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rsindex 9ba71a56b9..edaa8b78e1 100644--- a/crates/agent_harness/src/domain/service/deliver.rs+++ b/crates/agent_harness/src/domain/service/deliver.rs@@ -78,7 +78,11 @@ whereif AgentKind::for_session(session.bot_id, &session.harness).is_managed() {let container = self.containers.resume(session_id).await?;let mcp_servers = self- .resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)+ .resumed_mcp_servers(+ session_id,+ session.owner_user()?,+ &session.mcp_servers,+ ).await?;self.sessions.attach_session(@@ -110,7 +114,7 @@ where.egress.provision(session_id,- &session.owner_id,+ session.owner_user()?,&AgentMcpServers::Selected {servers: Vec::new(),},diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rsindex 2bea123967..a1842117ee 100644--- a/crates/agent_harness/src/domain/service/lifecycle.rs+++ b/crates/agent_harness/src/domain/service/lifecycle.rs@@ -294,6 +294,9 @@ wheresize: SandboxSize,) -> Result<()> {let session = self.sessions.get_session(session_id).await?;+ // The size is remembered as the owner's preference, so this is a+ // person's operation: asked first, before anything is closed.+ let owner = session.owner_user()?;let effect = self.containers.resize_effect(session.sandbox_size, size);// Only a sandboxed coder has a sandbox to act on: a Cursor session// runs in Cursor's cloud, the in-memory bot has no sandbox, and an@@ -309,7 +312,7 @@ whereif effect == SandboxResizeEffect::Restart {let container = self.containers.resume(session_id).await?;let mcp_servers = self- .resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)+ .resumed_mcp_servers(session_id, owner, &session.mcp_servers).await?;let permission_policy = self.permission_policy_for(session.bot_id).await;self.sessions@@ -323,9 +326,7 @@ where}}self.sessions.set_sandbox_size(session_id, size).await?;- self.sessions- .set_user_sandbox_size(&session.owner_id, size)- .await?;+ self.sessions.set_user_sandbox_size(owner, size).await?;Ok(())}}diff --git a/crates/agent_harness/src/domain/service/lifecycle_events.rs b/crates/agent_harness/src/domain/service/lifecycle_events.rsindex 76c1ca686a..7615756c17 100644--- a/crates/agent_harness/src/domain/service/lifecycle_events.rs+++ b/crates/agent_harness/src/domain/service/lifecycle_events.rs@@ -59,7 +59,7 @@ whereself.sessions.session_bot(session.bot_id),self.sessions.session_participants(session.id),)?;- Ok(session_identity(session, &bot, participants))+ Ok(session_identity(session, &bot, participants)?)}/// Publish one fact about `session_id`, built once its identity is known,diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 925443cb72..e3ac7ef335 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -4,6 +4,7 @@use agent_session::domain::ports::SelectedManagedPersona;use agent_session::domain::repository_branch::RepositoryBranch;+use model_owner::Owner;use super::*;use crate::domain::model::SessionRepository;@@ -55,13 +56,22 @@ where&self,request: agent_session::domain::ports::OpenExternalAgentSession,) -> agent_session::domain::error::Result<AgentSession> {+ // An external session is opened as a person: the thread it claims is+ // checked against what they may post in, and the announcement is+ // made in their name. Any other kind of owner is refused before a+ // row exists for it.+ let owner_user = request+ .owner+ .as_user()+ .cloned()+ .ok_or_else(|| AgentSessionError::OwnerNotUser(request.owner.owner_type()))?;// The thread linkage is the caller's claim: it is honoured only when// the owner can write to that parent and the message sits in it.if let Some(thread) = &request.thread {self.inner.prompt_context.authorize_origin(- &request.owner,+ &owner_user,&AnnounceOrigin {parent: thread.parent.clone(),thread_id: thread.thread_id,@@ -89,7 +99,7 @@ where.create_session(CreateAgentSessionParams {repo_branch: None,id: AgentSessionId::new(),- owner_id: request.owner.clone(),+ owner_id: request.owner,bot_id: request.bot_id,thread_id: request.thread.as_ref().map(|thread| thread.thread_id),originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),@@ -119,7 +129,7 @@ whereorigin_message_id: thread.message_id,prompted_message_id: MessageId::first(AuthorKind::User),prompted_content: thread.content,- triggered_by: request.owner,+ triggered_by: owner_user,};if let Err(error) = self.inner.announcer.announce(announcement).await {tracing::warn!(@@ -186,6 +196,16 @@ whereservers: Vec::new(),};}+ // A managed session runs as its owner: its egress spends their+ // connected apps, the repositories it may pick are the ones they+ // reach, and its sandbox size is their preference. Only a person has+ // those, so any other kind of owner is refused before anything is+ // provisioned.+ let owner_user = request+ .owner+ .as_user()+ .cloned()+ .ok_or_else(|| AgentSessionError::OwnerNotUser(request.owner.owner_type()))?;// Explicit source choices are a domain decision, before any session or egress grant exists.let selected_repo = if let Some(url) = request.repo_url.as_deref() {if kind != AgentKind::Cursor {@@ -205,7 +225,7 @@ where.as_ref().ok_or(agent_session::domain::error::AgentSessionError::Forbidden)?;let reachable = repositories- .for_user(&request.owner)+ .for_user(&owner_user).await.map_err(into_session_error)?;let listed = reachable@@ -229,11 +249,7 @@ whereNone};let defaults = self.inner.defaults.for_bot(bot_id);- let sandbox_size = self- .inner- .sessions- .user_sandbox_size(&request.owner)- .await?;+ let sandbox_size = self.inner.sessions.user_sandbox_size(&owner_user).await?;let session_id = AgentSessionId::new();// Same ordering as the trigger path's open: the token has to be minted// before the row, because the row is what carries the hash that makes@@ -241,7 +257,7 @@ wherelet egress = self.inner.egress- .provision(session_id, &request.owner, &mcp_servers)+ .provision(session_id, &owner_user, &mcp_servers).await.map_err(into_session_error)?;let session = self@@ -250,7 +266,7 @@ where.create_session(CreateAgentSessionParams {repo_branch: selected_repo.as_ref().map(|(_, branch)| branch.clone()),id: session_id,- owner_id: request.owner.clone(),+ owner_id: request.owner,bot_id,thread_id: None,originating_message_id: None,@@ -330,7 +346,7 @@ whereHarnessCommand::Deliver(DeliverAction {id: AgentActionId::mint(),action: AgentAction::prompt(raw_prompt),- actor: Some(request.owner),+ actor: Some(owner_user),announce: None,}),)@@ -477,7 +493,7 @@ where.create_session(CreateAgentSessionParams {repo_branch: None,id: session_id,- owner_id: origin.sender.clone(),+ owner_id: Owner::User(origin.sender.clone()),bot_id,thread_id: Some(origin.thread_id),originating_message_id: Some(origin.message_id),diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rsindex bf55ed9169..4f5c19995c 100644--- a/crates/agent_harness/src/domain/service/queue.rs+++ b/crates/agent_harness/src/domain/service/queue.rs@@ -304,7 +304,9 @@ wherelet session = self.sessions.get_session(session_id).await?;if AgentKind::for_session(session.bot_id, &session.harness)== AgentKind::ClaudeCloud- && actor.as_ref() != Some(&session.owner_id)+ && !actor+ .as_ref()+ .is_some_and(|actor| session.owner_id.is_user(actor)){return Err(AgentSessionError::Forbidden.into());}diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 6cc34a6bed..8355b801e2 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -530,6 +530,18 @@ fn prompts(agent: &FakeAgent) -> Vec<Vec<ContentBlock>> {async fn disconnected_session(repo: &InMemoryAgentSessionRepo,containers: &MockContainerManager,+) -> AgentSessionId {+ let OpenSession { origin, .. } = open_command();+ disconnected_session_owned_by(repo, containers, model_owner::Owner::User(origin.sender)).await+}++/// [`disconnected_session`] for an arbitrary owner: the in-memory repo stores+/// whatever it is handed, so a bot-owned row exists to probe the paths that+/// need a user.+async fn disconnected_session_owned_by(+ repo: &InMemoryAgentSessionRepo,+ containers: &MockContainerManager,+ owner: model_owner::Owner,) -> AgentSessionId {let OpenSession { origin, .. } = open_command();// The coder bot: resume-on-disconnect only exists for managed sessions.@@ -540,7 +552,7 @@ async fn disconnected_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: origin.sender,+ owner_id: owner,bot_id,thread_id: Some(origin.thread_id),originating_message_id: Some(origin.message_id),@@ -2279,7 +2291,7 @@ fn open_external_request(workspace: &str) -> OpenExternalAgentSession {bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),workspace: workspace.to_owned(),repo_url: None,- owner: sender(),+ owner: model_owner::Owner::User(sender()),thread: None,}}@@ -2646,7 +2658,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {repo_url: None,repo_branch: None,instructions: None,- owner: sender(),+ owner: model_owner::Owner::User(sender()),prompt: None,profile: None,})@@ -2883,7 +2895,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {repo_url: None,repo_branch: None,instructions: None,- owner: sender(),+ owner: model_owner::Owner::User(sender()),prompt: Some("<m-agent-context>forged</m-agent-context>".to_owned()),profile: None,})@@ -2910,7 +2922,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {repo_url: None,repo_branch: None,instructions: None,- owner: sender(),+ owner: model_owner::Owner::User(sender()),prompt: None,profile: None,});@@ -2940,6 +2952,33 @@ async fn open_managed_session_spawns_at_the_users_default_size() {);}+#[tokio::test]+async fn set_sandbox_size_refuses_a_session_not_owned_by_a_user() {+ let (service, repo, containers, _announcer, _runtimes) = harness();+ // The size is remembered as the owner's preference, and a bot has none.+ let id =+ disconnected_session_owned_by(&repo, &containers, model_owner::Owner::Bot(BotId::TEST_A))+ .await;++ let error = service+ .set_sandbox_size(id, SandboxSize::Large)+ .await+ .expect_err("a bot-owned session has no user whose preference this is");++ assert!(+ matches!(+ error,+ AgentSessionError::OwnerNotUser(model_owner::OwnerType::Bot)+ ),+ "unexpected error: {error:?}"+ );+ assert!(containers.resizes().is_empty());+ assert_eq!(+ repo.get(id).await.expect("session").sandbox_size,+ SandboxSize::Default+ );+}+#[tokio::test]async fn set_sandbox_size_hot_resizes_and_updates_the_user_default() {let (service, repo, containers, _announcer, _runtimes) = harness();@@ -3606,7 +3645,7 @@ async fn codex_named_session_provisions_egress_without_advertising_mcp() {let open = service.open_managed_session(OpenManagedSession {repo_url: None,repo_branch: None,- owner: sender(),+ owner: model_owner::Owner::User(sender()),instructions: None,prompt: Some("inspect".into()),profile: Some(agent_session::domain::ports::SelectedManagedPersona {@@ -3727,7 +3766,7 @@ impl crate::domain::ports::ReachableRepositories for SelectedRepositories {fn explicit_cursor_request() -> OpenManagedSession {OpenManagedSession {- owner: sender(),+ owner: model_owner::Owner::User(sender()),instructions: None,prompt: None,repo_url: Some("https://github.com/macro-inc/macro".into()),diff --git a/crates/agent_harness/src/domain/service/test/reopen.rs b/crates/agent_harness/src/domain/service/test/reopen.rsindex c0559b5654..f31c100794 100644--- a/crates/agent_harness/src/domain/service/test/reopen.rs+++ b/crates/agent_harness/src/domain/service/test/reopen.rs@@ -10,7 +10,7 @@ async fn codex_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: sender(),+ owner_id: model_owner::Owner::User(sender()),bot_id: bot_id::CODEX_BOT_ID,thread_id: None,originating_message_id: None,diff --git a/crates/agent_harness/src/outbound/codex.rs b/crates/agent_harness/src/outbound/codex.rsindex 72e2b53cb5..d729d3e95b 100644--- a/crates/agent_harness/src/outbound/codex.rs+++ b/crates/agent_harness/src/outbound/codex.rs@@ -77,15 +77,18 @@ impl<"Codex connection encryption is not configured on this deployment".into(),)})?;+ // Codex work is paid for by the owner's connection, which only a+ // person has.+ let owner = row.owner_user()?.clone();let resolved = connections- .resolve(row.owner_id.as_ref())+ .resolve(owner.as_ref()).await.map_err(|e| HarnessError::Container(e.to_string()))?;let claim = Arc::new(std::sync::OnceLock::new());let runtime = Arc::new(CodexRuntime {provider: self.provider.clone(),connections,- owner: row.owner_id.clone(),+ owner,binding: RuntimeIdentity {connection_id: resolved.connection_id.to_string(),account_id: resolved.credentials.account_id.clone(),diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rsindex ee703288b8..168854ee68 100644--- a/crates/agent_harness/src/outbound/cursor/manager.rs+++ b/crates/agent_harness/src/outbound/cursor/manager.rs@@ -284,7 +284,10 @@ wherefields(agent.session.id = %session.id))]async fn client_for(&self, session: &AgentSession) -> Result<(CursorClient, Option<String>)> {- let config = self.keys.resolve(&session.owner_id).await?;+ // The key is a person's: a session owned by anything else has no+ // Cursor account to run on, and is refused here rather than resolved+ // as though it did.+ let config = self.keys.resolve(session.owner_user()?).await?;let client = CursorClient::new(CursorConfig {api_key: ApiKey::new(config.key.expose()),base_url: self.base_url.clone(),@@ -322,6 +325,7 @@ whererestore: Option<RestoredCursorSession>,) -> Result<agent_session::domain::connection::RuntimeAttachment<PipeTransport>> {let session_id = session.id;+ let owner = session.owner_user()?.clone();let owner_binding: Option<agent_session::domain::connection::AttachmentActivation>;let journal: Arc<dyn cursor_cloud_agents::domain::journal::CursorJournal> = match &self.journal_storage@@ -367,7 +371,7 @@ wheresuper::pull_request::CursorPullRequestReporter {service: service.clone(),session: session_id,- owner: session.owner_id.clone(),+ owner: owner.clone(),},));}@@ -378,7 +382,7 @@ whereArc::clone(&self.repositories),self.sessions.clone(),Arc::clone(&self.usage),- session.owner_id.clone(),+ owner,session_id,);let service = Arc::new(diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex a22cb472d2..64364f134f 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -80,8 +80,10 @@ impl AgentSessionRepo for StubSessions {Ok(AgentSession {repo_branch: self.repo_branch.clone(),id,- owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned())- .expect("valid user id"),+ owner_id: model_owner::Owner::User(+ MacroUserIdStr::try_from("macro|[email protected]".to_owned())+ .expect("valid user id"),+ ),thread_id: None,thread_parent: None,originating_message_id: None,diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex a20a2b8e62..4e344d0749 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -140,8 +140,10 @@ impl AgentSessionRepo for FixedBotSessions {repo_branch: None,pull_request_url: None,id,- owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned())- .expect("valid user id"),+ owner_id: model_owner::Owner::User(+ MacroUserIdStr::try_from("macro|[email protected]".to_owned())+ .expect("valid user id"),+ ),thread_id: None,thread_parent: None,originating_message_id: None,diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.tomlindex 8582cd90df..b3d04c8a9d 100644--- a/crates/agent_inmem/Cargo.toml+++ b/crates/agent_inmem/Cargo.toml@@ -25,6 +25,7 @@ dashmap = { workspace = true }futures = { workspace = true }genai_telemetry = { path = "../genai_telemetry" }macro_user_id = { path = "../macro_user_id" }+model_owner = { path = "../model_owner" }http = { workspace = true }http-body-util = { workspace = true }macro_uuid = { path = "../macro_uuid" }diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rsindex 9486c806bf..5d9db19719 100644--- a/crates/agent_inmem/src/domain/agent.rs+++ b/crates/agent_inmem/src/domain/agent.rs@@ -37,7 +37,7 @@ use ai_tools::user_tool_review::{ReviewError, ReviewFieldKind, ReviewForm, ReviewOutcome, ReviewRequest, UserToolReviewer,};use async_trait::async_trait;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use tokio_util::sync::CancellationToken;use tracing::Instrument as _;@@ -104,7 +104,7 @@ pub struct AgentState {/// The Macro session this agent runs.pub session_id: AgentSessionId,/// The session's owner; turns run on their behalf.- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// Runs the actual turns.pub engine: Arc<dyn TurnEngine>,/// Conversation state, shared with the manager so it survives reattach.diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rsindex 24ea5cd90c..f07ba681a4 100644--- a/crates/agent_inmem/src/domain/agent/test.rs+++ b/crates/agent_inmem/src/domain/agent/test.rs@@ -13,6 +13,7 @@ use rig_agent::completion::PromptError;use super::*;use crate::domain::engine::TurnEngine;use crate::testing::{HangingEngine, ScriptedEngine};+use macro_user_id::user_id::MacroUserIdStr;struct Harness {notifications: std::sync::Mutex<Vec<SessionNotification>>,@@ -60,7 +61,9 @@ where);let state = Arc::new(AgentState {session_id,- owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ owner: model_owner::Owner::User(+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ ),engine,store,active_cancel: std::sync::Mutex::new(Vec::new()),@@ -560,7 +563,9 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {);let state = Arc::new(AgentState {session_id,- owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ owner: model_owner::Owner::User(+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ ),engine: Arc::new(ScriptedEngine::new(Vec::new())),store,active_cancel: std::sync::Mutex::new(Vec::new()),@@ -651,7 +656,9 @@ where);let state = Arc::new(AgentState {session_id,- owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ owner: model_owner::Owner::User(+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),+ ),engine,store,active_cancel: std::sync::Mutex::new(Vec::new()),diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rsindex 2cfa4ba279..18b5e19a17 100644--- a/crates/agent_inmem/src/domain/engine.rs+++ b/crates/agent_inmem/src/domain/engine.rs@@ -5,8 +5,8 @@ use std::sync::Arc;use agent::types::ChatMessage;use agent::{AgentError, StreamPart};use ai_tools::user_tool_review::UserToolReviewer;-use macro_user_id::user_id::MacroUserIdStr;use mcp_toolset::RemoteMcpToolSet;+use model_owner::Owner;use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;@@ -23,9 +23,10 @@ pub struct AgentIdentity {/// Everything one conversational turn needs.pub struct TurnRequest {- /// The user the turn acts on behalf of. Tools run with their identity and- /// token usage is recorded against them.- pub owner: MacroUserIdStr<'static>,+ /// The session's owner, whom the turn acts on behalf of: tools run with+ /// their identity and token usage is recorded against them. Both need a+ /// person, which the engine asks of this rather than assumes.+ pub owner: Owner,/// Model id the turn runs on. Unknown ids fall back to the loop's/// default model rather than failing the turn.pub model: String,diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rsindex c43bfe4ceb..34790aa074 100644--- a/crates/agent_inmem/src/outbound/manager.rs+++ b/crates/agent_inmem/src/outbound/manager.rs@@ -14,7 +14,7 @@ use agent_runtime_protocol::domain::connection::{RuntimeConnection, ServerChanneuse agent_runtime_protocol::domain::schema::v0::SystemEvent;use agent_session::domain::model::AgentSessionId;use dashmap::DashMap;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use crate::domain::agent::{AgentState, serve};use crate::domain::engine::{AgentIdentity, TurnEngine};@@ -31,7 +31,7 @@ pub struct SessionFacts {/// The session the agent serves.pub id: AgentSessionId,/// The session's owner; turns act on their behalf.- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// Model id stamped on the session row.pub model: String,/// The bot's display name and `@` handle, folded into every turn'sdiff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rsindex 54e0cf7be0..4751f27908 100644--- a/crates/agent_inmem/src/outbound/manager/test.rs+++ b/crates/agent_inmem/src/outbound/manager/test.rs@@ -17,6 +17,7 @@ use agent_session::domain::service::{AgentSessionService, AgentSessionServiceImpuse agent_session::testing::InMemoryAgentSessionRepo;use bot_id::BotId;use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use super::*;use crate::domain::engine::AgentIdentity;@@ -101,7 +102,7 @@ fn manager(repo: &InMemoryAgentSessionRepo, engine: Arc<ScriptedEngine>) -> InMefn facts(id: AgentSessionId) -> SessionFacts {SessionFacts {id,- owner: owner(),+ owner: Owner::User(owner()),model: "test-model".to_owned(),identity: None,instructions: None,@@ -169,7 +170,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {.create_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: Owner::User(owner()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,@@ -309,7 +310,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {.create_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: Owner::User(owner()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,@@ -456,7 +457,7 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {.create_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: Owner::User(owner()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,@@ -531,7 +532,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {.create_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: Owner::User(owner()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,@@ -591,7 +592,7 @@ async fn identity_reaches_every_turn_including_after_a_reattach() {.create_session(CreateAgentSessionParams {repo_branch: None,id,- owner_id: owner(),+ owner_id: Owner::User(owner()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rsindex 55b9ffccf7..b1f8f56c92 100644--- a/crates/agent_inmem/src/rig_engine.rs+++ b/crates/agent_inmem/src/rig_engine.rs@@ -33,6 +33,7 @@ use macro_user_id::user_id::MacroUserIdStr;use memory::domain::MemoryService as _;use memory::domain::service::MemoryServiceImpl;use memory::outbound::pg_memory_repo::PgMemoryRepo;+use model_owner::Owner;use sqlx::PgPool;use tokio::sync::mpsc;use tracing::Instrument as _;@@ -133,6 +134,21 @@ async fn drive_turn(reviewer,} = request;+ // A turn runs as a person: tools act with the owner's identity, the+ // memory is theirs, and usage is billed to them. A session owned by+ // anything else has no turn to run here, and says so instead of running+ // as somebody it is not.+ let owner = match owner {+ Owner::User(owner) => owner,+ other => {+ return Err(AgentError::Other(anyhow::anyhow!(+ "in-process turns run as the session owner, who must be a user; \+ this session is owned by a {}",+ other.owner_type()+ )));+ }+ };+// Chat's tools with the session's prompt: the user tools (`SendEmail`,// `CreateCalendarEvent`) defer to the user, and this runtime finishes// them in the turn through `reviewer`.diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 07d7952297..2d997878b3 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -27,7 +27,6 @@ outbound = ["dep:entity_access_db_utils","dep:entity_registry_db_utils","dep:model-entity",- "dep:model_owner","dep:sqlx","macro_user_id/sqlx",]@@ -67,7 +66,7 @@ entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }genai_telemetry = { path = "../genai_telemetry" }model-entity = { path = "../model-entity", optional = true }-model_owner = { path = "../model_owner", optional = true }+model_owner = { path = "../model_owner" }clap = { workspace = true, optional = true }macro_authorization = { path = "../macro_authorization", default-features = false, optional = true }macro_user_id = { path = "../macro_user_id" }diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rsindex c11535e389..24363b563d 100644--- a/crates/agent_session/src/bin/seed_jsonl.rs+++ b/crates/agent_session/src/bin/seed_jsonl.rs@@ -241,7 +241,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {CreateAgentSessionParams {repo_branch: None,id: session_id,- owner_id: owner,+ owner_id: model_owner::Owner::User(owner),bot_id: BotId::new_from_uuid(args.bot_id),thread_id: None,originating_message_id: None,diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rsindex 8f2dda4bdb..20609a81fc 100644--- a/crates/agent_session/src/domain/error.rs+++ b/crates/agent_session/src/domain/error.rs@@ -1,6 +1,7 @@use crate::domain::model::AgentSessionId;use agent_runtime_protocol::domain::action::ActionError;use agent_runtime_protocol::domain::ports::TransportError;+use model_owner::OwnerType;use thiserror::Error;pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;@@ -23,6 +24,12 @@ pub enum AgentSessionError {ThreadSessionExists,#[error("the session owner is not a known user")]UnknownOwner,+ /// A path that runs as the session's owner - spending their credentials,+ /// attributing work to them, granting them access - met an owner that is+ /// not a user. Every session is user-owned today; this is the boundary+ /// that says so out loud instead of assuming it.+ #[error("this path needs a user-owned session, but the owner is a {0}")]+ OwnerNotUser(OwnerType),#[error("expected a GitHub PR URL: https://github.com/owner/repo/pull/number")]InvalidPullRequestUrl,#[error("invalid agent session name: {0}")]diff --git a/crates/agent_session/src/domain/lifecycle.rs b/crates/agent_session/src/domain/lifecycle.rsindex c672b4df7e..9a70e38376 100644--- a/crates/agent_session/src/domain/lifecycle.rs+++ b/crates/agent_session/src/domain/lifecycle.rs@@ -4,27 +4,30 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::domain::events::{SessionIdentity, ThreadOrigin};+use super::error::Result;use super::model::{AgentSession, SessionBot};/// The identity block every lifecycle event carries, from the session row,/// its bot, and the users its log has attributed frames to.////// The audience is `participants` plus the owner, who belongs on it whether-/// or not they have acted yet.+/// or not they have acted yet. The event names its owner as a user, so a+/// session owned by anything else has no identity here and is refused+/// rather than described as somebody it is not.////// A thread origin needs all three of its ids. A session created from a/// thread has them all; one created without a message has none. Anything in/// between is a row this code does not know how to describe, so it is/// reported as no origin rather than a half one.-#[must_use]pub fn session_identity(session: &AgentSession,bot: &SessionBot,participants: Vec<MacroUserIdStr<'static>>,-) -> SessionIdentity {+) -> Result<SessionIdentity> {+ let owner = session.owner_user()?;let mut audience = participants;- if !audience.contains(&session.owner_id) {- audience.push(session.owner_id.clone());+ if !audience.contains(owner) {+ audience.push(owner.clone());}let origin =match (@@ -47,13 +50,13 @@ pub fn session_identity(None}};- SessionIdentity {+ Ok(SessionIdentity {session_id: session.id,session_name: session.name.clone(),bot_id: session.bot_id,bot_name: bot.name.clone(),- owner_id: session.owner_id.clone(),+ owner_id: owner.clone(),origin,audience,- }+ })}diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 5bc0487e1b..d8b6915933 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -4,6 +4,9 @@ use bots::domain::models::BotId;use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;++use super::error::AgentSessionError;// The log vocabulary - the session id, the log entry, and the frame it// carries - is owned by `agent_fold`, the bottom of the agent session stack,@@ -162,8 +165,8 @@ pub use bots::domain::models::{AgentMcpServer, AgentMcpServers};pub struct CreateAgentSessionParams {/// Caller-minted session id, available before persistence.pub id: AgentSessionId,- /// User who created and owns the session.- pub owner_id: MacroUserIdStr<'static>,+ /// Who created and owns the session.+ pub owner_id: Owner,/// Bot running the agent.pub bot_id: BotId,/// Root message identifying the originating thread, if any.@@ -208,8 +211,8 @@ pub struct AgentSession {pub id: AgentSessionId,/// User-facing session name.pub name: String,- /// The user who created and owns the session. Immutable for its life.- pub owner_id: MacroUserIdStr<'static>,+ /// Who created and owns the session. Immutable for its life.+ pub owner_id: Owner,/// The root message where the bot was originally invoked, if any.pub thread_id: Option<Uuid>,/// Entity owning the originating thread, derived from its root message.@@ -253,6 +256,21 @@ pub struct AgentSession {pub modified_at: DateTime<Utc>,}+impl AgentSession {+ /// The user this session runs as.+ ///+ /// For every path that acts as the owner - spends their credentials,+ /// bills them, grants them access - rather than merely names them. The+ /// owner is a user for every session today, but the type no longer says+ /// so; asking here fails typed for any other kind instead of treating a+ /// bot or team as a person.+ pub fn owner_user(&self) -> Result<&MacroUserIdStr<'static>, AgentSessionError> {+ self.owner_id+ .as_user()+ .ok_or_else(|| AgentSessionError::OwnerNotUser(self.owner_id.owner_type()))+ }+}+/// A persisted agent-session name changed and should be shown to live viewers.#[derive(Debug, Clone, PartialEq, Eq)]pub struct AgentSessionRenamed {@@ -535,8 +553,8 @@ pub struct AgentSessionPreviewData {pub id: AgentSessionId,/// User-facing session name.pub name: String,- /// The user who owns the session.- pub owner_id: MacroUserIdStr<'static>,+ /// Who owns the session.+ pub owner_id: Owner,/// The bot running the agent, for its avatar.pub bot_id: BotId,/// Minimal bot identity, hydrated by the service after checking session access.diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 58be877e1f..45fe10a865 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -12,6 +12,7 @@ use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessause bots::domain::models::BotId;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;use std::num::NonZeroUsize;/// A bidirectional connection to an agent runtime.@@ -103,24 +104,27 @@ pub enum ManagedPersonaError {NotAgent,/// The bot is served by an external runtime.External,- /// The user does not own or belong to the persona's owner.+ /// The owner does not own or belong to the persona's owner, or is not+ /// a user at all.Forbidden,/// Looking up the persona or its owner failed.Lookup(AgentSessionError),}-/// Resolve and authorize a managed persona for a user.+/// Resolve and authorize a managed persona for the session's owner.////// Ownership policy lives in the domain: private personas belong to their/// owner, team personas are available to team members, selected-channel/// personas are available to anyone who can `@` them in a shared channel,/// and managed system bots (the deployment's own coders) are available to-/// everyone, exactly as they are when mentioned in a channel.-pub async fn managed_persona_for_user<Bots: BotDirectory>(+/// everyone, exactly as they are when mentioned in a channel. Every rule is+/// about a person, so an owner that is not a user selects nothing.+pub async fn managed_persona_for_owner<Bots: BotDirectory>(bots: &Bots,bot_id: BotId,- user: &MacroUserIdStr<'static>,+ owner: &Owner,) -> std::result::Result<SelectedManagedPersona, ManagedPersonaError> {+ let user = owner.as_user().ok_or(ManagedPersonaError::Forbidden)?;let facts = bots.bot_facts(bot_id).await@@ -200,8 +204,8 @@ pub struct OpenExternalAgentSession {pub workspace: String,/// Repository nominally checked out at `workspace`, when stated.pub repo_url: Option<String>,- /// The user who owns the session.- pub owner: MacroUserIdStr<'static>,+ /// Who owns the session.+ pub owner: Owner,/// The thread whose mention triggered the session, when one did.pub thread: Option<SessionThread>,/// Instructions the session's runtime works under, when any were stated.@@ -219,8 +223,8 @@ pub struct OpenManagedSession {pub repo_url: Option<String>,/// Starting branch for the selected repository.pub repo_branch: Option<super::repository_branch::RepositoryBranch>,- /// The user who owns the session and is credited for its messages.- pub owner: MacroUserIdStr<'static>,+ /// Who owns the session and is credited for its messages.+ pub owner: Owner,/// First prompt to deliver once the sandbox is attached. `None` opens an/// idle session its owner prompts from the session's own surface.pub prompt: Option<String>,diff --git a/crates/agent_session/src/domain/ports/test.rs b/crates/agent_session/src/domain/ports/test.rsindex fd636e0281..eb4734f0a4 100644--- a/crates/agent_session/src/domain/ports/test.rs+++ b/crates/agent_session/src/domain/ports/test.rs@@ -1,7 +1,8 @@-use super::{BotDirectory, BotFacts, ManagedPersonaError, managed_persona_for_user};+use super::{BotDirectory, BotFacts, ManagedPersonaError, managed_persona_for_owner};use bots::domain::models::BotId;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;const OWNER: &str = "macro|[email protected]";const TEAMMATE: &str = "macro|[email protected]";@@ -75,6 +76,10 @@ fn user(id: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(id.to_owned()).unwrap()}+fn owner(id: &str) -> Owner {+ Owner::User(user(id))+}+impl BotDirectory for Directory {async fn bot_facts(&self, bot: BotId) -> super::Result<Option<BotFacts>> {Ok((bot == BotId::TEST_A).then(|| self.facts.clone()))@@ -100,7 +105,7 @@ impl BotDirectory for Directory {#[tokio::test]async fn owner_can_select_a_private_persona() {let selected =- managed_persona_for_user(&Directory::managed_private(), BotId::TEST_A, &user(OWNER))+ managed_persona_for_owner(&Directory::managed_private(), BotId::TEST_A, &owner(OWNER)).await.expect("owner");assert_eq!(selected.bot_id, BotId::TEST_A);@@ -108,10 +113,10 @@ async fn owner_can_select_a_private_persona() {#[tokio::test]async fn stranger_cannot_select_a_private_all_channel_persona() {- let error = managed_persona_for_user(+ let error = managed_persona_for_owner(&Directory::managed_private(),BotId::TEST_A,- &user(STRANGER),+ &owner(STRANGER),).await.expect_err("private all-channel personas stay with their owner");@@ -120,10 +125,10 @@ async fn stranger_cannot_select_a_private_all_channel_persona() {#[tokio::test]async fn channel_co_member_can_select_a_selected_channel_persona() {- let selected = managed_persona_for_user(+ let selected = managed_persona_for_owner(&Directory::managed_selected_channel(),BotId::TEST_A,- &user(TEAMMATE),+ &owner(TEAMMATE),).await.expect("channel co-member");@@ -132,10 +137,10 @@ async fn channel_co_member_can_select_a_selected_channel_persona() {#[tokio::test]async fn stranger_cannot_select_a_selected_channel_persona_without_membership() {- let error = managed_persona_for_user(+ let error = managed_persona_for_owner(&Directory::managed_selected_channel(),BotId::TEST_A,- &user(STRANGER),+ &owner(STRANGER),).await.expect_err("no shared channel");@@ -145,7 +150,7 @@ async fn stranger_cannot_select_a_selected_channel_persona_without_membership()#[tokio::test]async fn team_member_can_select_a_team_persona() {let selected =- managed_persona_for_user(&Directory::managed_team(), BotId::TEST_A, &user(TEAMMATE))+ managed_persona_for_owner(&Directory::managed_team(), BotId::TEST_A, &owner(TEAMMATE)).await.expect("team member");assert_eq!(selected.bot_id, BotId::TEST_A);@@ -154,7 +159,7 @@ async fn team_member_can_select_a_team_persona() {#[tokio::test]async fn stranger_cannot_select_a_team_all_channel_persona() {let error =- managed_persona_for_user(&Directory::managed_team(), BotId::TEST_A, &user(STRANGER))+ managed_persona_for_owner(&Directory::managed_team(), BotId::TEST_A, &owner(STRANGER)).await.expect_err("all-channel team personas stay with the team");assert!(matches!(error, ManagedPersonaError::Forbidden));@@ -162,12 +167,26 @@ async fn stranger_cannot_select_a_team_all_channel_persona() {#[tokio::test]async fn channel_co_member_can_select_a_team_selected_channel_persona() {- let selected = managed_persona_for_user(+ let selected = managed_persona_for_owner(&Directory::managed_team_selected_channel(),BotId::TEST_A,- &user(TEAMMATE),+ &owner(TEAMMATE),).await.expect("channel co-member");assert_eq!(selected.bot_id, BotId::TEST_A);}++#[tokio::test]+async fn an_owner_that_is_not_a_user_selects_no_persona() {+ // Every persona rule is about a person - who owns it, whose team it+ // belongs to, who shares a channel with it - so a bot owner matches none+ // of them, even for a persona anyone could otherwise select.+ let result = managed_persona_for_owner(+ &Directory::managed_private(),+ BotId::TEST_A,+ &Owner::Bot(BotId::TEST_A),+ )+ .await;+ assert!(matches!(result, Err(ManagedPersonaError::Forbidden)));+}diff --git a/crates/agent_session/src/domain/pull_request.rs b/crates/agent_session/src/domain/pull_request.rsindex b0bf30972c..ed76f9ec41 100644--- a/crates/agent_session/src/domain/pull_request.rs+++ b/crates/agent_session/src/domain/pull_request.rs@@ -71,7 +71,7 @@ whereasync move {let result = async {let stored = self.repo.get(session).await?;- if &stored.owner_id != owner {+ if !stored.owner_id.is_user(owner) {return Err(AgentSessionError::Forbidden);}let url = canonical_url(url)?;diff --git a/crates/agent_session/src/domain/pull_request/test.rs b/crates/agent_session/src/domain/pull_request/test.rsindex e63437b9b2..e9a932e691 100644--- a/crates/agent_session/src/domain/pull_request/test.rs+++ b/crates/agent_session/src/domain/pull_request/test.rs@@ -46,11 +46,11 @@ async fn persists_and_publishes_once_and_rejects_another_owner() {));assert!(repo.list_by_session(session.id).await.unwrap().is_empty());service- .set_pull_request(session.id, &session.owner_id, url, None)+ .set_pull_request(session.id, session.owner_user().unwrap(), url, None).await.unwrap();service- .set_pull_request(session.id, &session.owner_id, url, None)+ .set_pull_request(session.id, session.owner_user().unwrap(), url, None).await.unwrap();assert!(repo.list_by_session(session.id).await.unwrap().is_empty());@@ -66,7 +66,7 @@ async fn persists_and_publishes_once_and_rejects_another_owner() {service.set_pull_request(session.id,- &session.owner_id,+ session.owner_user().unwrap(),"https://github.com/org/repo/pull/124",None,)@@ -92,7 +92,7 @@ async fn gateway_failure_does_not_undo_the_persisted_link() {let service = SessionPullRequestService::new(repo.clone(), RecordingRealtime::down());let url = "https://github.com/org/repo/pull/123";service- .set_pull_request(session.id, &session.owner_id, url, None)+ .set_pull_request(session.id, session.owner_user().unwrap(), url, None).await.unwrap();assert_eq!(@@ -124,12 +124,17 @@ async fn superseded_claim_cannot_publish_even_an_unchanged_url() {let service = SessionPullRequestService::new(repo.clone(), realtime.clone());let current_url = "https://github.com/org/repo/pull/2";service- .set_pull_request(session.id, &session.owner_id, current_url, Some(current))+ .set_pull_request(+ session.id,+ session.owner_user().unwrap(),+ current_url,+ Some(current),+ ).await.unwrap();for url in ["https://github.com/org/repo/pull/1", current_url] {assert!(- matches!(service.set_pull_request(session.id, &session.owner_id, url, Some(old)).await, Err(AgentSessionError::FencedOut(id)) if id == session.id)+ matches!(service.set_pull_request(session.id, session.owner_user().unwrap(), url, Some(old)).await, Err(AgentSessionError::FencedOut(id)) if id == session.id));}assert_eq!(diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex e7bbefa80b..ab9174da76 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -1039,7 +1039,7 @@ async fn publish_renamed_lifecycle<R>(let session = repo.get(id).await?;let (bot, participants) =tokio::try_join!(repo.session_bot(session.bot_id), repo.participants(id))?;- Ok::<_, AgentSessionError>(session_identity(&session, &bot, participants))+ session_identity(&session, &bot, participants)}.await;match identity {diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex 1d2536ad7e..db637ad489 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -61,7 +61,7 @@ async fn previews_hydrate_bot_identity_only_for_accessible_sessions() {let session = fx.repo.get(fx.session).await.unwrap();let previews = fx.service- .preview_sessions(&session.owner_id, vec![fx.session, fx.session])+ .preview_sessions(session.owner_user().unwrap(), vec![fx.session, fx.session]).await.unwrap();assert_eq!(previews.len(), 1);diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex bd00d472e1..1d8daf86b0 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -40,6 +40,7 @@ use macro_authorization::{};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;use serde::{Deserialize, Serialize};use utoipa::ToSchema;@@ -51,7 +52,7 @@ use crate::domain::model::{use crate::domain::ports::{AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlDisposition, ControlEvent,ManagedPersonaError, OpenExternalAgentSession, OpenManagedSession, SessionOpener,- SessionThread, managed_persona_for_user,+ SessionThread, managed_persona_for_owner,};use crate::domain::service::AgentSessionService;use bots::domain::models::BotId;@@ -1678,7 +1679,11 @@ fn resolve_bot(}}-/// Resolve the user who owns the session.+/// Resolve who owns the session.+///+/// Only ever a user here: every caller this route admits acts as a person,+/// and the body's `owner` claim is a user id. The type is wider than that so+/// the row and the runtimes are asked, not told, what kind of owner they got.////// A user caller always owns their own sessions. A harness caller always has a/// verified acting user - the owner for a private harness, a confirmed team@@ -1693,12 +1698,14 @@ fn resolve_bot(fn resolve_owner(caller: &UserBotOrHarnessAuthorization,claimed: Option<String>,-) -> Result<MacroUserIdStr<'static>, CreateSessionApiError> {+) -> Result<Owner, CreateSessionApiError> {if let Some(user) = caller.acting_user() {- return Ok(user.macro_user_id.clone());+ return Ok(Owner::User(user.macro_user_id.clone()));}let claimed = claimed.ok_or(CreateSessionApiError::OwnerRequired)?;- MacroUserIdStr::try_from(claimed).map_err(|_| CreateSessionApiError::UnparseableOwner)+ MacroUserIdStr::try_from(claimed)+ .map(Owner::User)+ .map_err(|_| CreateSessionApiError::UnparseableOwner)}#[utoipa::path(@@ -1747,16 +1754,19 @@ pub async fn create_agent_session_handler<}let owner = resolve_owner(&caller.authorization, None)?;let profile = if let Some(bot_id) = request.bot_id {- let selected =- managed_persona_for_user(state.bots.as_ref(), BotId::new_from_uuid(bot_id), &owner)- .await- .map_err(|error| match error {- ManagedPersonaError::Unknown => CreateSessionApiError::UnknownBot,- ManagedPersonaError::NotAgent => CreateSessionApiError::NotAnAgentBot,- ManagedPersonaError::External => CreateSessionApiError::ExternalPersona,- ManagedPersonaError::Forbidden => CreateSessionApiError::NotYourBot,- ManagedPersonaError::Lookup(error) => CreateSessionApiError::Domain(error),- })?;+ let selected = managed_persona_for_owner(+ state.bots.as_ref(),+ BotId::new_from_uuid(bot_id),+ &owner,+ )+ .await+ .map_err(|error| match error {+ ManagedPersonaError::Unknown => CreateSessionApiError::UnknownBot,+ ManagedPersonaError::NotAgent => CreateSessionApiError::NotAnAgentBot,+ ManagedPersonaError::External => CreateSessionApiError::ExternalPersona,+ ManagedPersonaError::Forbidden => CreateSessionApiError::NotYourBot,+ ManagedPersonaError::Lookup(error) => CreateSessionApiError::Domain(error),+ })?;Some(selected)} else {Nonediff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 6e141ff7e3..2dca4749b9 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -421,7 +421,7 @@ async fn the_owner_opens_a_session_for_their_bot() {assert_eq!(response.status(), StatusCode::CREATED);// The caller owns their own session; no claimed owner needed.let opened = opener.opened.lock().unwrap();- assert_eq!(opened[0].owner.as_ref(), OWNER);+ assert!(matches!(&opened[0].owner, Owner::User(user) if user.as_ref() == OWNER));}#[tokio::test]@@ -496,7 +496,7 @@ async fn a_harness_session_is_owned_by_its_verified_acting_user() {assert_eq!(response.status(), StatusCode::CREATED);let opened = opener.opened.lock().unwrap();assert_eq!(opened[0].bot_id, BotId::TEST_A);- assert_eq!(opened[0].owner.as_ref(), STRANGER);+ assert!(matches!(&opened[0].owner, Owner::User(user) if user.as_ref() == STRANGER));}#[tokio::test]@@ -516,7 +516,7 @@ async fn a_harness_may_not_own_a_session_by_an_unverified_body_claim() {assert_eq!(response.status(), StatusCode::CREATED);let opened = opener.opened.lock().unwrap();assert_eq!(opened[0].bot_id, BotId::TEST_A);- assert_eq!(opened[0].owner.as_ref(), OWNER);+ assert!(matches!(&opened[0].owner, Owner::User(user) if user.as_ref() == OWNER));}#[tokio::test]diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rsindex 0bd7c4e207..7bec2c4fe6 100644--- a/crates/agent_session/src/inbound/axum_router/test/read.rs+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs@@ -11,7 +11,7 @@ async fn view_router() -> Router {repo.create(CreateAgentSessionParams {repo_branch: None,id: AgentSessionId::TEST_A,- owner_id: MacroUserIdStr::try_from(OWNER.to_owned()).unwrap(),+ owner_id: Owner::User(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),bot_id: BotId::TEST_A,thread_id: None,originating_message_id: None,diff --git a/crates/agent_session/src/outbound/name_generator.rs b/crates/agent_session/src/outbound/name_generator.rsindex ec916a05ae..8952b3630e 100644--- a/crates/agent_session/src/outbound/name_generator.rs+++ b/crates/agent_session/src/outbound/name_generator.rs@@ -56,7 +56,12 @@ impl AgentSessionNameGenerator for HaikuAgentSessionNameGenerator {"<agent_session_first_prompt>\n{}\n</agent_session_first_prompt>\n\nGenerate the session title now.",initial_prompt.trim());- let usage_ctx = UsageContext::new(AiFeature::ChatRename, session.owner_id.clone())+ // Usage is billed to a person; a session owned by anything else has+ // nobody to bill, so it keeps its default name.+ let owner = session+ .owner_user()+ .map_err(|error| rootcause::report!(error))?;+ let usage_ctx = UsageContext::new(AiFeature::ChatRename, owner.clone()).with_entity(Some(session.id.as_uuid()));let response = agent::complete(PredefinedModel::Fast,diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex 0ba660294b..b5a8c79f74 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -198,7 +198,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {Ok(Self {id: AgentSessionId::new_from_uuid(row.id),name: row.name,- owner_id: MacroUserIdStr::try_from(row.owner_id)+ owner_id: Owner::from_principal_str(&row.owner_id).context("agent session has an unparseable owner")?,thread_id: row.thread_id,thread_parent: row.thread_parent.map(|parent| parent.0),@@ -259,6 +259,13 @@ impl AgentSessionRepo for PgAgentSessionRepo {} = params;let mcp_servers_json = serde_json::to_value(mcp_servers.servers()).context("serialize agent session mcp servers")?;+ // The row's `owner_id` references `"User"`, the owner's grant is a+ // user access row, and the session lands in the owner's history:+ // this store holds user-owned sessions, and says so before writing+ // anything rather than letting the foreign key say it for a bot.+ let owner_user = owner_id+ .as_user()+ .ok_or_else(|| AgentSessionError::OwnerNotUser(owner_id.owner_type()))?;// The session row and its access grants land together: a crash between// the two would leave a session nobody - not even its owner -@@ -294,7 +301,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {NULL::TEXT AS "external_last_run_id?""#,id.as_uuid(),- owner_id.as_ref(),+ owner_user.as_ref(),thread_id,originating_message_id,bot_id.as_uuid(),@@ -328,7 +335,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {&mut transaction,&id.as_uuid(),EntityType::AgentSession,- owner_id.as_ref(),+ owner_user.as_ref(),EntityAccessSourceType::User,AccessLevel::Owner,)@@ -340,7 +347,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {NewEntityRecord::new(id.as_uuid(),RegisteredEntityType::AgentSession,- Owner::User(owner_id.clone()),+ owner_id.clone(),),).await@@ -379,7 +386,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {// row is what Soup's `viewed_at` and the frecency ranking read, so// without it a brand-new session would rank below everything the// owner has ever opened.- upsert_user_history(&mut transaction, owner_id.as_ref(), &id.as_uuid())+ upsert_user_history(&mut transaction, owner_user.as_ref(), &id.as_uuid()).await.context("failed to record the agent session in the owner's history")?;@@ -478,7 +485,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {bot: None,id,name: row.name,- owner_id: MacroUserIdStr::try_from(row.owner_id)+ owner_id: Owner::from_principal_str(&row.owner_id).context("agent session has an unparseable owner")?,bot_id: BotId::new_from_uuid(row.bot_id),status: parse_status(&row.status, row.status_event_name)?,diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex f7b9f2eb2c..8d715a4658 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -86,7 +86,7 @@ fn new_session(CreateAgentSessionParams {repo_branch: None,id: AgentSessionId::new(),- owner_id: user_id(OWNER),+ owner_id: Owner::User(user_id(OWNER)),bot_id,thread_id,originating_message_id,@@ -214,6 +214,30 @@ fn acp_notification() -> AcpMessage {)}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {+ let repo = PgAgentSessionRepo::new(pool.clone());+ let bot_id = create_test_bot(&pool).await;+ let params = CreateAgentSessionParams {+ owner_id: Owner::Bot(bot_id),+ ..new_session(bot_id, None, None)+ };+ let id = params.id;++ // Refused by type before the row's user foreign key, user access row, or+ // user history could say it less clearly - and before any of them is+ // written.+ let error = AgentSessionRepo::create(&repo, params)+ .await+ .expect_err("a bot cannot own a session row");++ assert!(matches!(+ error,+ AgentSessionError::OwnerNotUser(model_owner::OwnerType::Bot)+ ));+ assert_eq!(entity_row_count(&pool, id).await, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_and_get_round_trips(pool: PgPool) {let repo = PgAgentSessionRepo::new(pool.clone());@@ -845,7 +869,7 @@ async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {let someone_else = create_session(&repo,CreateAgentSessionParams {- owner_id: user_id(OTHER_OWNER),+ owner_id: Owner::User(user_id(OTHER_OWNER)),..new_session(bot_id, None, None)},)@@ -1099,7 +1123,7 @@ async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {id: from_channel.id,bot: None,name: DEFAULT_AGENT_SESSION_NAME.to_string(),- owner_id: user_id(OWNER),+ owner_id: Owner::User(user_id(OWNER)),bot_id,status: SessionStatus::NoMessages,created_at: from_channel.created_at,@@ -1113,7 +1137,7 @@ async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {id: private.id,bot: None,name: DEFAULT_AGENT_SESSION_NAME.to_string(),- owner_id: user_id(OWNER),+ owner_id: Owner::User(user_id(OWNER)),bot_id,status: SessionStatus::Event(SystemEvent::AcpReady),created_at: private.created_at,@@ -1971,8 +1995,8 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {let session = create_session(&repo, new_session(bot, None, None)).await;let url = "https://github.com/org/repo/pull/123";let (first, second) = tokio::join!(- repo.record_pull_request(session.id, &session.owner_id, url, None),- repo.record_pull_request(session.id, &session.owner_id, url, None),+ repo.record_pull_request(session.id, session.owner_user().unwrap(), url, None),+ repo.record_pull_request(session.id, session.owner_user().unwrap(), url, None),);assert_eq!(usize::from(first.unwrap()) + usize::from(second.unwrap()),@@ -2014,7 +2038,7 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {);assert!(!repo- .record_pull_request(session.id, &session.owner_id, url, None)+ .record_pull_request(session.id, session.owner_user().unwrap(), url, None).await.unwrap());@@ -2067,13 +2091,23 @@ async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPoo};let original_url = "https://github.com/org/repo/pull/1";assert!(- repo.record_pull_request(session.id, &session.owner_id, original_url, Some(old))- .await- .unwrap()+ repo.record_pull_request(+ session.id,+ session.owner_user().unwrap(),+ original_url,+ Some(old)+ )+ .await+ .unwrap());assert!(!repo- .record_pull_request(session.id, &session.owner_id, original_url, Some(old))+ .record_pull_request(+ session.id,+ session.owner_user().unwrap(),+ original_url,+ Some(old)+ ).await.unwrap());@@ -2082,7 +2116,7 @@ async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPoosqlx::query!("UPDATE agent_session SET manager_fence = manager_fence + 1, pull_request_url = $2 WHERE id = $1", session.id.as_uuid(), "https://github.com/org/repo/pull/2").execute(&mut *takeover).await.unwrap();let stale_repo = repo.clone();- let owner = session.owner_id.clone();+ let owner = session.owner_user().unwrap().clone();let mut stale = tokio::spawn(async move {stale_repo.record_pull_request(@@ -2114,7 +2148,7 @@ async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPooassert!(matches!(repo.record_pull_request(session.id,- &session.owner_id,+ session.owner_user().unwrap(),"https://github.com/org/repo/pull/2",Some(old))diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex fa497a43e6..c500713e32 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -187,7 +187,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {created_at: session.created_at,modified_at: session.modified_at,},- has_grant: session.owner_id == *viewer,+ has_grant: session.owner_id.is_user(viewer),thread_parent: session.thread_parent.clone(),}).collect())@@ -268,7 +268,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {.lock().expect("in-memory session store is not poisoned").values()- .filter(|session| session.owner_id.as_ref() == owner.as_ref())+ .filter(|session| session.owner_id.is_user(owner)).cloned().collect();found.sort_by(|a, b| {@@ -739,8 +739,10 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {pull_request_url: None,id,name: DEFAULT_AGENT_SESSION_NAME.to_owned(),- owner_id: macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")- .expect("valid macro user id"),+ owner_id: model_owner::Owner::User(+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")+ .expect("valid macro user id"),+ ),thread_id: None,thread_parent: None,originating_message_id: None,@@ -916,7 +918,7 @@ impl crate::domain::pull_request::SessionPullRequestRepo for InMemoryAgentSessiolet mut sessions = self.sessions.lock().unwrap();let stored = sessions.get_mut(&session)- .filter(|stored| &stored.owner_id == owner)+ .filter(|stored| stored.owner_id.is_user(owner)).ok_or(AgentSessionError::Forbidden)?;if stored.pull_request_url.as_deref() == Some(url) {return Ok(false);diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.tomlindex 140cf62e8f..6d61788616 100644--- a/crates/agent_trigger/Cargo.toml+++ b/crates/agent_trigger/Cargo.toml@@ -48,4 +48,5 @@ messages = { path = "../messages", features = ["test-utils"] }agent_session = { path = "../agent_session", features = ["test-utils"] }bot_id = { path = "../bot_id", features = ["test-utils"] }mockall = { workspace = true }+model_owner = { path = "../model_owner" }tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 8627e112d4..2ecde2ea9a 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -105,7 +105,9 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {pull_request_url: None,id,name: agent_session::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),- owner_id: MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),+ owner_id: model_owner::Owner::User(+ MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),+ ),thread_id: Some(Uuid::from_u128(3)),thread_parent: Some(MessageParent::Channel(Uuid::from_u128(1))),originating_message_id: None,diff --git a/crates/model_owner/src/lib.rs b/crates/model_owner/src/lib.rsindex d9a4724abd..7a5e1a55a3 100644--- a/crates/model_owner/src/lib.rs+++ b/crates/model_owner/src/lib.rs@@ -129,6 +129,19 @@ impl Owner {pub fn is_user(&self, user: &MacroUserIdStr<'_>) -> bool {matches!(self, Self::User(owner) if owner == user)}++ /// The user this owner is, or `None` for a bot or team.+ ///+ /// For paths that act as a person - spending their credentials or+ /// attributing work to them - so the kinds an owner can be are handled+ /// where a user is needed rather than assumed.+ #[must_use]+ pub fn as_user(&self) -> Option<&MacroUserIdStr<'static>> {+ match self {+ Self::User(user) => Some(user),+ Self::Bot(_) | Self::Team(_) => None,+ }+ }}impl Display for Owner {diff --git a/crates/model_owner/src/test.rs b/crates/model_owner/src/test.rsindex e10f0f451b..1efc827006 100644--- a/crates/model_owner/src/test.rs+++ b/crates/model_owner/src/test.rs@@ -119,6 +119,25 @@ fn is_user_matches_only_that_user() {);}+#[test]+fn as_user_is_only_the_user_kind() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ assert_eq!(Owner::User(user.clone()).as_user(), Some(&user));+ assert_eq!(+ Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1")+ .unwrap()+ .as_user(),+ None+ );+ assert_eq!(+ Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef")+ .unwrap()+ .as_user(),+ None+ );+}+#[test]fn display_equals_principal_id() {for principal in [diff --git a/services/agent_harness_service/src/internal_mcp.rs b/services/agent_harness_service/src/internal_mcp.rsindex c0d7717cfc..d83c074ca8 100644--- a/services/agent_harness_service/src/internal_mcp.rs+++ b/services/agent_harness_service/src/internal_mcp.rs@@ -129,13 +129,18 @@ impl ServerHandler for InternalTools {.ok_or_else(|| {rmcp::ErrorData::invalid_request("Missing session authorization", None)})?;+ // Session tools run as the owner; a session owned by anything else+ // has nobody to run them as.+ let owner = grant+ .owner_user()+ .map_err(|error| rmcp::ErrorData::invalid_request(error.to_string(), None))?;let result = toolset().try_tool_call(SessionToolContext {service: self.service.clone(),session: grant.id,},- RequestContext::new(grant.owner_id.clone()),+ RequestContext::new(owner.clone()),&request.name,&serde_json::Value::Object(request.arguments.unwrap_or_default()),)