Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-sessions): back-link the agent session from its pull requests (#9234)
Eric Hayesd724afd86d04
diff --git a/.agents/skills/git/SKILL.md b/.agents/skills/git/SKILL.mdindex e3eb3a4120..8ab93466ac 100644--- a/.agents/skills/git/SKILL.md+++ b/.agents/skills/git/SKILL.md@@ -61,7 +61,7 @@ test fixtures. Describe the code change and nothing else.(`Slack integration`), never as the source of a request or report.- Never cite support channels, tickets, chat channels or threads, calls,meetings, emails, or links into support tools or Macro workspace items- (task links are fine). Don't say who asked or where it was reported.+ (task and agent-session links are fine). Don't say who asked or where it was reported.- Never mention places tied to a person or customer (cities, offices, regions).- When the reason matters, say it in general terms: "Users with long readhistories saw channels load slowly", not "<customer> reported indiff --git a/.github/workflows/pr-privacy-check.yml b/.github/workflows/pr-privacy-check.ymlindex 66e2ed264e..da47713477 100644--- a/.github/workflows/pr-privacy-check.yml+++ b/.github/workflows/pr-privacy-check.yml@@ -66,9 +66,10 @@ jobs:report "$source" "phone number" "$(grep -oE '(\+[0-9]{1,3}[ .-]?)?\(?[0-9]{3}\)?[ .-][0-9]{3}[ .-][0-9]{4}' <<<"$text" || true)"report "$source" "support or chat link" "$(grep -oiE 'https?://([a-z0-9-]+\.slack\.com/(archives|client|team)|app\.slack\.com/client|app\.intercom\.(com|io)|[a-z0-9-]+\.zendesk\.com/agent|app\.frontapp\.com|discord\.com/channels|mail\.google\.com|app\.hubspot\.com|app\.usepylon\.com|app\.plain\.com|app\.crisp\.chat|secure\.helpscout\.net)[^[:space:])>]*' <<<"$text" || true)"# Links to workspace items (channels, documents, chats, emails). Tasks are- # the issue tracker and may be linked like GitHub issues.+ # the issue tracker and may be linked like GitHub issues; agent sessions are+ # the provenance coding agents link from the pull requests they open.report "$source" "Macro workspace link" "$(grep -oiE 'https?://([a-z0-9-]+\.)?macro\.com/app/[a-z-]+/[A-Za-z0-9-]+[^[:space:])>`]*' <<<"$text" \- | grep -viE '/app/tasks?/' || true)"+ | grep -viE '^https?://([a-z0-9-]+\.)?macro\.com/app/(tasks?|agent)/' || true)"# `@scope/package` names end in a slash and are not mentions.report "$source" "@mention" "$(grep -oE '(^|[[:space:](])@[A-Za-z0-9][A-Za-z0-9-]*/?' <<<"$prose" \| sed -E 's/^[[:space:](]*//' | grep -v '/$' \diff --git a/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.md b/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.mdindex fd69b5a871..6a1d6b596a 100644--- a/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.md+++ b/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.md@@ -1,3 +1,3 @@## Pull requests-Deliver the work as a pull request, and register it with macro_internal.set_pull_request.+Deliver the work as a pull request, register it with macro_internal.set_pull_request, and link the session_url it returns in the pull request description.diff --git a/crates/agent_session/src/inbound/toolset/context.rs b/crates/agent_session/src/inbound/toolset/context.rsindex cd6ef8caa1..3d91c3ae9c 100644--- a/crates/agent_session/src/inbound/toolset/context.rs+++ b/crates/agent_session/src/inbound/toolset/context.rs@@ -15,4 +15,6 @@ pub struct SessionToolContext {pub tasks: Arc<dyn SessionTasks>,/// Session resolved from the request credential.pub session: AgentSessionId,+ /// The session's page in the Macro app.+ pub session_url: String,}diff --git a/crates/agent_session/src/inbound/toolset/mod.rs b/crates/agent_session/src/inbound/toolset/mod.rsindex f611651243..943439578f 100644--- a/crates/agent_session/src/inbound/toolset/mod.rs+++ b/crates/agent_session/src/inbound/toolset/mod.rs@@ -14,7 +14,7 @@ pub use coding_agents::{pub use context::SessionToolContext;pub use link_task::LinkTask;pub use read_agent_session::{ReadAgentSession, ReadAgentSessionContext};-pub use set_pull_request::SetPullRequest;+pub use set_pull_request::{SetPullRequest, SetPullRequestOutput};pub use task_pull_requests::TaskPullRequestsTool;mod manage_agent_session;diff --git a/crates/agent_session/src/inbound/toolset/set_pull_request.rs b/crates/agent_session/src/inbound/toolset/set_pull_request.rsindex 8361a21230..b761a93131 100644--- a/crates/agent_session/src/inbound/toolset/set_pull_request.rs+++ b/crates/agent_session/src/inbound/toolset/set_pull_request.rs@@ -6,7 +6,7 @@ use ai_toolset::{};use async_trait::async_trait;use schemars::JsonSchema;-use serde::Deserialize;+use serde::{Deserialize, Serialize};use super::SessionToolContext;@@ -15,7 +15,7 @@ use super::SessionToolContext;#[serde(deny_unknown_fields)]#[schemars(title = "set_pull_request",- description = "Set the pull request associated with this coding session. This records the link shown in Macro; it does not create or modify the GitHub PR. Returns the recorded URL."+ description = "Set the pull request associated with this coding session. This records the link shown in Macro; it does not create or modify the GitHub PR. Returns the recorded URL and this session's Macro link, which belongs in the pull request description.")]pub struct SetPullRequest {/// Link to the PR this session works on.@@ -25,6 +25,15 @@ pub struct SetPullRequest {pub url: String,}+/// The recorded pull request and the session that opened it.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SetPullRequestOutput {+ /// The pull request URL as recorded.+ pub pull_request_url: String,+ /// The calling session in the Macro app, to link from the pull request description.+ pub session_url: String,+}+impl ToolAnnotated for SetPullRequest {const ANNOTATIONS: ToolAnnotations =ToolAnnotations::destructive("Set pull request").with_idempotent();@@ -32,21 +41,25 @@ impl ToolAnnotated for SetPullRequest {#[async_trait]impl AsyncTool<SessionToolContext> for SetPullRequest {- type Output = String;+ type Output = SetPullRequestOutput;#[tracing::instrument(skip_all, err)]async fn call(&self,context: ServiceContext<SessionToolContext>,request: RequestContext,- ) -> ToolResult<String> {- context+ ) -> ToolResult<SetPullRequestOutput> {+ let pull_request_url = context.service.set_pull_request(context.session, &request.user_id, &self.url, None).await.map_err(|error| ToolCallError {description: error.to_string(),internal_error: error.into(),- })+ })?;+ Ok(SetPullRequestOutput {+ pull_request_url,+ session_url: context.session_url.clone(),+ })}}diff --git a/crates/prompt/src/pull_requests.rs b/crates/prompt/src/pull_requests.rsindex 62e7a439f8..37c29de0d4 100644--- a/crates/prompt/src/pull_requests.rs+++ b/crates/prompt/src/pull_requests.rs@@ -8,6 +8,9 @@ use crate::types::StaticPrompt;/// Standing instruction for opening a pull request a person can merge.pub const READY_PULL_REQUEST: &str = "When you open a pull request, open it ready for review, not as a draft, and get CI passing before you hand it off. A draft, or a pull request whose checks are failing or still running, is not finished. If it was created as a draft, mark it ready for review.";+/// Back-link from a pull request to the session that opened it.+pub const SESSION_BACKLINK: &str = "macro_internal.set_pull_request returns this session's session_url; link it in the pull request description (for example, \"Macro agent session: <session_url>\") so reviewers can see how the change was made. Edit the description to add it if the pull request already exists.";+/// The pull-request section of the instructions for external MCP clients,/// which may be coding agents. In-app hosts have no repository to work in.pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(@@ -20,6 +23,7 @@ pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(pub fn internal_mcp_instructions() -> String {format!("When you create or start working on a pull request, register its URL with Macro using macro_internal.set_pull_request. \+ {SESSION_BACKLINK} \{READY_PULL_REQUEST} \Save any screenshot or screen recording meant for the user into your artifacts directory and refer to it in prose by file name only, never by a sandbox path: Macro re-hosts uploaded artifacts and cannot reach files anywhere else.")@@ -34,6 +38,7 @@ mod tests {let instructions = internal_mcp_instructions();assert!(instructions.contains("macro_internal.set_pull_request"));assert!(instructions.contains("register its URL"));+ assert!(instructions.contains(SESSION_BACKLINK));assert!(instructions.contains(READY_PULL_REQUEST));assert!(instructions.contains("artifacts directory"));}diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 8e490ee4f3..bbc278314c 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -604,11 +604,14 @@ Coding agents use `macro_internal.set_pull_request` to register an existing ornew GitHub PR with their session. Macro Internal MCP is hosted by the harnessservice at `/mcp/internal` on its egress listener, separately from workspace MCP.Cursor, sandbox, and macrod sessions receive session-scoped credentials; the-model supplies only the URL. The tool records the link, not the GitHub PR itself.+model supplies only the URL. The tool records the link, not the GitHub PR itself,+and returns the session's `/app/agent/<id>` URL.Macro Internal MCP's server instructions ask coding agents to register PRs with-it, to open them ready for review rather than as drafts, and to get CI passing-before handing off. External MCP clients get the ready-for-review rule in-Macro's MCP instructions, and in-app agents tell coding agents they dispatch. It is not prepended+it, to link the returned session URL in the PR description (the PR block reads+that link as the PR's origin), to open them ready for review rather than as+drafts, and to get CI passing before handing off. External MCP clients get the+ready-for-review rule in Macro's MCP instructions, and in-app agents tell coding+agents they dispatch. It is not prependedto individual user messages. Cursorenables automatic PR creation when a repository is selected. Its returned URLis also recorded becausediff --git a/services/agent_harness_service/src/internal_mcp.rs b/services/agent_harness_service/src/internal_mcp.rsindex 13aa2b1dd9..2d31caf0ac 100644--- a/services/agent_harness_service/src/internal_mcp.rs+++ b/services/agent_harness_service/src/internal_mcp.rs@@ -79,6 +79,8 @@ pub(super) struct InternalTools {pub(super) cognition: Option<Arc<dyn Cognition>>,pub(super) reviews: Arc<OnceLock<ReviewService>>,pub(super) gate: Arc<dyn agent_inmem::domain::tool_gate::NativeToolGate>,+ /// Macro app origin, for links back to the calling session.+ pub(super) app_url: Arc<str>,}impl ServerHandler for InternalTools {@@ -283,6 +285,11 @@ impl ServerHandler for InternalTools {service: self.service.clone(),tasks: self.tasks.clone(),session: grant.id,+ session_url: format!(+ "{}/app/agent/{}",+ self.app_url.trim_end_matches('/'),+ grant.id+ ),},RequestContext::new(acting_user.clone()),&request.name,diff --git a/services/agent_harness_service/src/internal_mcp/test.rs b/services/agent_harness_service/src/internal_mcp/test.rsindex 10e2cbeb52..eb467dcaf9 100644--- a/services/agent_harness_service/src/internal_mcp/test.rs+++ b/services/agent_harness_service/src/internal_mcp/test.rs@@ -177,6 +177,7 @@ async fn each_harness_gets_only_internal_tools_and_writes_only_its_session() {cognition: None,reviews: Arc::new(OnceLock::new()),gate: Arc::new(agent_inmem::domain::tool_gate::UngatedNativeTools),+ app_url: "https://macro.com".into(),},);assert_eq!(@@ -339,6 +340,15 @@ async fn each_harness_gets_only_internal_tools_and_writes_only_its_session() {})).await;assert!(called.get("error").is_none(), "{called}");assert_ne!(called["result"]["isError"], true, "{called}");+ let output: serde_json::Value =+ serde_json::from_str(called["result"]["content"][0]["text"].as_str().unwrap()).unwrap();+ assert_eq!(+ output,+ serde_json::json!({+ "pull_request_url": "https://github.com/org/repo/pull/1",+ "session_url": format!("https://macro.com/app/agent/{}", session.id),+ })+ );assert_eq!(repo.get(session.id).awaitdiff --git a/services/agent_harness_service/src/internal_mcp/test/code_mode.rs b/services/agent_harness_service/src/internal_mcp/test/code_mode.rsindex 702e60ffdc..a322850468 100644--- a/services/agent_harness_service/src/internal_mcp/test/code_mode.rs+++ b/services/agent_harness_service/src/internal_mcp/test/code_mode.rs@@ -101,6 +101,7 @@ async fn authenticated_mcp_runs_javascript_and_persists_source_and_result(pool:cognition: None,reviews: Arc::new(std::sync::OnceLock::new()),gate: Arc::new(agent_inmem::domain::tool_gate::UngatedNativeTools),+ app_url: "https://macro.com".into(),},);assert_eq!(diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 573e19b04c..39b49dbc66 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -769,6 +769,7 @@ async fn run() -> anyhow::Result<()> {cognition: tool_context.cognition_tool_context.service.clone(),reviews: reviews_cell.clone(),gate: owner_tool_gate.clone(),+ app_url: macro_service_urls::AppServiceUrl::new()?.as_str().into(),},);// One connector for the agent and the telemetry catalog. It pools eachdiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_privacy_check.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_privacy_check.shindex 060e076bda..80db3aac5e 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_privacy_check.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_privacy_check.sh@@ -38,9 +38,10 @@ scan() {report "$source" "phone number" "$(grep -oE '(\+[0-9]{1,3}[ .-]?)?\(?[0-9]{3}\)?[ .-][0-9]{3}[ .-][0-9]{4}' <<<"$text" || true)"report "$source" "support or chat link" "$(grep -oiE 'https?://([a-z0-9-]+\.slack\.com/(archives|client|team)|app\.slack\.com/client|app\.intercom\.(com|io)|[a-z0-9-]+\.zendesk\.com/agent|app\.frontapp\.com|discord\.com/channels|mail\.google\.com|app\.hubspot\.com|app\.usepylon\.com|app\.plain\.com|app\.crisp\.chat|secure\.helpscout\.net)[^[:space:])>]*' <<<"$text" || true)"# Links to workspace items (channels, documents, chats, emails). Tasks are- # the issue tracker and may be linked like GitHub issues.+ # the issue tracker and may be linked like GitHub issues; agent sessions are+ # the provenance coding agents link from the pull requests they open.report "$source" "Macro workspace link" "$(grep -oiE 'https?://([a-z0-9-]+\.)?macro\.com/app/[a-z-]+/[A-Za-z0-9-]+[^[:space:])>`]*' <<<"$text" \- | grep -viE '/app/tasks?/' || true)"+ | grep -viE '^https?://([a-z0-9-]+\.)?macro\.com/app/(tasks?|agent)/' || true)"# `@scope/package` names end in a slash and are not mentions.report "$source" "@mention" "$(grep -oE '(^|[[:space:](])@[A-Za-z0-9][A-Za-z0-9-]*/?' <<<"$prose" \| sed -E 's/^[[:space:](]*//' | grep -v '/$' \