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(macrod): teach agents runtime self-knowledge on their first prompt (#8991)
Wolf Mermelstein256dc9b98479
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 1774689c6a..45dde06d4c 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -22,6 +22,11 @@ pub use agent_fold::domain::model::{/// whose string value is the [`AgentSessionId`] the ACP session serves.pub const MACRO_AGENT_SESSION_META_KEY: &str = "macro.com/agentSessionId";+/// The `_meta` key on `session/new`, `session/load` and `session/resume`+/// whose string value is how the session answers permission requests+/// (`autoAccept` or `prompt`), so a runtime can tell its agent.+pub const MACRO_PERMISSION_POLICY_META_KEY: &str = "macro.com/permissionPolicy";+/// Identity of one harness participant, minted fresh at construction.////// A restarted process is a new replica: whatever the old identity claimed isdiff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rsindex 5ee7520584..e67799bd68 100644--- a/crates/agent_session/src/domain/session/session.rs+++ b/crates/agent_session/src/domain/session/session.rs@@ -23,7 +23,9 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::PROTOCOL_VERSION;use crate::domain::error::AgentSessionError;-use crate::domain::model::{AgentSessionId, MACRO_AGENT_SESSION_META_KEY};+use crate::domain::model::{+ AgentSessionId, MACRO_AGENT_SESSION_META_KEY, MACRO_PERMISSION_POLICY_META_KEY,+};use super::types::{CloseReason, Effect, Input, OutstandingPermission, PendingAction, PendingElicitation,@@ -783,6 +785,11 @@ impl<Token> SessionMachine<Token> {MACRO_AGENT_SESSION_META_KEY.to_owned(),serde_json::Value::String(self.id.to_string()),);+ let permission_policy: &'static str = self.permission_policy.into();+ meta.insert(+ MACRO_PERMISSION_POLICY_META_KEY.to_owned(),+ serde_json::Value::String(permission_policy.to_owned()),+ );meta}diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rsindex 7c842db185..4f3eb2d7c3 100644--- a/crates/agent_session/src/domain/session/tests.rs+++ b/crates/agent_session/src/domain/session/tests.rs@@ -1237,7 +1237,7 @@ fn session_new_carries_the_sessions_workspace() {}#[test]-fn session_new_names_the_macro_session_in_meta() {+fn session_new_names_the_macro_session_and_permission_policy_in_meta() {let mut machine = SessionMachine::new(AgentSessionId::TEST_A,"/home/operator/code".to_owned(),@@ -1247,7 +1247,7 @@ fn session_new_names_the_macro_session_in_meta() {machine.handle(acp_ready());let effects = machine.handle(initialized());- let named: Vec<String> = effects+ let named: Vec<(String, String)> = effects.iter().filter_map(|effect| match effect {Effect::Send {@@ -1255,14 +1255,23 @@ fn session_new_names_the_macro_session_in_meta() {..} if request.method.as_ref() == "session/new" => {let params = request.params.clone()?.into_value();- params["_meta"][crate::domain::model::MACRO_AGENT_SESSION_META_KEY]- .as_str()- .map(str::to_owned)+ let meta = ¶ms["_meta"];+ Some((+ meta[crate::domain::model::MACRO_AGENT_SESSION_META_KEY]+ .as_str()?+ .to_owned(),+ meta[crate::domain::model::MACRO_PERMISSION_POLICY_META_KEY]+ .as_str()?+ .to_owned(),+ ))}_ => None,}).collect();- assert_eq!(named, [AgentSessionId::TEST_A.to_string()]);+ assert_eq!(+ named,+ [(AgentSessionId::TEST_A.to_string(), "autoAccept".to_owned())]+ );}#[test]@@ -2004,7 +2013,10 @@ fn new_mcp_servers_resume_a_live_session_before_its_next_prompt() {"url": "https://egress.example.com/mcp/linear","headers": [],}],- "_meta": { "macro.com/agentSessionId": AgentSessionId::TEST_A.to_string() },+ "_meta": {+ "macro.com/agentSessionId": AgentSessionId::TEST_A.to_string(),+ "macro.com/permissionPolicy": "autoAccept",+ },})));assert_eq!(machine.status(), RuntimeStatus::Handshaking);diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rsindex 7b84c1d6bc..8ba7860f1e 100644--- a/crates/agent_session/src/domain/session/types.rs+++ b/crates/agent_session/src/domain/session/types.rs@@ -18,7 +18,8 @@ pub(super) struct PendingAction<Token> {}/// How a connection answers the agent's `session/request_permission`.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, strum::IntoStaticStr)]+#[strum(serialize_all = "camelCase")]pub enum PermissionPolicy {/// Approve the broadest allow option the moment the request arrives./// Right for runtimes in sandboxes this deployment owns, where nothingdiff --git a/crates/coding_agent_worker/AGENTS.md b/crates/coding_agent_worker/AGENTS.mdindex deadaa660a..e3d988b192 100644--- a/crates/coding_agent_worker/AGENTS.md+++ b/crates/coding_agent_worker/AGENTS.md@@ -14,6 +14,10 @@ the local ACP process (Claude Code, Codex, ...), and drives native`config.example.toml`, `default.macrod.toml`).- `src/daemon.rs` + `src/runtime.rs`: the serving core — persistent harnessservice connection, ACP process bridge, start/stop/restart on re-pair.+- `src/self_knowledge.rs`: the `<macrod-runtime>` section the bridge+ (`src/harness.rs`) prefixes to each new session's first prompt — macrod+ version, workspace, forwarded MCP servers, permission bypass, listing only+ what the session has. General Macro guidance stays in the `SelfKnowledge` tool.- `src/trigger.rs` + `src/dispatch.rs`: agent-trigger broker events → sessioncreate/dial/prompt against the live harness service.- `src/tui.rs` (`src/tui/`): the control panel itself (registration, agents,diff --git a/crates/coding_agent_worker/src/harness.rs b/crates/coding_agent_worker/src/harness.rsindex 297d919ae4..53a8b608f5 100644--- a/crates/coding_agent_worker/src/harness.rs+++ b/crates/coding_agent_worker/src/harness.rs@@ -8,11 +8,16 @@ use std::time::Duration;use crate::config::Harness;use crate::outbound::acp_probe::{ProbeError, ProbeSubprocess, probe_subprocess};use crate::outbound::acp_process::AcpProcess;-use agent_client_protocol::{Client, ConnectTo, LineDirection};+use crate::self_knowledge::SelfKnowledge;+use agent_client_protocol::{+ Channel as AcpChannel, Client, ConnectTo, LineDirection, TransportFrame,+};use agent_runtime_protocol::domain::connection::{ConnectionError, ModelProbeHandler, RuntimeChannel, RuntimeConnection,};use agent_runtime_protocol::domain::schema::v0::SystemEvent;+use futures::StreamExt as _;+use tokio_util::task::AbortOnDropHandle;#[cfg(test)]mod test;@@ -57,12 +62,15 @@ pub async fn bridge(}});+ let (agent_side, relay_side) = AcpChannel::duplex();+ let _relay = AbortOnDropHandle::new(tokio::spawn(relay(acp, relay_side)));+runtime.system_event(SystemEvent::AcpReady).map_err(BridgeError::Announce)?;let outcome = tokio::select! {- outcome = ConnectTo::<Client>::connect_to(agent, acp) => outcome,+ outcome = ConnectTo::<Client>::connect_to(agent, agent_side) => outcome,() = runtime.closed() => Ok(()),};@@ -75,6 +83,51 @@ pub async fn bridge(outcome.map_err(|error| BridgeError::Harness(error.to_string()))}+/// Pump frames between the service and the agent, teaching each new+/// session's agent about this runtime on its first prompt. Ends when either+/// side closes, which closes the other.+async fn relay(mut service: AcpChannel, mut agent: AcpChannel) {+ let mut self_knowledge = SelfKnowledge::default();+ loop {+ tokio::select! {+ frame = service.rx.next() => {+ let Some(frame) = frame else { break };+ let frame = match frame {+ TransportFrame::Single(message) => {+ TransportFrame::Single(teach(&mut self_knowledge, message))+ }+ other => other,+ };+ if agent.tx.unbounded_send(frame).is_err() {+ break;+ }+ }+ frame = agent.rx.next() => {+ let Some(frame) = frame else { break };+ if let TransportFrame::Single(message) = &frame+ && let Ok(message) = serde_json::to_value(message)+ {+ self_knowledge.inbound(&message);+ }+ if service.tx.unbounded_send(frame).is_err() {+ break;+ }+ }+ }+ }+}++fn teach(+ self_knowledge: &mut SelfKnowledge,+ message: agent_client_protocol::RawJsonRpcMessage,+) -> agent_client_protocol::RawJsonRpcMessage {+ let Ok(mut value) = serde_json::to_value(&message) else {+ return message;+ };+ self_knowledge.outbound(&mut value);+ serde_json::from_value(value).unwrap_or(message)+}+fn probe_process(harness: &Harness, cwd: &Path) -> ProbeSubprocess {ProbeSubprocess {command: harness.command.clone().into(),diff --git a/crates/coding_agent_worker/src/harness/test.rs b/crates/coding_agent_worker/src/harness/test.rsindex b5e556bcfe..82c3762736 100644--- a/crates/coding_agent_worker/src/harness/test.rs+++ b/crates/coding_agent_worker/src/harness/test.rs@@ -92,3 +92,66 @@ async fn model_probe_process_failures_are_safely_redacted() {assert_eq!(error, "the ACP model probe process failed");assert!(!error.contains("secret-argument"));}++#[tokio::test]+async fn relay_teaches_a_new_session_on_its_first_prompt() {+ let (mut service, service_side) = AcpChannel::duplex();+ let (agent_side, mut agent) = AcpChannel::duplex();+ let _relay = tokio::spawn(relay(service_side, agent_side));+ let frame = |value: serde_json::Value| {+ TransportFrame::Single(serde_json::from_value(value).expect("a valid JSON-RPC message"))+ };+ let received = |frame: TransportFrame| match frame {+ TransportFrame::Single(message) => {+ serde_json::to_value(message).expect("a serializable message")+ }+ other => panic!("expected one message, got {other:?}"),+ };++ service+ .tx+ .unbounded_send(frame(serde_json::json!({+ "jsonrpc": "2.0", "id": 1, "method": "session/new",+ "params": {"cwd": "/home/operator/code", "mcpServers": []}+ })))+ .expect("the relay is running");+ agent+ .rx+ .next()+ .await+ .expect("session/new reaches the agent");+ agent+ .tx+ .unbounded_send(frame(serde_json::json!({+ "jsonrpc": "2.0", "id": 1, "result": {"sessionId": "acp-1"}+ })))+ .expect("the relay is running");+ service+ .rx+ .next()+ .await+ .expect("the answer reaches the service");+ service+ .tx+ .unbounded_send(frame(serde_json::json!({+ "jsonrpc": "2.0", "id": 2, "method": "session/prompt",+ "params": {"sessionId": "acp-1", "prompt": [{"type": "text", "text": "hello"}]}+ })))+ .expect("the relay is running");++ let prompt = received(agent.rx.next().await.expect("the prompt reaches the agent"));+ let blocks = prompt["params"]["prompt"]+ .as_array()+ .expect("the prompt is a block list");+ assert_eq!(blocks.len(), 2);+ assert!(+ blocks[0]["text"]+ .as_str()+ .is_some_and(|text| text.starts_with("<macrod-runtime>")),+ "got {prompt}"+ );+ assert_eq!(+ blocks[1],+ serde_json::json!({"type": "text", "text": "hello"})+ );+}diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rsindex c176b7a150..099be4dc5f 100644--- a/crates/coding_agent_worker/src/main.rs+++ b/crates/coding_agent_worker/src/main.rs@@ -25,6 +25,7 @@ mod herdr;mod outbound;mod repository;mod runtime;+mod self_knowledge;mod service;mod trigger;mod tui;diff --git a/crates/coding_agent_worker/src/self_knowledge.rs b/crates/coding_agent_worker/src/self_knowledge.rsnew file mode 100644index 0000000000..f4f43777e0--- /dev/null+++ b/crates/coding_agent_worker/src/self_knowledge.rs@@ -0,0 +1,152 @@+//! Tells each new session's agent what macrod is and what it can do from+//! here. The first `session/prompt` of a session the agent created gains a+//! leading text block describing this runtime; loaded and resumed sessions+//! already carry it from their first turn. General Macro guidance stays in+//! the Macro MCP server's `SelfKnowledge` tool.++use std::collections::HashMap;++use agent_session::domain::model::MACRO_PERMISSION_POLICY_META_KEY;+use serde_json::Value;++#[cfg(test)]+mod test;++/// What one session was opened with, as far as its agent should know.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct SessionFacts {+ /// The directory the agent works in.+ pub(crate) workspace: String,+ /// Names of the MCP servers Macro forwarded to this session.+ pub(crate) mcp_servers: Vec<String>,+ /// Whether Macro approves the agent's tool permission requests itself.+ pub(crate) permission_bypass: bool,+}++/// Correlates `session/new` with its answer, then rewrites that session's+/// first prompt. The harness serves every session over one process, so+/// sessions are followed by request id until the agent names them.+#[derive(Debug, Default)]+pub(crate) struct SelfKnowledge {+ /// `session/new` requests awaiting their answer, by request id.+ opening: HashMap<String, SessionFacts>,+ /// Sessions created but not yet prompted, by ACP session id.+ unprompted: HashMap<String, SessionFacts>,+}++impl SelfKnowledge {+ /// Observe a message on its way to the agent, prefixing the runtime+ /// section to a new session's first prompt.+ pub(crate) fn outbound(&mut self, message: &mut Value) {+ match message.get("method").and_then(Value::as_str) {+ Some("session/new") => {+ let id = message+ .get("id")+ .filter(|id| !id.is_null())+ .map(Value::to_string);+ if let (Some(id), Some(params)) = (id, message.get("params")) {+ self.opening.insert(id, session_facts(params));+ }+ }+ Some("session/prompt") => {+ let Some(params) = message.get_mut("params") else {+ return;+ };+ let Some(facts) = params+ .get("sessionId")+ .and_then(Value::as_str)+ .and_then(|session| self.unprompted.remove(session))+ else {+ return;+ };+ if let Some(Value::Array(prompt)) = params.get_mut("prompt") {+ prompt.insert(+ 0,+ serde_json::json!({"type": "text", "text": render(&facts)}),+ );+ }+ }+ _ => {}+ }+ }++ /// Observe a message from the agent, learning which session a+ /// `session/new` answer created.+ pub(crate) fn inbound(&mut self, message: &Value) {+ if message.get("method").is_some() {+ return;+ }+ let Some(id) = message+ .get("id")+ .filter(|id| !id.is_null())+ .map(Value::to_string)+ else {+ return;+ };+ let Some(facts) = self.opening.remove(&id) else {+ return;+ };+ if let Some(session) = message.pointer("/result/sessionId").and_then(Value::as_str) {+ self.unprompted.insert(session.to_owned(), facts);+ }+ }+}++fn session_facts(params: &Value) -> SessionFacts {+ SessionFacts {+ workspace: params+ .get("cwd")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_owned(),+ mcp_servers: params+ .get("mcpServers")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|server| server.get("name").and_then(Value::as_str))+ .map(str::to_owned)+ .collect(),+ permission_bypass: params+ .pointer("/_meta")+ .and_then(|meta| meta.get(MACRO_PERMISSION_POLICY_META_KEY))+ .and_then(Value::as_str)+ == Some("autoAccept"),+ }+}++/// The runtime section, listing only what this session actually has.+pub(crate) fn render(facts: &SessionFacts) -> String {+ let mut lines = vec![+ "<macrod-runtime>".to_owned(),+ format!(+ "You are running through macrod {}, the Macro agent daemon on the operator's own {} machine. \+ Macro users reach you from Macro (channels, documents, agent sessions); each prompt arrives \+ through macrod, and your replies stream back to Macro.",+ env!("CARGO_PKG_VERSION"),+ std::env::consts::OS,+ ),+ ];+ if !facts.workspace.is_empty() {+ lines.push(format!(+ "- Workspace: you work in `{}` on the operator's machine. Changes there are real.",+ facts.workspace+ ));+ }+ if !facts.mcp_servers.is_empty() {+ lines.push(format!(+ "- MCP servers forwarded from Macro: {}. Use them to read and act in the Macro workspace; \+ for questions about Macro itself, call its SelfKnowledge tool.",+ facts.mcp_servers.join(", ")+ ));+ }+ if facts.permission_bypass {+ lines.push(+ "- Permission bypass: Macro approves your tool permission requests automatically; \+ no one is asked before you run commands or edit files."+ .to_owned(),+ );+ }+ lines.push("</macrod-runtime>".to_owned());+ lines.join("\n")+}diff --git a/crates/coding_agent_worker/src/self_knowledge/test.rs b/crates/coding_agent_worker/src/self_knowledge/test.rsnew file mode 100644index 0000000000..441fbc5ab8--- /dev/null+++ b/crates/coding_agent_worker/src/self_knowledge/test.rs@@ -0,0 +1,104 @@+use super::*;+use serde_json::json;++#[test]+fn renders_every_enabled_capability() {+ let section = render(&SessionFacts {+ workspace: "/home/operator/code".to_owned(),+ mcp_servers: vec!["macro".to_owned(), "linear".to_owned()],+ permission_bypass: true,+ });++ assert_eq!(+ section,+ format!(+ "<macrod-runtime>\n\+ You are running through macrod {}, the Macro agent daemon on the operator's own {} machine. \+ Macro users reach you from Macro (channels, documents, agent sessions); each prompt arrives \+ through macrod, and your replies stream back to Macro.\n\+ - Workspace: you work in `/home/operator/code` on the operator's machine. Changes there are real.\n\+ - MCP servers forwarded from Macro: macro, linear. Use them to read and act in the Macro workspace; \+ for questions about Macro itself, call its SelfKnowledge tool.\n\+ - Permission bypass: Macro approves your tool permission requests automatically; \+ no one is asked before you run commands or edit files.\n\+ </macrod-runtime>",+ env!("CARGO_PKG_VERSION"),+ std::env::consts::OS,+ )+ );+}++#[test]+fn leaves_out_capabilities_the_session_does_not_have() {+ let section = render(&SessionFacts {+ workspace: "/home/operator/code".to_owned(),+ mcp_servers: Vec::new(),+ permission_bypass: false,+ });++ assert!(section.contains("Workspace: you work in `/home/operator/code`"));+ assert!(!section.contains("MCP servers"));+ assert!(!section.contains("Permission bypass"));+}++#[test]+fn only_a_new_sessions_first_prompt_carries_the_runtime_section() {+ let mut self_knowledge = SelfKnowledge::default();+ let mut open = json!({+ "jsonrpc": "2.0", "id": 1, "method": "session/new",+ "params": {+ "cwd": "/home/operator/code",+ "mcpServers": [{"type": "http", "name": "macro", "url": "https://example.test/mcp", "headers": []}],+ "_meta": {"macro.com/permissionPolicy": "autoAccept"}+ }+ });+ self_knowledge.outbound(&mut open);+ self_knowledge.inbound(&json!({"jsonrpc": "2.0", "id": 1, "result": {"sessionId": "acp-1"}}));++ let mut first = json!({+ "jsonrpc": "2.0", "id": 2, "method": "session/prompt",+ "params": {"sessionId": "acp-1", "prompt": [{"type": "text", "text": "hello"}]}+ });+ self_knowledge.outbound(&mut first);+ let mut second = json!({+ "jsonrpc": "2.0", "id": 3, "method": "session/prompt",+ "params": {"sessionId": "acp-1", "prompt": [{"type": "text", "text": "again"}]}+ });+ self_knowledge.outbound(&mut second);++ let expected = render(&SessionFacts {+ workspace: "/home/operator/code".to_owned(),+ mcp_servers: vec!["macro".to_owned()],+ permission_bypass: true,+ });+ assert_eq!(+ first["params"]["prompt"],+ json!([{"type": "text", "text": expected}, {"type": "text", "text": "hello"}])+ );+ assert_eq!(+ second["params"]["prompt"],+ json!([{"type": "text", "text": "again"}])+ );+}++#[test]+fn a_loaded_session_is_not_taught_again() {+ let mut self_knowledge = SelfKnowledge::default();+ let mut load = json!({+ "jsonrpc": "2.0", "id": 1, "method": "session/load",+ "params": {"sessionId": "acp-1", "cwd": "/home/operator/code", "mcpServers": []}+ });+ self_knowledge.outbound(&mut load);+ self_knowledge.inbound(&json!({"jsonrpc": "2.0", "id": 1, "result": {}}));++ let mut prompt = json!({+ "jsonrpc": "2.0", "id": 2, "method": "session/prompt",+ "params": {"sessionId": "acp-1", "prompt": [{"type": "text", "text": "hello"}]}+ });+ self_knowledge.outbound(&mut prompt);++ assert_eq!(+ prompt["params"]["prompt"],+ json!([{"type": "text", "text": "hello"}])+ );+}