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
Tell Macro agents their name and @handle in the system prompt (#6354)
Eric Hayescbe69c01591d
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.tsindex 8ea8761480..c97934f20b 100644--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts@@ -65,7 +65,10 @@ vi.mock('@service-agent-harness/client', () => ({get: vi.fn(() => worker.getSession()),getLog: vi.fn(async () => ({isErr: () => false,- value: { bot: { id: 'bot', name: 'Agent' }, entries: [] },+ value: {+ bot: { id: 'bot', name: 'Agent', handle: 'agent' },+ entries: [],+ },})),},}));diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.tsindex 47eebbf217..c77593bd75 100644--- a/apps/web/src/features/block-agent/debug/replay/driver.ts+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts@@ -24,7 +24,11 @@ import { err, ok } from 'neverthrow';import { type Accessor, createSignal } from 'solid-js';import type { ReplayBackend } from './interceptor';-export const REPLAY_BOT: SessionBot = { id: 'replay-bot', name: 'Replay' };+export const REPLAY_BOT: SessionBot = {+ id: 'replay-bot',+ name: 'Replay',+ handle: 'replay',+};export const REPLAY_OWNER = 'macro|[email protected]';/** POST ack → frame in the log, same ordering the harness produces. */diff --git a/apps/web/src/lib/queries/agent-session/session-fold.test.ts b/apps/web/src/lib/queries/agent-session/session-fold.test.tsindex 0f772f9115..8ceb798e30 100644--- a/apps/web/src/lib/queries/agent-session/session-fold.test.ts+++ b/apps/web/src/lib/queries/agent-session/session-fold.test.ts@@ -39,7 +39,7 @@ function event(session: string, n: number) {return { agentSessionId: session, ...frame(n) };}-const bot = { id: 'bot-id', name: 'Agent' };+const bot = { id: 'bot-id', name: 'Agent', handle: 'agent' };const message = { agentSessionId: 'session-a' } as FoldedMessage;const metadata = {model: null,diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionBot.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionBot.tsindex 2b357f4dc5..70557a17e5 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionBot.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sessionBot.ts@@ -14,6 +14,8 @@ import type { SessionBotAvatarUrl } from './sessionBotAvatarUrl';export interface SessionBot {/** Avatar, when it has one. */avatarUrl?: SessionBotAvatarUrl;+ /** Stable `@` handle, without a leading `@`. */+ handle: string;/** The bot's id. A message it sent has `"bot|{id}"` as its sender. */id: BotId;/** Display name. */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.jsonindex 708a66c49e..ce354856a0 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@@ -1753,12 +1753,16 @@"SessionBot": {"type": "object","description": "The agent behind a session, as much of it as rendering a message needs.",- "required": ["id", "name"],+ "required": ["id", "name", "handle"],"properties": {"avatarUrl": {"type": ["string", "null"],"description": "Avatar, when it has one."},+ "handle": {+ "type": "string",+ "description": "Stable `@` handle, without a leading `@`."+ },"id": {"$ref": "#/components/schemas/BotId","description": "The bot's id. A message it sent has `\"bot|{id}\"` as its sender."diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rsindex 9166dd5078..ddc973dd7f 100644--- a/crates/agent_inmem/src/domain/agent.rs+++ b/crates/agent_inmem/src/domain/agent.rs@@ -39,7 +39,7 @@ use async_trait::async_trait;use macro_user_id::user_id::MacroUserIdStr;use tokio_util::sync::CancellationToken;-use crate::domain::engine::{TurnEngine, TurnRequest};+use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};use crate::domain::mcp::{DynMcpToolConnector, dialable_servers};use crate::domain::session::{HistoryEntry, SessionStore, messages_for_turn};use crate::domain::user_input::{@@ -91,6 +91,8 @@ struct TurnInput {messages: Vec<ChatMessage>,/// Model the turn runs on.model: String,+ /// Who this agent is, for the engine's system prompt.+ identity: Option<AgentIdentity>,/// The session's instructions, for the engine's system prompt.instructions: Option<String>,}@@ -198,11 +200,13 @@ impl AgentState {|| TurnInput {messages: messages_for_turn(&[], prompt),model: String::new(),+ identity: None,instructions: None,},|state| TurnInput {messages: messages_for_turn(&state.history, prompt),model: state.model.clone(),+ identity: state.identity.clone(),instructions: state.instructions.clone(),},)@@ -658,6 +662,7 @@ async fn run_turn(let TurnInput {messages,model,+ identity,instructions,} = state.turn_input(&prompt);let awaiting = Arc::new(AwaitingUser::default());@@ -665,6 +670,7 @@ async fn run_turn(let mut parts = state.engine.run_turn(TurnRequest {owner: state.owner.clone(),model,+ identity,instructions,messages,mcp_tools: state.current_mcp_tools(),diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rsindex 81aca7fba0..2cfa4ba279 100644--- a/crates/agent_inmem/src/domain/engine.rs+++ b/crates/agent_inmem/src/domain/engine.rs@@ -12,6 +12,15 @@ use tokio_util::sync::CancellationToken;use super::user_input::SharedUserInputRequester;+/// The agent's display name and `@` handle, for the turn's system prompt.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AgentIdentity {+ /// Display name, e.g. `Grunk`.+ pub name: String,+ /// Stable `@` handle without a leading `@`, e.g. `grunk`.+ pub handle: String,+}+/// Everything one conversational turn needs.pub struct TurnRequest {/// The user the turn acts on behalf of. Tools run with their identity and@@ -20,6 +29,10 @@ pub struct TurnRequest {/// Model id the turn runs on. Unknown ids fall back to the loop's/// default model rather than failing the turn.pub model: String,+ /// Who this agent is. Folded into every turn's system prompt so the+ /// model can answer "who are you" even when the session has no+ /// instructions. `None` leaves the standing prompt unnamed.+ pub identity: Option<AgentIdentity>,/// The session's instructions, appended to the engine's own system/// prompt. `None` runs the engine's default prompt unchanged.pub instructions: Option<String>,diff --git a/crates/agent_inmem/src/domain/session.rs b/crates/agent_inmem/src/domain/session.rsindex 2f8431bd6e..8e0bbe9c2e 100644--- a/crates/agent_inmem/src/domain/session.rs+++ b/crates/agent_inmem/src/domain/session.rs@@ -10,6 +10,8 @@ use agent_client_protocol::schema::v1::SessionId;use agent_session::domain::model::AgentSessionId;use dashmap::DashMap;+use super::engine::AgentIdentity;+/// One entry of the conversation, in the shape/// [`agent::to_rig_messages`] round-trips.#[derive(Debug, Clone)]@@ -27,6 +29,8 @@ pub struct SessionState {pub acp_session_id: Option<SessionId>,/// Model id turns run on; `session/set_config_option` moves it.pub model: String,+ /// Who this agent is, snapshotted from the session's bot at attach.+ pub identity: Option<AgentIdentity>,/// Instructions every turn runs under, snapshotted from the session row/// at attach. Nothing moves them: they are the session's system prompt,/// and a conversation whose system prompt changed halfway is one the@@ -43,6 +47,7 @@ impl SessionState {Self {acp_session_id: None,model,+ identity: None,instructions: None,history: Vec::new(),}diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rsindex 31cc07a857..c43bfe4ceb 100644--- a/crates/agent_inmem/src/outbound/manager.rs+++ b/crates/agent_inmem/src/outbound/manager.rs@@ -17,7 +17,7 @@ use dashmap::DashMap;use macro_user_id::user_id::MacroUserIdStr;use crate::domain::agent::{AgentState, serve};-use crate::domain::engine::TurnEngine;+use crate::domain::engine::{AgentIdentity, TurnEngine};use crate::domain::mcp::DynMcpToolConnector;use crate::domain::replay::{FrameSource, replay_history};use crate::domain::session::{SessionState, SessionStore};@@ -34,6 +34,10 @@ pub struct SessionFacts {pub owner: MacroUserIdStr<'static>,/// Model id stamped on the session row.pub model: String,+ /// The bot's display name and `@` handle, folded into every turn's+ /// system prompt so the model knows who it is. Looked up from the+ /// session's bot at attach; `None` only in tests that do not name one.+ pub identity: Option<AgentIdentity>,/// Instructions stamped on the session row, folded into every turn's/// system prompt. Immutable for the session's life, so a reattach that/// finds a live conversation leaves what is stored alone.@@ -139,6 +143,7 @@ impl InMemAgentManager {self.store.entry(facts.id).or_insert_with(|| SessionState {acp_session_id: facts.acp_session_id.clone(),model: facts.model.clone(),+ identity: facts.identity.clone(),instructions: facts.instructions.clone(),history,});diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rsindex 11f308c6b5..c333fcee54 100644--- a/crates/agent_inmem/src/outbound/manager/test.rs+++ b/crates/agent_inmem/src/outbound/manager/test.rs@@ -19,6 +19,7 @@ use bot_id::BotId;use macro_user_id::user_id::MacroUserIdStr;use super::*;+use crate::domain::engine::AgentIdentity;use crate::outbound::log_frames::LogFrameSource;use crate::testing::ScriptedEngine;use agent_session::domain::model::ReplicaId;@@ -102,6 +103,7 @@ fn facts(id: AgentSessionId) -> SessionFacts {id,owner: owner(),model: "test-model".to_owned(),+ identity: None,instructions: None,acp_session_id: None,}@@ -115,6 +117,16 @@ fn facts_with_instructions(id: AgentSessionId, instructions: &str) -> SessionFac}}+fn facts_with_identity(id: AgentSessionId, name: &str, handle: &str) -> SessionFacts {+ SessionFacts {+ identity: Some(AgentIdentity {+ name: name.to_owned(),+ handle: handle.to_owned(),+ }),+ ..facts(id)+ }+}+/// Frames the log holds, flattened to JSON strings for loose assertions.async fn logged_frames(repo: &InMemoryAgentSessionRepo, id: AgentSessionId) -> Vec<String> {repo.list_by_session(id)@@ -554,6 +566,85 @@ async fn a_session_without_instructions_hands_the_engine_none() {assert_eq!(engine.requests()[0].instructions, None);}+/// The session's bot identity reaches every turn, including after a reattach+/// that replaces the agent task. A named agent with no instructions still+/// knows who it is.+#[tokio::test]+async fn identity_reaches_every_turn_including_after_a_reattach() {+ let repo = InMemoryAgentSessionRepo::new();+ let sessions = AgentSessionServiceImpl::new(+ repo.clone(),+ FoldedMessageService::new(repo.clone()),+ NoOpRealtime,+ NoOpAgentSessionNameGenerator,+ Arc::new(NoOpTurnObserver),+ Arc::new(NoopLifecyclePublisher),+ ReplicaId::mint(),+ );++ let id = AgentSessionId::new();+ sessions+ .create_session(CreateAgentSessionParams {+ id,+ owner_id: owner(),+ bot_id: BotId::TEST_A,+ thread_id: None,+ originating_message_id: None,+ model: "test-model".to_owned(),+ harness: "macro-inmem".to_owned(),+ repo_url: None,+ workspace: "/workspace".to_owned(),+ sandbox_size: agent_session::domain::model::SandboxSize::Default,+ instructions: None,+ mcp_servers: Default::default(),+ egress_token_hash: None,+ })+ .await+ .expect("the session row should create");++ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(+ "i am grunk".to_owned(),+ )]));+ let manager = manager(&repo, Arc::clone(&engine));++ for prompt in ["who are you", "say your handle"] {+ attach_retrying(+ &sessions,+ id,+ &manager,+ facts_with_identity(id, "Grunk", "grunk"),+ )+ .await;+ sessions+ .send_action(+ id,+ Some(owner()),+ AgentAction::prompt(prompt),+ AgentActionId::mint(),+ )+ .await+ .expect("the prompt should send");+ await_turns(&engine, prompt).await;+ }++ let identities: Vec<Option<(String, String)>> = engine+ .requests()+ .into_iter()+ .map(|turn| {+ turn.identity+ .map(|identity| (identity.name, identity.handle))+ })+ .collect();+ assert_eq!(+ identities,+ vec![+ Some(("Grunk".to_owned(), "grunk".to_owned())),+ Some(("Grunk".to_owned(), "grunk".to_owned())),+ ],+ "both turns run as the named agent"+ );+}+/// The egress token has no container environment to live in here, so the/// manager keeps what spawn handed it: a resume finds it, teardown forgets it.#[tokio::test]diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rsindex 867d8aef49..8398a6e618 100644--- a/crates/agent_inmem/src/outbound/rig_engine/test.rs+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs@@ -1,4 +1,5 @@use super::*;+use crate::domain::engine::AgentIdentity;/// A stand-in for the toolset prompt, short enough to assert on positionally.const TOOLS: &str = "TOOLS";@@ -22,11 +23,11 @@ fn ask_user_is_only_advertised_when_the_client_supports_it() {#[test]fn instructions_are_a_delimited_section_after_the_standing_prompt() {- let prompt = system_prompt(&TOOLS, Some("be terse"), None);+ let prompt = system_prompt(&TOOLS, None, Some("be terse"), None);assert!(prompt.starts_with(&prompt::agent_session::PROMPT.to_string()),- "the session preamble comes first"+ "the session preamble comes first when the agent is unnamed");assert!(prompt.contains(&format!(@@ -37,12 +38,31 @@ fn instructions_are_a_delimited_section_after_the_standing_prompt() {assert!(prompt.ends_with("\n<session_instructions>\nbe terse\n</session_instructions>"));}+/// A named agent is told who it is before anything else, even when it has+/// no session instructions — otherwise "who are you" has nothing to go on.+#[test]+fn identity_precedes_the_standing_prompt_and_does_not_need_instructions() {+ let identity = AgentIdentity {+ name: "Grunk".to_owned(),+ handle: "grunk".to_owned(),+ };+ let prompt = system_prompt(&TOOLS, Some(&identity), None, None);+ let identity_section = prompt::agent_identity::render("Grunk", "grunk");++ assert!(+ prompt.starts_with(&identity_section),+ "identity is the first thing the model reads"+ );+ assert!(prompt.contains(&prompt::agent_session::PROMPT.to_string()));+ assert!(!prompt.contains("session_instructions"));+}+/// The order is the contract, not an accident: instructions qualify the/// standing prompt, and memory comes last so a remembered fact is never read/// as an instruction.#[test]fn memory_follows_instructions_rather_than_preceding_them() {- let prompt = system_prompt(&TOOLS, Some("be terse"), Some("prefers Rust"));+ let prompt = system_prompt(&TOOLS, None, Some("be terse"), Some("prefers Rust"));let instructions = prompt.find("<session_instructions>")@@ -57,7 +77,7 @@ fn memory_follows_instructions_rather_than_preceding_them() {/// model would have to interpret.#[test]fn no_instructions_means_no_section() {- let prompt = system_prompt(&TOOLS, None, Some("prefers Rust"));+ let prompt = system_prompt(&TOOLS, None, None, Some("prefers Rust"));assert!(!prompt.contains("session_instructions"));assert!(prompt.contains("<user_memory>\nprefers Rust\n</user_memory>"));@@ -67,7 +87,7 @@ fn no_instructions_means_no_section() {/// not become a blank delimited section.#[test]fn empty_instructions_add_no_section() {- let prompt = system_prompt(&TOOLS, Some(""), None);+ let prompt = system_prompt(&TOOLS, None, Some(""), None);assert!(!prompt.contains("session_instructions"));}diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rsindex 29928df330..80f3bf034d 100644--- a/crates/agent_inmem/src/rig_engine.rs+++ b/crates/agent_inmem/src/rig_engine.rs@@ -3,9 +3,10 @@//!//! Consumption mirrors the scheduled-action executor//! (`services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs`):-//! the full static toolset, the agent-session preamble, the static Macro-//! prompt (immediately before any session instructions), and the owner's-//! memory, with usage recorded per turn against the session owner.+//! the full static toolset, the agent's name and handle, the agent-session+//! preamble, the static Macro prompt (immediately before any session+//! instructions), and the owner's memory, with usage recorded per turn+//! against the session owner.//!//! User tools (`SendEmail`, `CreateCalendarEvent`) are the chat host's//! deferring ones, finished inside the turn: the turn's [`TurnRequest`]@@ -35,7 +36,7 @@ use memory::outbound::pg_memory_repo::PgMemoryRepo;use sqlx::PgPool;use tokio::sync::mpsc;-use crate::domain::engine::{TurnEngine, TurnRequest};+use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};use crate::inbound::ask_user::{AskUser, AskUserContext};#[cfg(test)]@@ -119,6 +120,7 @@ async fn drive_turn(let TurnRequest {owner,model,+ identity,instructions,messages,mcp_tools,@@ -134,6 +136,7 @@ async fn drive_turn(let user_memory = fetch_user_memory(&db, &base_context, &owner).await;let system_prompt = system_prompt(&tools.prompt,+ identity.as_ref(),instructions.as_deref(),user_memory.as_deref(),);@@ -205,21 +208,34 @@ async fn drive_turn(result}-/// The turn's system prompt: the agent-session preamble, the static Macro-/// prompt (how to use the product: mentions, tools, terminology), then the-/// session's own instructions and the owner's memory when there are any.+/// The turn's system prompt: the agent's identity, the agent-session+/// preamble, the static Macro prompt (how to use the product: mentions,+/// tools, terminology), then the session's own instructions and the owner's+/// memory when there are any.///-/// The static Macro prompt sits immediately before `<session_instructions>`-/// so it is the preamble the model reads as it takes in the caller's word —-/// the same reason DCS puts `additional_instructions` after the standing-/// prompt. Memory stays last so a remembered fact is never read as an-/// instruction.+/// Identity comes first so a named agent (even one with no instructions)+/// knows who it is before reading anything else. The static Macro prompt+/// sits immediately before `<session_instructions>` so it is the preamble+/// the model reads as it takes in the caller's word — the same reason DCS+/// puts `additional_instructions` after the standing prompt. Memory stays+/// last so a remembered fact is never read as an instruction.fn system_prompt(tools_prompt: &impl std::fmt::Display,+ identity: Option<&AgentIdentity>,instructions: Option<&str>,user_memory: Option<&str>,) -> String {- let mut prompt = format!("{}\n{}", prompt::agent_session::PROMPT, tools_prompt);+ let mut prompt = String::new();+ if let Some(identity) = identity {+ prompt.push_str(&prompt::agent_identity::render(+ &identity.name,+ &identity.handle,+ ));+ prompt.push('\n');+ }+ prompt.push_str(&prompt::agent_session::PROMPT.to_string());+ prompt.push('\n');+ prompt.push_str(&tools_prompt.to_string());// Blank instructions are "none" stated clumsily. A delimited section with// nothing in it is worse than no section: the model has to decide what an// empty instruction means.diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rsindex c07856570a..9be5142e55 100644--- a/crates/agent_inmem/src/testing.rs+++ b/crates/agent_inmem/src/testing.rs@@ -3,7 +3,7 @@use agent::{AgentError, StreamPart};use tokio::sync::mpsc;-use crate::domain::engine::{TurnEngine, TurnRequest};+use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};/// Models advertised by shared test engines.pub(crate) const TEST_MODELS: &[&str] = &["test-model", "other-model"];@@ -24,6 +24,8 @@ pub(crate) struct RecordedTurn {pub(crate) messages: Vec<String>,/// The session's instructions, as handed to the engine.pub(crate) instructions: Option<String>,+ /// Who the agent is, as handed to the engine.+ pub(crate) identity: Option<AgentIdentity>,}impl ScriptedEngine {@@ -56,6 +58,7 @@ impl TurnEngine for ScriptedEngine {.map(|message| message.content.message_text_with_tools()).collect(),instructions: request.instructions.clone(),+ identity: request.identity.clone(),});let (parts, receiver) = mpsc::channel(64);let script = self.script.clone();diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 441eea1a7e..3602b1a334 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -287,6 +287,8 @@ pub struct SessionBot {pub id: BotId,/// Display name.pub name: String,+ /// Stable `@` handle, without a leading `@`.+ pub handle: String,/// Avatar, when it has one.#[serde(skip_serializing_if = "Option::is_none")]pub avatar_url: Option<String>,diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex ab4e889e54..e02d650d9b 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -1298,6 +1298,10 @@ async fn session_log_returns_the_sessions_frames_in_order() {"every frame is served, none folded away");assert!(!log.bot.name.is_empty(), "the response names the agent");+ assert!(+ !log.bot.handle.is_empty(),+ "the response includes the agent's handle"+ );// The order is the contract: folding is a left fold from the first frame,// so a reordered log derives different turn numbering.diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex f7e654a890..77c59a1883 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -590,11 +590,13 @@ impl AgentSessionRepo for PgAgentSessionRepo {Some(bot) => SessionBot {id,name: bot.name,+ handle: bot.handle,avatar_url: bot.avatar_url,},None => SessionBot {id,name: "Agent".to_owned(),+ handle: "agent".to_owned(),avatar_url: None,},})diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex c3cd008d28..227545a1c6 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -254,6 +254,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {Ok(SessionBot {id,name: "Test Agent".to_owned(),+ handle: "test-agent".to_owned(),avatar_url: None,})}diff --git a/crates/prompt/src/agent_identity.rs b/crates/prompt/src/agent_identity.rsnew file mode 100644index 0000000000..f033e11053--- /dev/null+++ b/crates/prompt/src/agent_identity.rs@@ -0,0 +1,16 @@+//! The agent's own display name and `@` handle.+//!+//! User-created agents are named independently of their instructions, so an+//! agent with an empty prompt still needs to know who it is. Rendered as its+//! own section so it is not mixed into the caller's instructions.++/// The identity section naming this agent.+///+/// `handle` is the stable `@` handle without a leading `@`; one is added here+/// so the model sees the mention form users type.+#[must_use]+pub fn render(name: &str, handle: &str) -> String {+ format!(+ "# Identity\nYou are {name} (@{handle}). Users mention and address you as @{handle}. When asked who you are, answer with this name and handle.\n"+ )+}diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rsindex e970c4a775..4e5161c41e 100644--- a/crates/prompt/src/agent_session.rs+++ b/crates/prompt/src/agent_session.rs@@ -4,9 +4,9 @@ use crate::types::StaticPrompt;static TITLE: &str = "Agent Sessions";-static INSTRUCTIONS: &str = r##"You are Macro's agent, working inside an agent session that was opened from a channel mention. Your replies stream back into that channel thread and also render in the session itself.+static INSTRUCTIONS: &str = r##"You are a Macro agent working inside an agent session. Your replies render in the session; when the session was opened from a channel mention they also stream back into that thread.-- Each prompt is a message from a user in the thread. Answer it directly; use your tools to look things up or act in the workspace when that is what the request needs.+- Each prompt is a message from a user. Answer it directly; use your tools to look things up or act in the workspace when that is what the request needs.- Be concise and directly useful. Respond in Markdown.- When you reference a Macro document, channel, chat, project, task, email thread, calendar event, person, date/time, agent session, or other mentionable chip, emit the matching XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex 70c6795aac..ee6cba437d 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -6,6 +6,7 @@#![deny(missing_docs)]pub mod about_macro;+pub mod agent_identity;pub mod agent_session;pub mod channel_mention;pub mod citations;@@ -232,6 +233,13 @@ mod tests {assert!(instructions.contains("\"blockName\":\"skill\""));}+ #[test]+ fn agent_identity_names_the_agent_before_the_session_preamble() {+ let identity = agent_identity::render("Grunk", "grunk");+ assert!(identity.starts_with("# Identity\n"));+ assert!(identity.contains("You are Grunk (@grunk)."));+ }+#[test]fn markdown_surface_scope_names_every_surface_but_the_reply_tone_exception() {// The mention rule must name every Markdown-authoring surface and thediff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex e41ca8caa8..b965dca9f8 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -663,6 +663,10 @@ export type SessionBot = {* Avatar, when it has one.*/avatarUrl?: string | null;+ /**+ * Stable `@` handle, without a leading `@`.+ */+ handle: string;/*** The bot's id. A message it sent has `"bot|{id}"` as its sender.*/diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 708a66c49e..ce354856a0 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -1753,12 +1753,16 @@"SessionBot": {"type": "object","description": "The agent behind a session, as much of it as rendering a message needs.",- "required": ["id", "name"],+ "required": ["id", "name", "handle"],"properties": {"avatarUrl": {"type": ["string", "null"],"description": "Avatar, when it has one."},+ "handle": {+ "type": "string",+ "description": "Stable `@` handle, without a leading `@`."+ },"id": {"$ref": "#/components/schemas/BotId","description": "The bot's id. A message it sent has `\"bot|{id}\"` as its sender."diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.tsindex cf51d2d54b..7ddfb2bf1d 100644--- a/packages/sdk/tests/agent-sessions.test.ts+++ b/packages/sdk/tests/agent-sessions.test.ts@@ -112,7 +112,10 @@ describe('AgentSession', () => {}if (request.url.endsWith('/log')) {return Response.json(- { bot: { id: session.botId, name: 'Agent' }, entries: [] },+ {+ bot: { id: session.botId, name: 'Agent', handle: 'agent' },+ entries: [],+ },{ status: 200 },);}diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rsindex 373b9365b1..05e4313caa 100644--- a/services/agent_harness_service/src/containers.rs+++ b/services/agent_harness_service/src/containers.rs@@ -13,6 +13,7 @@ use agent_harness::domain::ports::ContainerManager;use agent_harness::domain::sandbox::SandboxResizeEffect;use agent_harness::outbound::containers::{HarnessContainer, HarnessContainers};use agent_harness::outbound::sidecar::SidecarSender;+use agent_inmem::domain::engine::AgentIdentity;use agent_inmem::outbound::manager::{InMemAgentManager, SessionFacts};use agent_runtime_protocol::domain::connection::ServerChannel;use agent_runtime_protocol::domain::ports::{Transport, TransportError, TransportSender};@@ -120,10 +121,19 @@ whereif self.inmem.is_some()&& AgentKind::for_session(row.bot_id, &row.harness) == AgentKind::InMemory{+ let bot = self+ .sessions+ .session_bot(row.bot_id)+ .await+ .map_err(HarnessError::Session)?;return Ok(Route::InMem(SessionFacts {id: session,owner: row.owner_id,model: row.model,+ identity: Some(AgentIdentity {+ name: bot.name,+ handle: bot.handle,+ }),instructions: row.instructions,acp_session_id: row.acp_session_id,}));