Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): start macrod-bound agents from the composer (#6844)

Wolf Mermelstein1032c6215074
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
index 7f70265f98..83fba99650 100644
--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -79,6 +79,7 @@ function SessionContent(props: {
retryLoad,
session,
sessionId,
+ startupError,
} = useAgentSession();
const panel = useSplitPanelOrThrow();
const [shareOpen, setShareOpen] = createSignal(false);
@@ -235,19 +236,32 @@ function SessionContent(props: {
when={!loadFailed()}
fallback={
<Show
- when={accessDenied()}
+ when={startupError()}
fallback={
- <LoadErrorPanel
- title="Unable to load this session"
- onRetry={loadRetryable() ? retryLoad : undefined}
- />
+ <Show
+ when={accessDenied()}
+ fallback={
+ <LoadErrorPanel
+ title="Unable to load this session"
+ onRetry={loadRetryable() ? retryLoad : undefined}
+ />
+ }
+ >
+ <EmptyStatePanel
+ centered
+ title="You don't have access to this session"
+ description="Ask a participant to share it with you."
+ />
+ </Show>
}
>
- <EmptyStatePanel
- centered
- title="You don't have access to this session"
- description="Ask a participant to share it with you."
- />
+ {(error) => (
+ <EmptyStatePanel
+ centered
+ title="The agent could not be started"
+ description={error()}
+ />
+ )}
</Show>
}
>
diff --git a/apps/web/src/features/agents-view/core/roster.test.ts b/apps/web/src/features/agents-view/core/roster.test.ts
index 056364dc2d..74b7c92b86 100644
--- a/apps/web/src/features/agents-view/core/roster.test.ts
+++ b/apps/web/src/features/agents-view/core/roster.test.ts
@@ -103,15 +103,17 @@ describe('buildAgentRoster', () => {
expect(saved[3]?.runtime.label).toBe('Disconnected runtime');
});
- it('cannot start a saved agent on a connected macrod runtime from here', () => {
+ it('can start a saved agent on a connected macrod runtime from here', () => {
const roster = buildAgentRoster({
...EMPTY,
runtimes: [{ id: 'h1', name: 'wolf-laptop', connected: true }],
agents: [persisted({ harness: 'macrod', harness_id: 'h1' })],
});
- expect(roster.at(-1)?.unavailableReason).toBe(
- 'Runs on its own machine · start it from a channel mention'
- );
+ expect(roster.at(-1)?.runtime).toEqual({
+ label: 'wolf-laptop',
+ connected: true,
+ });
+ expect(roster.at(-1)?.unavailableReason).toBeUndefined();
});
});
diff --git a/apps/web/src/features/agents-view/core/roster.ts b/apps/web/src/features/agents-view/core/roster.ts
index 4e99b944a7..cc1f3b3df0 100644
--- a/apps/web/src/features/agents-view/core/roster.ts
+++ b/apps/web/src/features/agents-view/core/roster.ts
@@ -158,10 +158,8 @@ function persistedAgent(
? 'Connect Cursor'
: undefined,
unavailableReason:
- agent.harness === 'macrod'
- ? connected
- ? 'Runs on its own machine · start it from a channel mention'
- : 'Its runtime is disconnected'
+ agent.harness === 'macrod' && !connected
+ ? 'Its runtime is disconnected'
: agent.harness === 'cursor' && !connected
? 'Connect Cursor to start it'
: undefined,
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
index 66580b50cc..5cd2cfa452 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -41,8 +41,9 @@ must supply a bot they own. */
open on the session's final id - URL, history row, references - the
moment the user acts, rather than after this request answers (which
for a managed sandbox can take a while). Omitted, the service mints
-one. Managed sessions only. Answers 409 if a session already holds
-the id. */
+one. Answers 409 if a session already holds the id. On an external
+request it is how a runtime answering a composer request names the
+id it was handed, so the requester waiting on that id finds the session. */
id?: CreateAgentSessionRequestId;
/** Instructions the session's runtime works under, for its whole life.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts
index 43b91abf91..11fce34bed 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts
@@ -10,7 +10,8 @@
open on the session's final id - URL, history row, references - the
moment the user acts, rather than after this request answers (which
for a managed sandbox can take a while). Omitted, the service mints
-one. Managed sessions only. Answers 409 if a session already holds
-the id.
+one. Answers 409 if a session already holds the id. On an external
+request it is how a runtime answering a composer request names the
+id it was handed, so the requester waiting on that id finds the session.
*/
export type CreateAgentSessionRequestId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index cca82e9347..55c3fb743e 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -2299,7 +2299,7 @@
"id": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Managed sessions only. Answers 409 if a session already holds\nthe id."
+ "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Answers 409 if a session already holds the id. On an external\nrequest it is how a runtime answering a composer request names the\nid it was handed, so the requester waiting on that id finds the session."
},
"instructions": {
"type": ["string", "null"],
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index bc52731830..e957e18ed5 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -98,7 +98,7 @@ where
.sessions
.create_session(CreateAgentSessionParams {
repo_branch: None,
- id: AgentSessionId::new(),
+ id: request.id.unwrap_or_else(AgentSessionId::new),
owner_id: request.owner,
bot_id: request.bot_id,
thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index dc2259f5cf..295027bc1d 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2354,6 +2354,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
fn open_external_request(workspace: &str) -> OpenExternalAgentSession {
OpenExternalAgentSession {
+ id: None,
profile: None,
instructions: None,
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 54c02036bf..13caf62329 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -29,6 +29,10 @@ pub enum AgentSessionError {
Handshake(String),
#[error("agent session {0} is no longer connected")]
Disconnected(AgentSessionId),
+ /// A session cannot be opened because the bot's externally run runtime
+ /// is not in a state to serve it. Says what the operator has to fix.
+ #[error("{0}")]
+ RuntimeUnavailable(&'static str),
#[error("this bot already has a session for this thread")]
ThreadSessionExists,
/// A create named an id a session already holds. Ids are minted by the
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index dea3748416..5da74d7e44 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -95,6 +95,49 @@ pub trait BotDirectory: Send + Sync + 'static {
) -> impl Future<Output = Result<bool>> + Send;
}
+/// A persona selected for a session started from Macro, by whoever runs it.
+#[derive(Debug, Clone)]
+pub enum SelectedPersona {
+ /// This deployment provisions the runtime.
+ Managed(SelectedManagedPersona),
+ /// The persona's operator runs the runtime, which opens its own sessions.
+ External {
+ /// Bot identity used by the session.
+ bot_id: BotId,
+ },
+}
+
+/// A session asked for from the composer, for a bot whose runtime is its
+/// operator's. The runtime creates it, the way it does for a mention.
+///
+/// No prompt: the caller delivers its own through the control endpoint once
+/// the session exists, exactly as it does for a managed one, so a prompt the
+/// user typed never rides the trigger topic.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RequestedExternalSession {
+ /// The id the runtime is told to create the session under.
+ pub session_id: AgentSessionId,
+ /// The bot the session runs for.
+ pub bot_id: BotId,
+ /// Who asked; owns the session that the runtime creates.
+ pub owner: MacroUserIdStr<'static>,
+ /// The model they chose over the persona's default, when they did. It
+ /// reaches the runtime the way the persona's own does: recorded on the
+ /// session, then selected when the session binds on its first prompt.
+ pub model: Option<String>,
+}
+
+/// Hands a composer request to the bot's own runtime and waits for the
+/// session it creates.
+pub trait ExternalSessionRequester: Send + Sync + 'static {
+ /// Ask the runtime and return the session once it exists. Fails with
+ /// [`AgentSessionError::RuntimeUnavailable`] when no runtime answers.
+ fn request(
+ &self,
+ request: RequestedExternalSession,
+ ) -> impl Future<Output = Result<AgentSession>> + Send;
+}
+
/// Why a user cannot select a bot as a managed session persona.
#[derive(Debug)]
pub enum ManagedPersonaError {
@@ -102,8 +145,10 @@ pub enum ManagedPersonaError {
Unknown,
/// The bot has no agent runtime.
NotAgent,
- /// The bot is served by an external runtime.
- External,
+ /// A first-party system bot this deployment does not run. It has no
+ /// operator to ask and no owner to authorize against, so it is nobody's
+ /// to start - a misconfiguration rather than a policy answer.
+ UnmanagedSystemBot,
/// The owner does not own or belong to the persona's owner, or is not
/// a user at all.
Forbidden,
@@ -111,7 +156,8 @@ pub enum ManagedPersonaError {
Lookup(AgentSessionError),
}
-/// Resolve and authorize a managed persona for the session's owner.
+/// Resolve and authorize a persona for the session's owner, whoever runs its
+/// runtime.
///
/// Ownership policy lives in the domain: private personas belong to their
/// owner, team personas are available to team members, selected-channel
@@ -119,11 +165,15 @@ pub enum ManagedPersonaError {
/// and managed system bots (the deployment's own coders) are available to
/// 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>(
+///
+/// A persona whose runtime its operator runs is authorized by those same
+/// rules and only then told apart, so the caller can hand the request to
+/// that runtime instead of opening the session here.
+pub async fn persona_for_owner<Bots: BotDirectory>(
bots: &Bots,
bot_id: BotId,
owner: &Owner,
-) -> std::result::Result<SelectedManagedPersona, ManagedPersonaError> {
+) -> std::result::Result<SelectedPersona, ManagedPersonaError> {
let user = owner.as_user().ok_or(ManagedPersonaError::Forbidden)?;
let facts = bots
.bot_facts(bot_id)
@@ -133,14 +183,14 @@ pub async fn managed_persona_for_owner<Bots: BotDirectory>(
if !facts.has_agent {
return Err(ManagedPersonaError::NotAgent);
}
- if !facts.is_managed {
- return Err(ManagedPersonaError::External);
- }
if facts.is_system {
- return Ok(SelectedManagedPersona {
+ if !facts.is_managed {
+ return Err(ManagedPersonaError::UnmanagedSystemBot);
+ }
+ return Ok(SelectedPersona::Managed(SelectedManagedPersona {
bot_id,
profile: None,
- });
+ }));
}
let authorized = if let Some(owner) = &facts.owner_user_id {
owner.as_ref() == user.as_ref()
@@ -164,11 +214,14 @@ pub async fn managed_persona_for_owner<Bots: BotDirectory>(
if !authorized {
return Err(ManagedPersonaError::Forbidden);
}
+ if !facts.is_managed {
+ return Ok(SelectedPersona::External { bot_id });
+ }
let profile = facts.managed_profile.ok_or(ManagedPersonaError::NotAgent)?;
- Ok(SelectedManagedPersona {
+ Ok(SelectedPersona::Managed(SelectedManagedPersona {
bot_id,
profile: Some(profile),
- })
+ }))
}
/// The mention that triggered a session, when one did.
@@ -196,6 +249,10 @@ pub struct SessionThread {
/// Everything needed to open a session served by an external runtime.
#[derive(Debug, Clone)]
pub struct OpenExternalAgentSession {
+ /// The id to create the session under, when the caller was told one: a
+ /// runtime answering a composer request creates the session the
+ /// requester is already waiting on. Minted here otherwise.
+ pub id: Option<AgentSessionId>,
/// The bot the session runs for.
pub bot_id: BotId,
/// Persisted agent settings resolved by the authenticated entry point.
diff --git a/crates/agent_session/src/domain/ports/test.rs b/crates/agent_session/src/domain/ports/test.rs
index eb4734f0a4..30faeaf6f0 100644
--- a/crates/agent_session/src/domain/ports/test.rs
+++ b/crates/agent_session/src/domain/ports/test.rs
@@ -1,4 +1,4 @@
-use super::{BotDirectory, BotFacts, ManagedPersonaError, managed_persona_for_owner};
+use super::{BotDirectory, BotFacts, ManagedPersonaError, SelectedPersona, persona_for_owner};
use bots::domain::models::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -104,16 +104,15 @@ impl BotDirectory for Directory {
#[tokio::test]
async fn owner_can_select_a_private_persona() {
- let selected =
- managed_persona_for_owner(&Directory::managed_private(), BotId::TEST_A, &owner(OWNER))
- .await
- .expect("owner");
- assert_eq!(selected.bot_id, BotId::TEST_A);
+ let selected = persona_for_owner(&Directory::managed_private(), BotId::TEST_A, &owner(OWNER))
+ .await
+ .expect("owner");
+ assert_eq!(managed(selected).bot_id, BotId::TEST_A);
}
#[tokio::test]
async fn stranger_cannot_select_a_private_all_channel_persona() {
- let error = managed_persona_for_owner(
+ let error = persona_for_owner(
&Directory::managed_private(),
BotId::TEST_A,
&owner(STRANGER),
@@ -125,19 +124,19 @@ 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_owner(
+ let selected = persona_for_owner(
&Directory::managed_selected_channel(),
BotId::TEST_A,
&owner(TEAMMATE),
)
.await
.expect("channel co-member");
- assert_eq!(selected.bot_id, BotId::TEST_A);
+ assert_eq!(managed(selected).bot_id, BotId::TEST_A);
}
#[tokio::test]
async fn stranger_cannot_select_a_selected_channel_persona_without_membership() {
- let error = managed_persona_for_owner(
+ let error = persona_for_owner(
&Directory::managed_selected_channel(),
BotId::TEST_A,
&owner(STRANGER),
@@ -149,32 +148,30 @@ 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_owner(&Directory::managed_team(), BotId::TEST_A, &owner(TEAMMATE))
- .await
- .expect("team member");
- assert_eq!(selected.bot_id, BotId::TEST_A);
+ let selected = persona_for_owner(&Directory::managed_team(), BotId::TEST_A, &owner(TEAMMATE))
+ .await
+ .expect("team member");
+ assert_eq!(managed(selected).bot_id, BotId::TEST_A);
}
#[tokio::test]
async fn stranger_cannot_select_a_team_all_channel_persona() {
- let error =
- managed_persona_for_owner(&Directory::managed_team(), BotId::TEST_A, &owner(STRANGER))
- .await
- .expect_err("all-channel team personas stay with the team");
+ let error = 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));
}
#[tokio::test]
async fn channel_co_member_can_select_a_team_selected_channel_persona() {
- let selected = managed_persona_for_owner(
+ let selected = persona_for_owner(
&Directory::managed_team_selected_channel(),
BotId::TEST_A,
&owner(TEAMMATE),
)
.await
.expect("channel co-member");
- assert_eq!(selected.bot_id, BotId::TEST_A);
+ assert_eq!(managed(selected).bot_id, BotId::TEST_A);
}
#[tokio::test]
@@ -182,7 +179,7 @@ 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(
+ let result = persona_for_owner(
&Directory::managed_private(),
BotId::TEST_A,
&Owner::Bot(BotId::TEST_A),
@@ -190,3 +187,94 @@ async fn an_owner_that_is_not_a_user_selects_no_persona() {
.await;
assert!(matches!(result, Err(ManagedPersonaError::Forbidden)));
}
+
+/// The managed persona a selection resolved to, failing the test otherwise.
+fn managed(selected: SelectedPersona) -> super::SelectedManagedPersona {
+ match selected {
+ SelectedPersona::Managed(persona) => persona,
+ SelectedPersona::External { .. } => panic!("expected a managed persona"),
+ }
+}
+
+/// An agent bound to its owner's own macrod, as the composer now starts it.
+fn external_facts(selected_channels: bool) -> BotFacts {
+ BotFacts {
+ is_managed: false,
+ ..managed_facts(selected_channels)
+ }
+}
+
+impl Directory {
+ fn external_private() -> Self {
+ Self {
+ facts: external_facts(false),
+ team_members: Vec::new(),
+ channel_members: Vec::new(),
+ }
+ }
+
+ fn external_team() -> Self {
+ let mut facts = external_facts(false);
+ facts.owner_user_id = None;
+ facts.owner_team_id = Some(Uuid::nil());
+ Self {
+ facts,
+ team_members: vec![OWNER, TEAMMATE],
+ channel_members: Vec::new(),
+ }
+ }
+}
+
+/// An externally run persona is authorized by the same ownership rules as a
+/// managed one, and only then told apart, so the caller can hand it to the
+/// runtime its operator runs.
+#[tokio::test]
+async fn owner_selects_their_external_persona_as_external() {
+ let selected = persona_for_owner(&Directory::external_private(), BotId::TEST_A, &owner(OWNER))
+ .await
+ .expect("owner");
+ assert!(matches!(
+ selected,
+ SelectedPersona::External {
+ bot_id: BotId::TEST_A
+ }
+ ));
+}
+
+#[tokio::test]
+async fn team_member_selects_a_team_external_persona() {
+ let selected = persona_for_owner(&Directory::external_team(), BotId::TEST_A, &owner(TEAMMATE))
+ .await
+ .expect("team member");
+ assert!(matches!(selected, SelectedPersona::External { .. }));
+}
+
+#[tokio::test]
+async fn stranger_cannot_select_someone_elses_external_persona() {
+ let error = persona_for_owner(
+ &Directory::external_private(),
+ BotId::TEST_A,
+ &owner(STRANGER),
+ )
+ .await
+ .expect_err("external personas stay with their owner");
+ assert!(matches!(error, ManagedPersonaError::Forbidden));
+}
+
+/// A first-party bot this deployment does not run has no operator to ask and
+/// no owner to authorize against: the state should not exist, and is refused
+/// rather than published to a topic nothing serves.
+#[tokio::test]
+async fn an_unmanaged_system_bot_selects_nothing() {
+ let mut facts = external_facts(false);
+ facts.is_system = true;
+ let directory = Directory {
+ facts,
+ team_members: Vec::new(),
+ channel_members: Vec::new(),
+ };
+ let error = persona_for_owner(&directory, BotId::TEST_A, &owner(OWNER))
+ .await
+ .expect_err("a system bot this deployment does not run is misconfigured");
+ assert!(matches!(error, ManagedPersonaError::UnmanagedSystemBot));
+}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index bdf852a10d..a241692364 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -51,8 +51,8 @@ use crate::domain::model::{
};
use crate::domain::ports::{
AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlDisposition, ControlEvent,
- ManagedPersonaError, OpenExternalAgentSession, OpenManagedSession, SessionOpener,
- SessionThread, managed_persona_for_owner,
+ ExternalSessionRequester, ManagedPersonaError, OpenExternalAgentSession, OpenManagedSession,
+ RequestedExternalSession, SelectedPersona, SessionOpener, SessionThread, persona_for_owner,
};
use crate::domain::service::AgentSessionService;
use bots::domain::models::BotId;
@@ -302,6 +302,12 @@ impl IntoResponse for AgentSessionApiError {
)
.into_response()
}
+ // Nothing to open onto: the operator has to bring the runtime up
+ // (or update it) before this bot's sessions can start from here.
+ Self::Domain(AgentSessionError::RuntimeUnavailable(reason)) => {
+ tracing::info!(reason, "open refused: the bot's runtime is unavailable");
+ (StatusCode::CONFLICT, reason).into_response()
+ }
// Same class as a disconnected runtime: nothing is wrong, and
// repeating the request will not land. The form the caller is
// answering has already resolved (someone else answered, a stop
@@ -1385,62 +1391,66 @@ pub async fn get_agent_session_log_handler<
/// Nothing about the gateway: a runtime dials once per bot, at an address its
/// own configuration names, so creating a session says nothing about where to
/// connect.
-pub struct CreateSessionState<Opener, Bots, Auth> {
+pub struct CreateSessionState<Opener, Bots, Requests, Auth> {
opener: Arc<Opener>,
bots: Arc<Bots>,
+ requests: Arc<Requests>,
authorization_state: MacroAuthorizationState<Auth>,
}
-impl<Opener, Bots, Auth> CreateSessionState<Opener, Bots, Auth> {
+impl<Opener, Bots, Requests, Auth> CreateSessionState<Opener, Bots, Requests, Auth> {
/// Create route state.
pub fn new(
opener: Arc<Opener>,
bots: Arc<Bots>,
+ requests: Arc<Requests>,
authorization_state: MacroAuthorizationState<Auth>,
) -> Self {
Self {
opener,
bots,
+ requests,
authorization_state,
}
}
}
-// Manual Clone impl so Opener and Bots don't need to be Clone (both are
-// behind Arcs).
-impl<Opener, Bots, Auth> Clone for CreateSessionState<Opener, Bots, Auth> {
+// Manual Clone impl so the ports don't need to be Clone (all behind Arcs).
+impl<Opener, Bots, Requests, Auth> Clone for CreateSessionState<Opener, Bots, Requests, Auth> {
fn clone(&self) -> Self {
Self {
opener: Arc::clone(&self.opener),
bots: Arc::clone(&self.bots),
+ requests: Arc::clone(&self.requests),
authorization_state: self.authorization_state.clone(),
}
}
}
-impl<Opener, Bots, Auth> FromRef<CreateSessionState<Opener, Bots, Auth>>
+impl<Opener, Bots, Requests, Auth> FromRef<CreateSessionState<Opener, Bots, Requests, Auth>>
for MacroAuthorizationState<Auth>
{
- fn from_ref(state: &CreateSessionState<Opener, Bots, Auth>) -> Self {
+ fn from_ref(state: &CreateSessionState<Opener, Bots, Requests, Auth>) -> Self {
state.authorization_state.clone()
}
}
/// Build the router serving `POST /agent-sessions`. Mount it under the same
/// prefix as [`agent_session_read_router`] and [`agent_session_control_router`].
-pub fn agent_session_create_router<Opener, Bots, Auth, S>(
- state: CreateSessionState<Opener, Bots, Auth>,
+pub fn agent_session_create_router<Opener, Bots, Requests, Auth, S>(
+ state: CreateSessionState<Opener, Bots, Requests, Auth>,
) -> Router<S>
where
Opener: SessionOpener,
Bots: BotDirectory,
+ Requests: ExternalSessionRequester,
Auth: MacroAuthorizationService,
S: Clone + Send + Sync + 'static,
{
Router::new()
.route(
"/",
- post(create_agent_session_handler::<Opener, Bots, Auth>),
+ post(create_agent_session_handler::<Opener, Bots, Requests, Auth>),
)
.with_state(state)
}
@@ -1464,8 +1474,9 @@ pub struct CreateAgentSessionRequest {
/// open on the session's final id - URL, history row, references - the
/// moment the user acts, rather than after this request answers (which
/// for a managed sandbox can take a while). Omitted, the service mints
- /// one. Managed sessions only. Answers 409 if a session already holds
- /// the id.
+ /// one. Answers 409 if a session already holds the id. On an external
+ /// request it is how a runtime answering a composer request names the
+ /// id it was handed, so the requester waiting on that id finds the session.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<Uuid>,
/// Bot the session runs for. On a managed request this optionally selects
@@ -1585,8 +1596,9 @@ pub enum CreateSessionApiError {
NotAnAgentBot,
/// The bot's sessions are opened by the trigger pipeline, not this route.
ManagedBot,
- /// The selected persona is served by an external runtime.
- ExternalPersona,
+ /// A first-party system bot this deployment does not run: nothing can
+ /// serve it, and no caller can fix that.
+ UnmanagedSystemBot,
/// The caller identified no user to own the session.
OwnerRequired,
/// The owner is not a parseable user id.
@@ -1597,6 +1609,9 @@ pub enum CreateSessionApiError {
MixedSessionShape,
/// The thread named neither a parent nor a channel.
ThreadParentRequired,
+ /// A field the request cannot honour for a persona whose runtime is its
+ /// operator's: they configure it, or the caller sends it separately.
+ ExternalPersonaUnsupported(&'static str),
/// The thread already routes to a session; carries it for recovery.
ThreadSessionExists {
/// The existing session, when it could be resolved.
@@ -1632,10 +1647,13 @@ impl IntoResponse for CreateSessionApiError {
StatusCode::UNPROCESSABLE_ENTITY,
"this bot's sessions are opened by the trigger pipeline".to_owned(),
),
- Self::ExternalPersona => (
- StatusCode::UNPROCESSABLE_ENTITY,
- "this persona cannot be started from Macro".to_owned(),
- ),
+ Self::UnmanagedSystemBot => {
+ tracing::error!("a system bot this deployment does not run was selected");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "this agent is misconfigured and cannot be started".to_owned(),
+ )
+ }
Self::OwnerRequired => (
StatusCode::UNPROCESSABLE_ENTITY,
"owner is required for bot callers".to_owned(),
@@ -1655,6 +1673,10 @@ impl IntoResponse for CreateSessionApiError {
StatusCode::UNPROCESSABLE_ENTITY,
"thread.parent is required".to_owned(),
),
+ Self::ExternalPersonaUnsupported(field) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ format!("{field} is not supported for an agent that runs on its own machine"),
+ ),
Self::ThreadSessionExists { session_id } => {
let body = ThreadSessionExistsResponse {
message: THREAD_SESSION_EXISTS_MESSAGE.to_owned(),
@@ -1681,6 +1703,12 @@ impl IntoResponse for CreateSessionApiError {
StatusCode::UNPROCESSABLE_ENTITY,
"owner is not a known user".to_owned(),
),
+ // Nothing to open onto: the persona's runtime is its operator's,
+ // and it did not answer. Says what they have to fix.
+ Self::Domain(AgentSessionError::RuntimeUnavailable(reason)) => {
+ tracing::info!(reason, "create refused: the bot's runtime is unavailable");
+ (StatusCode::CONFLICT, reason.to_owned())
+ }
Self::Domain(error) => {
tracing::error!(error = ?error, "failed to open an agent session");
(
@@ -1795,9 +1823,10 @@ fn resolve_owner(
pub async fn create_agent_session_handler<
Opener: SessionOpener,
Bots: BotDirectory,
+ Requests: ExternalSessionRequester,
Auth: MacroAuthorizationService,
>(
- State(state): State<CreateSessionState<Opener, Bots, Auth>>,
+ State(state): State<CreateSessionState<Opener, Bots, Requests, Auth>>,
caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,
Json(request): Json<CreateAgentSessionRequest>,
) -> Result<(StatusCode, Json<CreateAgentSessionResponse>), CreateSessionApiError> {
@@ -1815,20 +1844,69 @@ 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_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)
+ let selected =
+ 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::UnmanagedSystemBot => {
+ CreateSessionApiError::UnmanagedSystemBot
+ }
+ ManagedPersonaError::Forbidden => CreateSessionApiError::NotYourBot,
+ ManagedPersonaError::Lookup(error) => CreateSessionApiError::Domain(error),
+ })?;
+ match selected {
+ SelectedPersona::Managed(persona) => Some(persona),
+ // The persona's runtime is its operator's, so it opens the
+ // session itself, exactly as it does for a mention: the
+ // request goes out as a trigger and the runtime creates the
+ // session under the id we hand it. Nothing is announced,
+ // there being no thread, and no prompt travels with it - the
+ // caller delivers its first prompt through the control
+ // endpoint once this answers, as it does for a managed one.
+ SelectedPersona::External { bot_id } => {
+ if request.repo_url.is_some() || request.repo_branch.is_some() {
+ return Err(CreateSessionApiError::Domain(
+ AgentSessionError::InvalidRepositorySelection(
+ "repository selection is supported for Cursor coding agents",
+ ),
+ ));
+ }
+ // Refused rather than dropped: nothing delivers it, and a
+ // caller that sent one would otherwise never learn it was
+ // ignored. A model is different - it is applied when the
+ // session binds, like the persona's own.
+ if request.prompt.is_some() {
+ return Err(CreateSessionApiError::ExternalPersonaUnsupported("prompt"));
+ }
+ let owner = owner
+ .as_user()
+ .cloned()
+ .ok_or(CreateSessionApiError::OwnerRequired)?;
+ let session = state
+ .requests
+ .request(RequestedExternalSession {
+ // The caller's id when it minted one, so the
+ // surface it already opened is the session the
+ // runtime creates.
+ session_id: request
+ .id
+ .map(AgentSessionId::new_from_uuid)
+ .unwrap_or_else(AgentSessionId::new),
+ bot_id,
+ owner,
+ model: request.model.filter(|model| !model.trim().is_empty()),
+ })
+ .await?;
+ return Ok((
+ StatusCode::CREATED,
+ Json(CreateAgentSessionResponse {
+ session: AgentSessionResponse::new(session, true),
+ }),
+ ));
+ }
+ }
} else {
None
};
@@ -1864,11 +1942,7 @@ pub async fn create_agent_session_handler<
// An external runtime sends its own first prompt through the control
// endpoint, so accepting one here would silently drop it, and it runs on
// whatever model its operator configured, which is not ours to set.
- if request.prompt.is_some()
- || request.repo_branch.is_some()
- || request.model.is_some()
- || request.id.is_some()
- {
+ if request.prompt.is_some() || request.repo_branch.is_some() || request.model.is_some() {
return Err(CreateSessionApiError::MixedSessionShape);
}
let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;
@@ -1929,6 +2003,7 @@ pub async fn create_agent_session_handler<
let session = match state
.opener
.open_external_session(OpenExternalAgentSession {
+ id: request.id.map(AgentSessionId::new_from_uuid),
bot_id,
profile: managed_profile,
workspace,
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 9cd5749088..8f407c224d 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -201,6 +201,28 @@ impl OneBotDirectory {
}
}
+ /// A saved agent bound to the owner's paired macrod runtime.
+ fn macrod_agent() -> Self {
+ Self {
+ shares_channel_with: Vec::new(),
+ facts: BotFacts {
+ has_agent: true,
+ is_managed: false,
+ is_system: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
+ harness_id: Some(harness_id::HarnessId::TEST_A),
+ managed_profile: Some(crate::domain::ports::ManagedAgentProfile {
+ model: "persona-model".to_owned(),
+ harness: "macrod".to_owned(),
+ instructions: "persona instructions".to_owned(),
+ mcp_servers: Default::default(),
+ }),
+ selected_channels: false,
+ },
+ }
+ }
+
fn managed_agent() -> Self {
Self {
shares_channel_with: Vec::new(),
@@ -300,7 +322,80 @@ impl BotDirectory for OneBotDirectory {
}
}
+/// What a requester says when no runtime creates the session.
+const RUNTIME_UNAVAILABLE_REASON: &str =
+ "this agent's runtime did not open the session; make sure macrod is running and up to date";
+
+/// Stands in for the bot's runtime: records what was asked and answers with
+/// a session under the requested id, as macrod would have created it.
+#[derive(Default)]
+struct RecordingRequester {
+ requested: Mutex<Vec<RequestedExternalSession>>,
+ /// No runtime answers, as when the operator's macrod is not running.
+ unavailable: bool,
+}
+
+impl RecordingRequester {
+ /// A requester whose runtime never creates the session.
+ fn unavailable() -> Self {
+ Self {
+ requested: Mutex::default(),
+ unavailable: true,
+ }
+ }
+}
+
+impl ExternalSessionRequester for RecordingRequester {
+ async fn request(
+ &self,
+ request: RequestedExternalSession,
+ ) -> crate::domain::error::Result<AgentSession> {
+ if self.unavailable {
+ self.requested.lock().unwrap().push(request);
+ return Err(crate::domain::error::AgentSessionError::RuntimeUnavailable(
+ RUNTIME_UNAVAILABLE_REASON,
+ ));
+ }
+ let session = AgentSession {
+ repo_branch: None,
+ pull_request_url: None,
+ id: request.session_id,
+ name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
+ owner_id: Owner::User(request.owner.clone()),
+ thread_id: None,
+ thread_parent: None,
+ originating_message_id: None,
+ bot_id: request.bot_id,
+ model: request
+ .model
+ .clone()
+ .unwrap_or_else(|| "persona-model".to_owned()),
+ harness: "macrod".to_owned(),
+ repo_url: None,
+ workspace: "/home/operator/code".to_owned(),
+ sandbox_size: crate::domain::model::SandboxSize::Default,
+ instructions: None,
+ mcp_servers: Default::default(),
+ acp_session_id: None,
+ external: None,
+ status: SessionStatus::NoMessages,
+ created_at: Utc::now(),
+ modified_at: Utc::now(),
+ };
+ self.requested.lock().unwrap().push(request);
+ Ok(session)
+ }
+}
+
fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
+ router_with_requests(opener, bots, Arc::new(RecordingRequester::default()))
+}
+
+fn router_with_requests(
+ opener: Arc<RecordingOpener>,
+ bots: OneBotDirectory,
+ requests: Arc<RecordingRequester>,
+) -> Router {
let service = MacroAuthorizationServiceImpl::new(
FakeJwtValidator,
InternalAuthConfig {
@@ -314,6 +409,7 @@ fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
agent_session_create_router(CreateSessionState::new(
opener,
Arc::new(bots),
+ requests,
MacroAuthorizationState::new(Arc::new(service)),
))
}
@@ -739,6 +835,130 @@ async fn anyone_can_select_a_managed_system_bot() {
assert!(selected.profile.is_none());
}
+/// The composer sends the managed shape for every persona it lists, and
+/// mints the id it has already opened a surface on. A bot whose runtime its
+/// operator runs is not opened here: the request is handed to that runtime
+/// under that id, and the session it creates is what the caller gets back.
+/// No prompt travels with it - the caller sends its own through the session
+/// once this answers.
+#[tokio::test]
+async fn an_owner_starts_their_macrod_agent_from_the_composer() {
+ let opener = Arc::new(RecordingOpener::default());
+ let requests = Arc::new(RecordingRequester::default());
+ let minted = macro_uuid::generate_uuid_v7();
+ let request = as_user(
+ OWNER,
+ serde_json::json!({
+ "id": minted,
+ "botId": BotId::TEST_A.as_uuid(),
+ "model": "claude-opus-5",
+ })
+ .to_string(),
+ );
+
+ let response = router_with_requests(
+ opener.clone(),
+ OneBotDirectory::macrod_agent(),
+ requests.clone(),
+ )
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ assert!(opener.managed.lock().unwrap().is_empty());
+ assert!(opener.opened.lock().unwrap().is_empty());
+ {
+ let requested = requests.requested.lock().unwrap();
+ assert_eq!(requested.len(), 1);
+ assert_eq!(requested[0].bot_id, BotId::TEST_A);
+ assert_eq!(requested[0].owner.as_ref(), OWNER);
+ assert_eq!(requested[0].session_id.as_uuid(), minted);
+ assert_eq!(requested[0].model.as_deref(), Some("claude-opus-5"));
+ }
+
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(payload["session"]["id"], minted.to_string());
+ assert_eq!(payload["session"]["model"], "claude-opus-5");
+}
+
+/// Nothing delivers a prompt sent this way, so a caller that sends one is
+/// told rather than left to wonder why it had no effect.
+#[tokio::test]
+async fn a_macrod_agent_refuses_a_prompt_on_the_create() {
+ let requests = Arc::new(RecordingRequester::default());
+ let request = as_user(
+ OWNER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid(), "prompt": "fix it" }).to_string(),
+ );
+
+ let response = router_with_requests(
+ Arc::new(RecordingOpener::default()),
+ OneBotDirectory::macrod_agent(),
+ requests.clone(),
+ )
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(requests.requested.lock().unwrap().is_empty());
+}
+
+/// A runtime that never creates the session is a conflict the operator can
+/// act on, not a server fault: the message says what to fix.
+#[tokio::test]
+async fn a_macrod_agent_whose_runtime_never_answers_is_a_conflict() {
+ let requests = Arc::new(RecordingRequester::unavailable());
+ let request = as_user(
+ OWNER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid() }).to_string(),
+ );
+
+ let response = router_with_requests(
+ Arc::new(RecordingOpener::default()),
+ OneBotDirectory::macrod_agent(),
+ requests.clone(),
+ )
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::CONFLICT);
+ assert_eq!(requests.requested.lock().unwrap().len(), 1);
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ assert_eq!(
+ String::from_utf8(bytes.to_vec()).unwrap(),
+ RUNTIME_UNAVAILABLE_REASON
+ );
+}
+
+#[tokio::test]
+async fn a_stranger_cannot_start_someone_elses_macrod_agent() {
+ let requests = Arc::new(RecordingRequester::default());
+ let request = as_user(
+ STRANGER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid() }).to_string(),
+ );
+
+ let response = router_with_requests(
+ Arc::new(RecordingOpener::default()),
+ OneBotDirectory::macrod_agent(),
+ requests.clone(),
+ )
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert!(requests.requested.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn a_stranger_cannot_select_someone_elses_managed_persona() {
let opener = Arc::new(RecordingOpener::default());
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 5a77d09146..35e48546a3 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -58,6 +58,24 @@ pub struct AgentMentionedEvent {
pub message: MessagePostedMetadata,
}
+/// A session somebody asked for from Macro itself - the composer - rather
+/// than by mentioning the bot. Nothing was posted anywhere, so there is no
+/// thread to announce into and no message to quote.
+///
+/// Served by the bot's own runtime, which creates the session under the id
+/// named here so the requester can find it. No prompt: whoever asked
+/// delivers theirs through the session's control endpoint once it exists,
+/// so nothing a user typed travels on this topic.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AgentSessionRequestedEvent {
+ /// The bot the session runs for.
+ pub bot_id: BotId,
+ /// The id the runtime must create the session under.
+ pub session_id: AgentSessionId,
+ /// Who asked; owns the session the runtime creates.
+ pub owner: String,
+}
+
/// Events that open a new session.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -67,6 +85,9 @@ pub enum NewAgentSessionEvent {
TopLevelMentioned(AgentBotMentionedEvent),
/// Opened by a bot mention on a message parent other than a channel.
Mentioned(AgentMentionedEvent),
+ /// Asked for from the composer, with no mention behind it. Consumers that
+ /// only know mentions see no [`OpeningMention`] here and skip it.
+ Requested(AgentSessionRequestedEvent),
}
/// The mention a new-session event carries, whichever parent it was on.
@@ -92,6 +113,16 @@ impl NewAgentSessionEvent {
bot_id: mentioned.bot_id,
message: mentioned.message.clone(),
}),
+ Self::Requested(_) => None,
+ }
+ }
+
+ /// The composer request this event carries, if that is what it is.
+ #[must_use]
+ pub fn requested(&self) -> Option<&AgentSessionRequestedEvent> {
+ match self {
+ Self::Requested(requested) => Some(requested),
+ Self::TopLevelMentioned(_) | Self::Mentioned(_) => None,
}
}
}
@@ -200,7 +231,10 @@ impl AgentTriggerTopicEvent {
#[must_use]
pub fn bot_id(&self) -> Option<BotId> {
match self {
- Self::New(event) => event.mention().map(|mention| mention.bot_id),
+ Self::New(event) => event
+ .mention()
+ .map(|mention| mention.bot_id)
+ .or_else(|| event.requested().map(|requested| requested.bot_id)),
Self::Existing(event) => event.session_message().map(|message| message.bot_id),
}
}
@@ -349,10 +383,17 @@ impl AgentSessionMacroEvent {
let bot_id = match &event {
NewAgentSessionEvent::TopLevelMentioned(mentioned) => mentioned.bot_id,
NewAgentSessionEvent::Mentioned(mentioned) => mentioned.bot_id,
+ NewAgentSessionEvent::Requested(requested) => requested.bot_id,
};
Self::new(bot_id, AgentTriggerTopicEvent::New(event))
}
+ /// Ask a bot's own runtime to open a session nobody mentioned it for.
+ #[must_use]
+ pub fn requested_event(event: AgentSessionRequestedEvent) -> Self {
+ Self::new_session(NewAgentSessionEvent::Requested(event))
+ }
+
/// Feed one of a bot's existing sessions, however the message arrived.
#[must_use]
pub fn existing_event(event: ExistingAgentSessionEvent, bot_id: BotId) -> Self {
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index 0ad2be2381..da6750eb50 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -127,6 +127,36 @@ impl WorkExecutor for Dispatcher {
self.api.prompt(session, &sender, &content).await?;
Ok(())
}
+ TriggerWork::OpenRequested {
+ session,
+ bot,
+ sender,
+ } => {
+ // Same create as a mention, minus the thread: the requester is
+ // waiting on this id, so the session is created under it. No
+ // prompt here - whoever asked sends their own through the
+ // session once this create answers them.
+ let request = CreateAgentSessionRequest {
+ id: Some(session.as_uuid()),
+ bot_id: Some(bot.as_uuid()),
+ workspace: Some(self.workspace.path.to_string_lossy().into_owned()),
+ prompt: None,
+ repo_url: self.workspace.repo_url.clone(),
+ repo_branch: None,
+ owner: Some(sender.as_ref().to_owned()),
+ thread: None,
+ instructions: None,
+ model: None,
+ };
+ self.api.create_session(&request, &sender).await?;
+ // Be dialed in before the prompt the requester is about to
+ // send arrives, so it lands on a runtime that is serving.
+ self.runtime
+ .ensure_connected()
+ .await
+ .map_err(DispatchError::Dial)?;
+ Ok(())
+ }
TriggerWork::PromptExisting {
session,
sender,
diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rs
index af0afeed1d..6cf640239f 100644
--- a/crates/coding_agent_worker/src/trigger.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -5,7 +5,8 @@
use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
- AgentTriggerEventName, AgentTriggerTopicEvent, OpeningMention, SessionMessage,
+ AgentSessionRequestedEvent, AgentTriggerEventName, AgentTriggerTopicEvent,
+ NewAgentSessionEvent, OpeningMention, SessionMessage,
};
use bot_id::BotId;
use macro_event_broker::Event;
@@ -41,6 +42,18 @@ pub enum TriggerWork {
/// The mention's text: the first prompt, and the announcement quote.
content: String,
},
+ /// Open a session somebody asked for from the composer, under the id
+ /// they are waiting on. No thread, so nothing is announced anywhere;
+ /// the app shows the session directly and sends its own first prompt
+ /// through the session once this create answers.
+ OpenRequested {
+ /// The id to create the session under.
+ session: AgentSessionId,
+ /// The agent the session runs for.
+ bot: BotId,
+ /// Who asked; owns the session.
+ sender: MacroUserIdStr<'static>,
+ },
/// Forward a message into a session that already exists, serving it
/// first if this daemon is not already. Just the prompt: the harness
/// service announces the reply into its channel from the trigger event
@@ -69,6 +82,20 @@ pub enum Skipped {
/// Translate one trigger event into this daemon's work, or a reason to skip.
pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skipped> {
match event {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::Requested(
+ AgentSessionRequestedEvent {
+ bot_id,
+ session_id,
+ owner,
+ },
+ )) => {
+ let sender = MacroUserIdStr::try_from(owner).map_err(|_| Skipped::NotFromUser)?;
+ Ok(TriggerWork::OpenRequested {
+ session: session_id,
+ bot: bot_id,
+ sender,
+ })
+ }
AgentTriggerTopicEvent::New(event) => {
let Some(OpeningMention { bot_id, message }) = event.mention() else {
return Err(Skipped::Unrecognized);
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index 67b4ce5356..cf13071378 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -392,19 +392,37 @@ fn normalized_event(
///
/// Not the bot the event names: that is what a subscriber filters on, and a
/// bot is not an entity anyone holds access to.
-pub(crate) struct TriggerAudience {
- pub(crate) entity_id: String,
- pub(crate) entity_type: EntityType,
+pub(crate) enum TriggerAudience {
+ /// Whoever currently holds access to an entity.
+ Entity {
+ entity_id: String,
+ entity_type: EntityType,
+ },
+ /// Named people, when nothing was posted anywhere to hold access to.
+ People(Vec<MacroUserIdStr<'static>>),
}
impl TriggerAudience {
/// Whoever may currently read the conversation's parent.
fn parent(parent: &MessageParent) -> Self {
- Self {
+ Self::Entity {
entity_id: parent.entity_id(),
entity_type: parent.access_entity_type(),
}
}
+
+ /// The one person who asked for a session from the composer: nothing was
+ /// posted, so nobody else's access is in question. Their runtime, or
+ /// their team's, is who serves it.
+ fn requester(owner: &str) -> Result<Self, WebhookEventIngestionError> {
+ let owner = MacroUserIdStr::try_from(owner.to_owned()).map_err(|_| {
+ WebhookEventIngestionError::InvalidEntityId {
+ entity_type: "user",
+ entity_id: owner.to_owned(),
+ }
+ })?;
+ Ok(Self::People(vec![owner]))
+ }
}
/// Normalize one agent-trigger event.
@@ -420,13 +438,24 @@ pub(crate) fn normalized_agent_trigger_event(
) -> Result<(NormalizedWebhookEvent, TriggerAudience), WebhookEventIngestionError> {
use agent_trigger::domain::broker_events::AgentTriggerEventName;
- let (bot_id, parent) = match &event.event {
- AgentTriggerTopicEvent::New(new) => new
- .mention()
- .map(|mention| (mention.bot_id, mention.message.parent)),
- AgentTriggerTopicEvent::Existing(existing) => existing
- .session_message()
- .map(|message| (message.bot_id, message.message.parent)),
+ let (bot_id, audience) = match &event.event {
+ AgentTriggerTopicEvent::New(new) => match (new.mention(), new.requested()) {
+ (Some(mention), _) => Some((
+ mention.bot_id,
+ TriggerAudience::parent(&mention.message.parent),
+ )),
+ (None, Some(requested)) => Some((
+ requested.bot_id,
+ TriggerAudience::requester(&requested.owner)?,
+ )),
+ (None, None) => None,
+ },
+ AgentTriggerTopicEvent::Existing(existing) => existing.session_message().map(|message| {
+ (
+ message.bot_id,
+ TriggerAudience::parent(&message.message.parent),
+ )
+ }),
}
// Both trigger enums are non-exhaustive on purpose; an unknown shape
// has no bot to route to. Permanent, so the consumer skips it.
@@ -434,7 +463,6 @@ pub(crate) fn normalized_agent_trigger_event(
entity_type: "bot",
entity_id: "unrecognized agent-trigger event shape".to_owned(),
})?;
- let audience = TriggerAudience::parent(&parent);
let event_name: &'static str = AgentTriggerEventName::from(&event.event).into();
let broker_envelope = serde_json::to_value(event)?;
let bot_id = bot_id.to_string();
@@ -555,9 +583,13 @@ where
event: Event<AgentTriggerTopicEvent>,
) -> Result<(), WebhookEventIngestionError> {
let (event, audience) = normalized_agent_trigger_event(&event)?;
- let accessors = self
- .users_with_access(&audience.entity_id, audience.entity_type)
- .await?;
+ let accessors = match audience {
+ TriggerAudience::Entity {
+ entity_id,
+ entity_type,
+ } => self.users_with_access(&entity_id, entity_type).await?,
+ TriggerAudience::People(people) => people,
+ };
let workspace_ids = self
.repository
.resolve_workspace_ids(accessors)
@@ -583,9 +615,8 @@ where
} => {
let mut accessors = vec![owner];
if let Some(parent) = origin_parent {
- let audience = TriggerAudience::parent(&parent);
accessors.extend(
- self.users_with_access(&audience.entity_id, audience.entity_type)
+ self.users_with_access(&parent.entity_id(), parent.access_entity_type())
.await?,
);
}
diff --git a/crates/webhook/src/domain/ingestion/stream.rs b/crates/webhook/src/domain/ingestion/stream.rs
index 279e7678fb..e7342166f5 100644
--- a/crates/webhook/src/domain/ingestion/stream.rs
+++ b/crates/webhook/src/domain/ingestion/stream.rs
@@ -1,7 +1,7 @@
//! Stream-candidate adapters over shared webhook event normalization.
use super::{
- LifecycleAudience, WebhookEventIngestionError, lifecycle_audience,
+ LifecycleAudience, TriggerAudience, WebhookEventIngestionError, lifecycle_audience,
normalized_agent_session_lifecycle_event, normalized_agent_trigger_event,
normalized_channel_event, normalized_document_event, normalized_webhook_event,
};
@@ -57,11 +57,27 @@ pub(crate) fn agent_trigger_stream_candidate(
event: &Event<AgentTriggerTopicEvent>,
) -> Result<StreamCandidateEvent, WebhookEventIngestionError> {
let (normalized, audience) = normalized_agent_trigger_event(event)?;
- Ok(StreamCandidateEvent {
- audience: StreamAudience::Entity {
- entity_id: audience.entity_id,
- entity_type: audience.entity_type,
+ let audience = match audience {
+ TriggerAudience::Entity {
+ entity_id,
+ entity_type,
+ } => StreamAudience::Entity {
+ entity_id,
+ entity_type,
},
+ // Named people subscribe from their own workspaces, as a departed
+ // session's owner does.
+ TriggerAudience::People(people) => StreamAudience::Any(
+ people
+ .into_iter()
+ .map(|person| StreamAudience::Workspace {
+ workspace_id: person.to_string(),
+ })
+ .collect(),
+ ),
+ };
+ Ok(StreamCandidateEvent {
+ audience,
event: normalized,
})
}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index f2a9960385..d4170dcb11 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1350,6 +1350,23 @@ fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::Agen
))
}
+fn agent_trigger_requested_event()
+-> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent> {
+ use agent_trigger::domain::broker_events::{
+ AgentSessionRequestedEvent, AgentTriggerTopicEvent, NewAgentSessionEvent,
+ };
+
+ Event::new(AgentTriggerTopicEvent::New(
+ NewAgentSessionEvent::Requested(AgentSessionRequestedEvent {
+ bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
+ session_id: agent_session::domain::model::AgentSessionId::new_from_uuid(
+ uuid::Uuid::from_u128(0x5E55),
+ ),
+ owner: "macro|[email protected]".to_owned(),
+ }),
+ ))
+}
+
fn agent_trigger_document_event()
-> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent> {
use agent_trigger::domain::broker_events::{
@@ -1445,6 +1462,44 @@ async fn an_existing_session_trigger_is_gated_by_its_message_parent() {
);
}
+/// A session asked for from the composer was posted nowhere, so there is no
+/// parent whose readers decide who sees it: the requester alone does, and
+/// their workspaces are where the bot's runtime subscribes from.
+#[tokio::test]
+async fn a_requested_session_is_scoped_to_its_requester_and_named_by_the_bot() {
+ let access = MockAccessService::with_users(vec![]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+ let event = agent_trigger_requested_event();
+
+ service
+ .ingest_agent_trigger_event(event.clone())
+ .await
+ .expect("requested sessions are ingested");
+
+ // Nobody's access was consulted: the requester is the audience.
+ assert!(lock(&access.calls).is_empty());
+ let bot_id = bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)).to_string();
+ let repository_state = lock(&repository.state);
+ assert_eq!(repository_state.match_calls.len(), 1);
+ assert_eq!(repository_state.match_calls[0].entity_id, bot_id);
+ assert_eq!(
+ repository_state.match_calls[0].event_name,
+ "agent_trigger.new"
+ );
+ drop(repository_state);
+ let enqueuer_state = lock(&enqueuer.state);
+ assert_eq!(enqueuer_state.attempted_messages.len(), 1);
+ assert_eq!(
+ enqueuer_state.attempted_messages[0].event.broker_envelope,
+ serde_json::to_value(&event).expect("a serializable envelope"),
+ );
+}
+
#[tokio::test]
async fn agent_trigger_events_are_scoped_by_the_channel_but_named_by_the_bot() {
let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 49d7c8d086..87d81176c7 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -627,8 +627,9 @@ export type CreateAgentSessionRequest = {
* open on the session's final id - URL, history row, references - the
* moment the user acts, rather than after this request answers (which
* for a managed sandbox can take a while). Omitted, the service mints
- * one. Managed sessions only. Answers 409 if a session already holds
- * the id.
+ * one. Answers 409 if a session already holds the id. On an external
+ * request it is how a runtime answering a composer request names the
+ * id it was handed, so the requester waiting on that id finds the session.
*/
id?: string | null;
/**
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index cca82e9347..55c3fb743e 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -2299,7 +2299,7 @@
"id": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Managed sessions only. Answers 409 if a session already holds\nthe id."
+ "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Answers 409 if a session already holds the id. On an external\nrequest it is how a runtime answering a composer request names the\nid it was handed, so the requester waiting on that id finds the session."
},
"instructions": {
"type": ["string", "null"],
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 2ceb1f1a1b..75f4f6836d 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -16,7 +16,7 @@ use agent_harness::inbound::repositories::{
};
use agent_harness::inbound::runtime_gateway::{RuntimeGatewayState, runtime_gateway_router};
use agent_session::domain::ports::{
- AgentSessionNotificationRecipient, BotDirectory, SessionOpener,
+ AgentSessionNotificationRecipient, BotDirectory, ExternalSessionRequester, SessionOpener,
};
use agent_session::domain::service::AgentSessionService;
use agent_session::inbound::axum_router::{
@@ -61,10 +61,10 @@ fn health_router(ready: tokio::sync::watch::Receiver<bool>) -> Router {
}
/// All route state served by the public agent-harness HTTP listener.
-pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes> {
+pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes> {
read: AgentSessionRouterState<T, Access, Auth>,
control: AgentSessionControlState<R, Access, Auth>,
- create: CreateSessionState<Opener, Bots, Auth>,
+ create: CreateSessionState<Opener, Bots, Requests, Auth>,
gateway: RuntimeGatewayState<Auth>,
models: AgentModelsRouterState<Models, Auth>,
repositories: AgentRepositoriesRouterState<Auth>,
@@ -73,14 +73,14 @@ pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes> {
changes: AgentChangesRouterState<Changes, Access, Auth>,
}
-impl<T, R, Opener, Bots, Access, Auth, Models, Changes>
- ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>
+impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
+ ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
{
/// Group the independently constructed route states for the HTTP server.
pub fn new(
read: AgentSessionRouterState<T, Access, Auth>,
control: AgentSessionControlState<R, Access, Auth>,
- create: CreateSessionState<Opener, Bots, Auth>,
+ create: CreateSessionState<Opener, Bots, Requests, Auth>,
gateway: RuntimeGatewayState<Auth>,
models: AgentModelsRouterState<Models, Auth>,
repositories: AgentRepositoriesRouterState<Auth>,
@@ -143,8 +143,8 @@ where
}
/// Build the router and serve it until the process is asked to stop.
-pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth, Models, Changes>(
- states: ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>,
+pub async fn setup_and_serve<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>(
+ states: ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>,
runtime_commands_ready: tokio::sync::watch::Receiver<bool>,
port: u16,
shutdown: impl Future<Output = ()> + Send + 'static,
@@ -154,6 +154,7 @@ where
R: AgentSessionNotificationRecipient,
Opener: SessionOpener,
Bots: BotDirectory,
+ Requests: ExternalSessionRequester,
Access: EntityAccessService,
Auth: MacroAuthorizationService,
Models: AgentModelsService,
@@ -182,14 +183,15 @@ where
.context("agent harness service http failed")
}
-fn api_router<T, R, Opener, Bots, Access, Auth, Models, Changes>(
- states: ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>,
+fn api_router<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>(
+ states: ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>,
) -> Router
where
T: AgentSessionService,
R: AgentSessionNotificationRecipient,
Opener: SessionOpener,
Bots: BotDirectory,
+ Requests: ExternalSessionRequester,
Access: EntityAccessService,
Auth: MacroAuthorizationService,
Models: AgentModelsService,
diff --git a/services/agent_harness_service/src/external_session_requests.rs b/services/agent_harness_service/src/external_session_requests.rs
new file mode 100644
index 0000000000..96ef2061bd
--- /dev/null
+++ b/services/agent_harness_service/src/external_session_requests.rs
@@ -0,0 +1,92 @@
+//! Composer requests for sessions on a bot's own runtime.
+//!
+//! Composition-root adapter: the request goes out on the agent-trigger topic
+//! the same way a mention does, the runtime creates the session under the id
+//! it was handed, and this side waits for that row to appear so the caller
+//! gets the session back the way every other create does.
+
+use std::time::Duration;
+
+use agent_session::domain::error::AgentSessionError;
+use agent_session::domain::model::AgentSession;
+use agent_session::domain::ports::{
+ AgentSessionRepo, ExternalSessionRequester, RequestedExternalSession,
+};
+use agent_trigger::domain::broker_events::{AgentSessionMacroEvent, AgentSessionRequestedEvent};
+use macro_event_broker::MacroEventBroker;
+
+/// How long a runtime gets to create the session before the request is
+/// refused. A daemon that is up answers well inside this; one that is down
+/// or too old to know the event never will.
+const RUNTIME_ANSWER_TIMEOUT: Duration = Duration::from_secs(8);
+const POLL_INTERVAL: Duration = Duration::from_millis(250);
+
+/// [`ExternalSessionRequester`] over the trigger topic and the session table.
+pub struct BrokerExternalSessionRequests<Broker, Sessions> {
+ broker: Broker,
+ sessions: Sessions,
+}
+
+impl<Broker, Sessions> BrokerExternalSessionRequests<Broker, Sessions> {
+ /// Publish through `broker`; watch `sessions` for the created row.
+ pub fn new(broker: Broker, sessions: Sessions) -> Self {
+ Self { broker, sessions }
+ }
+}
+
+impl<Broker, Sessions> ExternalSessionRequester for BrokerExternalSessionRequests<Broker, Sessions>
+where
+ Broker: MacroEventBroker,
+ Sessions: AgentSessionRepo,
+{
+ async fn request(
+ &self,
+ request: RequestedExternalSession,
+ ) -> agent_session::domain::error::Result<AgentSession> {
+ let session_id = request.session_id;
+ let event = AgentSessionMacroEvent::requested_event(AgentSessionRequestedEvent {
+ bot_id: request.bot_id,
+ session_id,
+ owner: request.owner.as_ref().to_owned(),
+ });
+ self.broker
+ .send_event(&event)
+ .map_err(|error| AgentSessionError::Unknown(anyhow::anyhow!(error)))?
+ .await
+ .map_err(|error| AgentSessionError::Unknown(anyhow::anyhow!(error)))?
+ .map_err(|error| AgentSessionError::Unknown(anyhow::anyhow!(error)))?;
+
+ // The runtime creates the row; there is no other signal to wait on.
+ let deadline = tokio::time::Instant::now() + RUNTIME_ANSWER_TIMEOUT;
+ loop {
+ match self.sessions.get(session_id).await {
+ Ok(session) => {
+ let Some(model) = request.model else {
+ return Ok(session);
+ };
+ // The runtime created the row on the persona's default.
+ // The choice goes on the row now, ahead of the first
+ // prompt - which the caller cannot send before this
+ // answers - so the session binds on it, exactly as it
+ // would on the persona's own.
+ self.sessions.set_model(session_id, &model).await?;
+ return self.sessions.get(session_id).await;
+ }
+ Err(error) => {
+ if tokio::time::Instant::now() >= deadline {
+ tracing::info!(
+ %session_id,
+ bot_id = %request.bot_id,
+ last_error = %error,
+ "no runtime created the requested session in time"
+ );
+ return Err(AgentSessionError::RuntimeUnavailable(
+ "this agent's runtime did not open the session; make sure macrod is running and up to date",
+ ));
+ }
+ }
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ }
+}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 573dc80560..980f22d19e 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -12,6 +12,7 @@ mod api;
mod bots_directory;
mod config;
mod containers;
+mod external_session_requests;
mod harness_bindings;
mod internal_mcp;
mod model_providers;
@@ -739,7 +740,7 @@ async fn run() -> anyhow::Result<()> {
messages::domain::service::MessageService::new(
messages::outbound::pg_message_repo::PgMessageRepository::new(pool.clone()),
messages::domain::effects::MessageEffects::new(
- messages::outbound::broker::BrokerMessagePublisher::new(broker),
+ messages::outbound::broker::BrokerMessagePublisher::new(broker.clone()),
messages::domain::ports::NoMessageEventPublisher,
message_delivery,
),
@@ -1004,6 +1005,12 @@ async fn run() -> anyhow::Result<()> {
let create_state = CreateSessionState::new(
harness.clone(),
bots_directory.clone(),
+ Arc::new(
+ external_session_requests::BrokerExternalSessionRequests::new(
+ broker.clone(),
+ session_repo.clone(),
+ ),
+ ),
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
);
let gateway_state = RuntimeGatewayState::new(